var __defProp = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var _sessionStorage, _session;
function _mergeNamespaces(n2, m2) {
  for (var i2 = 0; i2 < m2.length; i2++) {
    const e2 = m2[i2];
    if (typeof e2 !== "string" && !Array.isArray(e2)) {
      for (const k2 in e2) {
        if (k2 !== "default" && !(k2 in n2)) {
          const d2 = Object.getOwnPropertyDescriptor(e2, k2);
          if (d2) {
            Object.defineProperty(n2, k2, d2.get ? d2 : {
              enumerable: true,
              get: () => e2[k2]
            });
          }
        }
      }
    }
  }
  return Object.freeze(Object.defineProperty(n2, Symbol.toStringTag, { value: "Module" }));
}
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var jsxRuntime = { exports: {} };
var reactJsxRuntime_production_min = {};
var react = { exports: {} };
var react_production_min = {};
/**
 * @license React
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReact_production_min;
function requireReact_production_min() {
  if (hasRequiredReact_production_min) return react_production_min;
  hasRequiredReact_production_min = 1;
  var l2 = Symbol.for("react.element"), n2 = Symbol.for("react.portal"), p2 = Symbol.for("react.fragment"), q3 = Symbol.for("react.strict_mode"), r2 = Symbol.for("react.profiler"), t2 = Symbol.for("react.provider"), u2 = Symbol.for("react.context"), v5 = Symbol.for("react.forward_ref"), w2 = Symbol.for("react.suspense"), x = Symbol.for("react.memo"), y2 = Symbol.for("react.lazy"), z2 = Symbol.iterator;
  function A2(a3) {
    if (null === a3 || "object" !== typeof a3) return null;
    a3 = z2 && a3[z2] || a3["@@iterator"];
    return "function" === typeof a3 ? a3 : null;
  }
  var B = { isMounted: function() {
    return false;
  }, enqueueForceUpdate: function() {
  }, enqueueReplaceState: function() {
  }, enqueueSetState: function() {
  } }, C2 = Object.assign, D2 = {};
  function E2(a3, b2, e2) {
    this.props = a3;
    this.context = b2;
    this.refs = D2;
    this.updater = e2 || B;
  }
  E2.prototype.isReactComponent = {};
  E2.prototype.setState = function(a3, b2) {
    if ("object" !== typeof a3 && "function" !== typeof a3 && null != a3) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
    this.updater.enqueueSetState(this, a3, b2, "setState");
  };
  E2.prototype.forceUpdate = function(a3) {
    this.updater.enqueueForceUpdate(this, a3, "forceUpdate");
  };
  function F2() {
  }
  F2.prototype = E2.prototype;
  function G2(a3, b2, e2) {
    this.props = a3;
    this.context = b2;
    this.refs = D2;
    this.updater = e2 || B;
  }
  var H2 = G2.prototype = new F2();
  H2.constructor = G2;
  C2(H2, E2.prototype);
  H2.isPureReactComponent = true;
  var I2 = Array.isArray, J2 = Object.prototype.hasOwnProperty, K2 = { current: null }, L2 = { key: true, ref: true, __self: true, __source: true };
  function M2(a3, b2, e2) {
    var d2, c2 = {}, k2 = null, h2 = null;
    if (null != b2) for (d2 in void 0 !== b2.ref && (h2 = b2.ref), void 0 !== b2.key && (k2 = "" + b2.key), b2) J2.call(b2, d2) && !L2.hasOwnProperty(d2) && (c2[d2] = b2[d2]);
    var g2 = arguments.length - 2;
    if (1 === g2) c2.children = e2;
    else if (1 < g2) {
      for (var f2 = Array(g2), m2 = 0; m2 < g2; m2++) f2[m2] = arguments[m2 + 2];
      c2.children = f2;
    }
    if (a3 && a3.defaultProps) for (d2 in g2 = a3.defaultProps, g2) void 0 === c2[d2] && (c2[d2] = g2[d2]);
    return { $$typeof: l2, type: a3, key: k2, ref: h2, props: c2, _owner: K2.current };
  }
  function N2(a3, b2) {
    return { $$typeof: l2, type: a3.type, key: b2, ref: a3.ref, props: a3.props, _owner: a3._owner };
  }
  function O2(a3) {
    return "object" === typeof a3 && null !== a3 && a3.$$typeof === l2;
  }
  function escape2(a3) {
    var b2 = { "=": "=0", ":": "=2" };
    return "$" + a3.replace(/[=:]/g, function(a4) {
      return b2[a4];
    });
  }
  var P2 = /\/+/g;
  function Q2(a3, b2) {
    return "object" === typeof a3 && null !== a3 && null != a3.key ? escape2("" + a3.key) : b2.toString(36);
  }
  function R2(a3, b2, e2, d2, c2) {
    var k2 = typeof a3;
    if ("undefined" === k2 || "boolean" === k2) a3 = null;
    var h2 = false;
    if (null === a3) h2 = true;
    else switch (k2) {
      case "string":
      case "number":
        h2 = true;
        break;
      case "object":
        switch (a3.$$typeof) {
          case l2:
          case n2:
            h2 = true;
        }
    }
    if (h2) return h2 = a3, c2 = c2(h2), a3 = "" === d2 ? "." + Q2(h2, 0) : d2, I2(c2) ? (e2 = "", null != a3 && (e2 = a3.replace(P2, "$&/") + "/"), R2(c2, b2, e2, "", function(a4) {
      return a4;
    })) : null != c2 && (O2(c2) && (c2 = N2(c2, e2 + (!c2.key || h2 && h2.key === c2.key ? "" : ("" + c2.key).replace(P2, "$&/") + "/") + a3)), b2.push(c2)), 1;
    h2 = 0;
    d2 = "" === d2 ? "." : d2 + ":";
    if (I2(a3)) for (var g2 = 0; g2 < a3.length; g2++) {
      k2 = a3[g2];
      var f2 = d2 + Q2(k2, g2);
      h2 += R2(k2, b2, e2, f2, c2);
    }
    else if (f2 = A2(a3), "function" === typeof f2) for (a3 = f2.call(a3), g2 = 0; !(k2 = a3.next()).done; ) k2 = k2.value, f2 = d2 + Q2(k2, g2++), h2 += R2(k2, b2, e2, f2, c2);
    else if ("object" === k2) throw b2 = String(a3), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b2 ? "object with keys {" + Object.keys(a3).join(", ") + "}" : b2) + "). If you meant to render a collection of children, use an array instead.");
    return h2;
  }
  function S2(a3, b2, e2) {
    if (null == a3) return a3;
    var d2 = [], c2 = 0;
    R2(a3, d2, "", "", function(a4) {
      return b2.call(e2, a4, c2++);
    });
    return d2;
  }
  function T3(a3) {
    if (-1 === a3._status) {
      var b2 = a3._result;
      b2 = b2();
      b2.then(function(b3) {
        if (0 === a3._status || -1 === a3._status) a3._status = 1, a3._result = b3;
      }, function(b3) {
        if (0 === a3._status || -1 === a3._status) a3._status = 2, a3._result = b3;
      });
      -1 === a3._status && (a3._status = 0, a3._result = b2);
    }
    if (1 === a3._status) return a3._result.default;
    throw a3._result;
  }
  var U2 = { current: null }, V2 = { transition: null }, W2 = { ReactCurrentDispatcher: U2, ReactCurrentBatchConfig: V2, ReactCurrentOwner: K2 };
  function X2() {
    throw Error("act(...) is not supported in production builds of React.");
  }
  react_production_min.Children = { map: S2, forEach: function(a3, b2, e2) {
    S2(a3, function() {
      b2.apply(this, arguments);
    }, e2);
  }, count: function(a3) {
    var b2 = 0;
    S2(a3, function() {
      b2++;
    });
    return b2;
  }, toArray: function(a3) {
    return S2(a3, function(a4) {
      return a4;
    }) || [];
  }, only: function(a3) {
    if (!O2(a3)) throw Error("React.Children.only expected to receive a single React element child.");
    return a3;
  } };
  react_production_min.Component = E2;
  react_production_min.Fragment = p2;
  react_production_min.Profiler = r2;
  react_production_min.PureComponent = G2;
  react_production_min.StrictMode = q3;
  react_production_min.Suspense = w2;
  react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W2;
  react_production_min.act = X2;
  react_production_min.cloneElement = function(a3, b2, e2) {
    if (null === a3 || void 0 === a3) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a3 + ".");
    var d2 = C2({}, a3.props), c2 = a3.key, k2 = a3.ref, h2 = a3._owner;
    if (null != b2) {
      void 0 !== b2.ref && (k2 = b2.ref, h2 = K2.current);
      void 0 !== b2.key && (c2 = "" + b2.key);
      if (a3.type && a3.type.defaultProps) var g2 = a3.type.defaultProps;
      for (f2 in b2) J2.call(b2, f2) && !L2.hasOwnProperty(f2) && (d2[f2] = void 0 === b2[f2] && void 0 !== g2 ? g2[f2] : b2[f2]);
    }
    var f2 = arguments.length - 2;
    if (1 === f2) d2.children = e2;
    else if (1 < f2) {
      g2 = Array(f2);
      for (var m2 = 0; m2 < f2; m2++) g2[m2] = arguments[m2 + 2];
      d2.children = g2;
    }
    return { $$typeof: l2, type: a3.type, key: c2, ref: k2, props: d2, _owner: h2 };
  };
  react_production_min.createContext = function(a3) {
    a3 = { $$typeof: u2, _currentValue: a3, _currentValue2: a3, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null };
    a3.Provider = { $$typeof: t2, _context: a3 };
    return a3.Consumer = a3;
  };
  react_production_min.createElement = M2;
  react_production_min.createFactory = function(a3) {
    var b2 = M2.bind(null, a3);
    b2.type = a3;
    return b2;
  };
  react_production_min.createRef = function() {
    return { current: null };
  };
  react_production_min.forwardRef = function(a3) {
    return { $$typeof: v5, render: a3 };
  };
  react_production_min.isValidElement = O2;
  react_production_min.lazy = function(a3) {
    return { $$typeof: y2, _payload: { _status: -1, _result: a3 }, _init: T3 };
  };
  react_production_min.memo = function(a3, b2) {
    return { $$typeof: x, type: a3, compare: void 0 === b2 ? null : b2 };
  };
  react_production_min.startTransition = function(a3) {
    var b2 = V2.transition;
    V2.transition = {};
    try {
      a3();
    } finally {
      V2.transition = b2;
    }
  };
  react_production_min.unstable_act = X2;
  react_production_min.useCallback = function(a3, b2) {
    return U2.current.useCallback(a3, b2);
  };
  react_production_min.useContext = function(a3) {
    return U2.current.useContext(a3);
  };
  react_production_min.useDebugValue = function() {
  };
  react_production_min.useDeferredValue = function(a3) {
    return U2.current.useDeferredValue(a3);
  };
  react_production_min.useEffect = function(a3, b2) {
    return U2.current.useEffect(a3, b2);
  };
  react_production_min.useId = function() {
    return U2.current.useId();
  };
  react_production_min.useImperativeHandle = function(a3, b2, e2) {
    return U2.current.useImperativeHandle(a3, b2, e2);
  };
  react_production_min.useInsertionEffect = function(a3, b2) {
    return U2.current.useInsertionEffect(a3, b2);
  };
  react_production_min.useLayoutEffect = function(a3, b2) {
    return U2.current.useLayoutEffect(a3, b2);
  };
  react_production_min.useMemo = function(a3, b2) {
    return U2.current.useMemo(a3, b2);
  };
  react_production_min.useReducer = function(a3, b2, e2) {
    return U2.current.useReducer(a3, b2, e2);
  };
  react_production_min.useRef = function(a3) {
    return U2.current.useRef(a3);
  };
  react_production_min.useState = function(a3) {
    return U2.current.useState(a3);
  };
  react_production_min.useSyncExternalStore = function(a3, b2, e2) {
    return U2.current.useSyncExternalStore(a3, b2, e2);
  };
  react_production_min.useTransition = function() {
    return U2.current.useTransition();
  };
  react_production_min.version = "18.3.1";
  return react_production_min;
}
var hasRequiredReact;
function requireReact() {
  if (hasRequiredReact) return react.exports;
  hasRequiredReact = 1;
  {
    react.exports = requireReact_production_min();
  }
  return react.exports;
}
/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactJsxRuntime_production_min;
function requireReactJsxRuntime_production_min() {
  if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
  hasRequiredReactJsxRuntime_production_min = 1;
  var f2 = requireReact(), k2 = Symbol.for("react.element"), l2 = Symbol.for("react.fragment"), m2 = Object.prototype.hasOwnProperty, n2 = f2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p2 = { key: true, ref: true, __self: true, __source: true };
  function q3(c2, a3, g2) {
    var b2, d2 = {}, e2 = null, h2 = null;
    void 0 !== g2 && (e2 = "" + g2);
    void 0 !== a3.key && (e2 = "" + a3.key);
    void 0 !== a3.ref && (h2 = a3.ref);
    for (b2 in a3) m2.call(a3, b2) && !p2.hasOwnProperty(b2) && (d2[b2] = a3[b2]);
    if (c2 && c2.defaultProps) for (b2 in a3 = c2.defaultProps, a3) void 0 === d2[b2] && (d2[b2] = a3[b2]);
    return { $$typeof: k2, type: c2, key: e2, ref: h2, props: d2, _owner: n2.current };
  }
  reactJsxRuntime_production_min.Fragment = l2;
  reactJsxRuntime_production_min.jsx = q3;
  reactJsxRuntime_production_min.jsxs = q3;
  return reactJsxRuntime_production_min;
}
var hasRequiredJsxRuntime;
function requireJsxRuntime() {
  if (hasRequiredJsxRuntime) return jsxRuntime.exports;
  hasRequiredJsxRuntime = 1;
  {
    jsxRuntime.exports = requireReactJsxRuntime_production_min();
  }
  return jsxRuntime.exports;
}
var jsxRuntimeExports = requireJsxRuntime();
var reactExports = requireReact();
const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports);
const t$6 = /* @__PURE__ */ _mergeNamespaces({
  __proto__: null,
  default: React
}, [reactExports]);
var reactDom = { exports: {} };
var reactDom_production_min = {};
var scheduler$1 = { exports: {} };
var scheduler_production_min$1 = {};
/**
 * @license React
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredScheduler_production_min$1;
function requireScheduler_production_min$1() {
  if (hasRequiredScheduler_production_min$1) return scheduler_production_min$1;
  hasRequiredScheduler_production_min$1 = 1;
  (function(exports$1) {
    function f2(a3, b2) {
      var c2 = a3.length;
      a3.push(b2);
      a: for (; 0 < c2; ) {
        var d2 = c2 - 1 >>> 1, e2 = a3[d2];
        if (0 < g2(e2, b2)) a3[d2] = b2, a3[c2] = e2, c2 = d2;
        else break a;
      }
    }
    function h2(a3) {
      return 0 === a3.length ? null : a3[0];
    }
    function k2(a3) {
      if (0 === a3.length) return null;
      var b2 = a3[0], c2 = a3.pop();
      if (c2 !== b2) {
        a3[0] = c2;
        a: for (var d2 = 0, e2 = a3.length, w2 = e2 >>> 1; d2 < w2; ) {
          var m2 = 2 * (d2 + 1) - 1, C2 = a3[m2], n2 = m2 + 1, x = a3[n2];
          if (0 > g2(C2, c2)) n2 < e2 && 0 > g2(x, C2) ? (a3[d2] = x, a3[n2] = c2, d2 = n2) : (a3[d2] = C2, a3[m2] = c2, d2 = m2);
          else if (n2 < e2 && 0 > g2(x, c2)) a3[d2] = x, a3[n2] = c2, d2 = n2;
          else break a;
        }
      }
      return b2;
    }
    function g2(a3, b2) {
      var c2 = a3.sortIndex - b2.sortIndex;
      return 0 !== c2 ? c2 : a3.id - b2.id;
    }
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var l2 = performance;
      exports$1.unstable_now = function() {
        return l2.now();
      };
    } else {
      var p2 = Date, q3 = p2.now();
      exports$1.unstable_now = function() {
        return p2.now() - q3;
      };
    }
    var r2 = [], t2 = [], u2 = 1, v5 = null, y2 = 3, z2 = false, A2 = false, B = false, D2 = "function" === typeof setTimeout ? setTimeout : null, E2 = "function" === typeof clearTimeout ? clearTimeout : null, F2 = "undefined" !== typeof setImmediate ? setImmediate : null;
    "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
    function G2(a3) {
      for (var b2 = h2(t2); null !== b2; ) {
        if (null === b2.callback) k2(t2);
        else if (b2.startTime <= a3) k2(t2), b2.sortIndex = b2.expirationTime, f2(r2, b2);
        else break;
        b2 = h2(t2);
      }
    }
    function H2(a3) {
      B = false;
      G2(a3);
      if (!A2) if (null !== h2(r2)) A2 = true, I2(J2);
      else {
        var b2 = h2(t2);
        null !== b2 && K2(H2, b2.startTime - a3);
      }
    }
    function J2(a3, b2) {
      A2 = false;
      B && (B = false, E2(L2), L2 = -1);
      z2 = true;
      var c2 = y2;
      try {
        G2(b2);
        for (v5 = h2(r2); null !== v5 && (!(v5.expirationTime > b2) || a3 && !M2()); ) {
          var d2 = v5.callback;
          if ("function" === typeof d2) {
            v5.callback = null;
            y2 = v5.priorityLevel;
            var e2 = d2(v5.expirationTime <= b2);
            b2 = exports$1.unstable_now();
            "function" === typeof e2 ? v5.callback = e2 : v5 === h2(r2) && k2(r2);
            G2(b2);
          } else k2(r2);
          v5 = h2(r2);
        }
        if (null !== v5) var w2 = true;
        else {
          var m2 = h2(t2);
          null !== m2 && K2(H2, m2.startTime - b2);
          w2 = false;
        }
        return w2;
      } finally {
        v5 = null, y2 = c2, z2 = false;
      }
    }
    var N2 = false, O2 = null, L2 = -1, P2 = 5, Q2 = -1;
    function M2() {
      return exports$1.unstable_now() - Q2 < P2 ? false : true;
    }
    function R2() {
      if (null !== O2) {
        var a3 = exports$1.unstable_now();
        Q2 = a3;
        var b2 = true;
        try {
          b2 = O2(true, a3);
        } finally {
          b2 ? S2() : (N2 = false, O2 = null);
        }
      } else N2 = false;
    }
    var S2;
    if ("function" === typeof F2) S2 = function() {
      F2(R2);
    };
    else if ("undefined" !== typeof MessageChannel) {
      var T3 = new MessageChannel(), U2 = T3.port2;
      T3.port1.onmessage = R2;
      S2 = function() {
        U2.postMessage(null);
      };
    } else S2 = function() {
      D2(R2, 0);
    };
    function I2(a3) {
      O2 = a3;
      N2 || (N2 = true, S2());
    }
    function K2(a3, b2) {
      L2 = D2(function() {
        a3(exports$1.unstable_now());
      }, b2);
    }
    exports$1.unstable_IdlePriority = 5;
    exports$1.unstable_ImmediatePriority = 1;
    exports$1.unstable_LowPriority = 4;
    exports$1.unstable_NormalPriority = 3;
    exports$1.unstable_Profiling = null;
    exports$1.unstable_UserBlockingPriority = 2;
    exports$1.unstable_cancelCallback = function(a3) {
      a3.callback = null;
    };
    exports$1.unstable_continueExecution = function() {
      A2 || z2 || (A2 = true, I2(J2));
    };
    exports$1.unstable_forceFrameRate = function(a3) {
      0 > a3 || 125 < a3 ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P2 = 0 < a3 ? Math.floor(1e3 / a3) : 5;
    };
    exports$1.unstable_getCurrentPriorityLevel = function() {
      return y2;
    };
    exports$1.unstable_getFirstCallbackNode = function() {
      return h2(r2);
    };
    exports$1.unstable_next = function(a3) {
      switch (y2) {
        case 1:
        case 2:
        case 3:
          var b2 = 3;
          break;
        default:
          b2 = y2;
      }
      var c2 = y2;
      y2 = b2;
      try {
        return a3();
      } finally {
        y2 = c2;
      }
    };
    exports$1.unstable_pauseExecution = function() {
    };
    exports$1.unstable_requestPaint = function() {
    };
    exports$1.unstable_runWithPriority = function(a3, b2) {
      switch (a3) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          a3 = 3;
      }
      var c2 = y2;
      y2 = a3;
      try {
        return b2();
      } finally {
        y2 = c2;
      }
    };
    exports$1.unstable_scheduleCallback = function(a3, b2, c2) {
      var d2 = exports$1.unstable_now();
      "object" === typeof c2 && null !== c2 ? (c2 = c2.delay, c2 = "number" === typeof c2 && 0 < c2 ? d2 + c2 : d2) : c2 = d2;
      switch (a3) {
        case 1:
          var e2 = -1;
          break;
        case 2:
          e2 = 250;
          break;
        case 5:
          e2 = 1073741823;
          break;
        case 4:
          e2 = 1e4;
          break;
        default:
          e2 = 5e3;
      }
      e2 = c2 + e2;
      a3 = { id: u2++, callback: b2, priorityLevel: a3, startTime: c2, expirationTime: e2, sortIndex: -1 };
      c2 > d2 ? (a3.sortIndex = c2, f2(t2, a3), null === h2(r2) && a3 === h2(t2) && (B ? (E2(L2), L2 = -1) : B = true, K2(H2, c2 - d2))) : (a3.sortIndex = e2, f2(r2, a3), A2 || z2 || (A2 = true, I2(J2)));
      return a3;
    };
    exports$1.unstable_shouldYield = M2;
    exports$1.unstable_wrapCallback = function(a3) {
      var b2 = y2;
      return function() {
        var c2 = y2;
        y2 = b2;
        try {
          return a3.apply(this, arguments);
        } finally {
          y2 = c2;
        }
      };
    };
  })(scheduler_production_min$1);
  return scheduler_production_min$1;
}
var hasRequiredScheduler$1;
function requireScheduler$1() {
  if (hasRequiredScheduler$1) return scheduler$1.exports;
  hasRequiredScheduler$1 = 1;
  {
    scheduler$1.exports = requireScheduler_production_min$1();
  }
  return scheduler$1.exports;
}
/**
 * @license React
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactDom_production_min;
function requireReactDom_production_min() {
  if (hasRequiredReactDom_production_min) return reactDom_production_min;
  hasRequiredReactDom_production_min = 1;
  var aa = requireReact(), ca = requireScheduler$1();
  function p2(a3) {
    for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a3, c2 = 1; c2 < arguments.length; c2++) b2 += "&args[]=" + encodeURIComponent(arguments[c2]);
    return "Minified React error #" + a3 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  var da2 = /* @__PURE__ */ new Set(), ea2 = {};
  function fa(a3, b2) {
    ha(a3, b2);
    ha(a3 + "Capture", b2);
  }
  function ha(a3, b2) {
    ea2[a3] = b2;
    for (a3 = 0; a3 < b2.length; a3++) da2.add(b2[a3]);
  }
  var ia = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), ja = Object.prototype.hasOwnProperty, ka = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, la2 = {}, ma = {};
  function oa(a3) {
    if (ja.call(ma, a3)) return true;
    if (ja.call(la2, a3)) return false;
    if (ka.test(a3)) return ma[a3] = true;
    la2[a3] = true;
    return false;
  }
  function pa2(a3, b2, c2, d2) {
    if (null !== c2 && 0 === c2.type) return false;
    switch (typeof b2) {
      case "function":
      case "symbol":
        return true;
      case "boolean":
        if (d2) return false;
        if (null !== c2) return !c2.acceptsBooleans;
        a3 = a3.toLowerCase().slice(0, 5);
        return "data-" !== a3 && "aria-" !== a3;
      default:
        return false;
    }
  }
  function qa(a3, b2, c2, d2) {
    if (null === b2 || "undefined" === typeof b2 || pa2(a3, b2, c2, d2)) return true;
    if (d2) return false;
    if (null !== c2) switch (c2.type) {
      case 3:
        return !b2;
      case 4:
        return false === b2;
      case 5:
        return isNaN(b2);
      case 6:
        return isNaN(b2) || 1 > b2;
    }
    return false;
  }
  function v5(a3, b2, c2, d2, e2, f2, g2) {
    this.acceptsBooleans = 2 === b2 || 3 === b2 || 4 === b2;
    this.attributeName = d2;
    this.attributeNamespace = e2;
    this.mustUseProperty = c2;
    this.propertyName = a3;
    this.type = b2;
    this.sanitizeURL = f2;
    this.removeEmptyString = g2;
  }
  var z2 = {};
  "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a3) {
    z2[a3] = new v5(a3, 0, false, a3, null, false, false);
  });
  [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a3) {
    var b2 = a3[0];
    z2[b2] = new v5(b2, 1, false, a3[1], null, false, false);
  });
  ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a3) {
    z2[a3] = new v5(a3, 2, false, a3.toLowerCase(), null, false, false);
  });
  ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a3) {
    z2[a3] = new v5(a3, 2, false, a3, null, false, false);
  });
  "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a3) {
    z2[a3] = new v5(a3, 3, false, a3.toLowerCase(), null, false, false);
  });
  ["checked", "multiple", "muted", "selected"].forEach(function(a3) {
    z2[a3] = new v5(a3, 3, true, a3, null, false, false);
  });
  ["capture", "download"].forEach(function(a3) {
    z2[a3] = new v5(a3, 4, false, a3, null, false, false);
  });
  ["cols", "rows", "size", "span"].forEach(function(a3) {
    z2[a3] = new v5(a3, 6, false, a3, null, false, false);
  });
  ["rowSpan", "start"].forEach(function(a3) {
    z2[a3] = new v5(a3, 5, false, a3.toLowerCase(), null, false, false);
  });
  var ra = /[\-:]([a-z])/g;
  function sa(a3) {
    return a3[1].toUpperCase();
  }
  "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a3) {
    var b2 = a3.replace(
      ra,
      sa
    );
    z2[b2] = new v5(b2, 1, false, a3, null, false, false);
  });
  "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a3) {
    var b2 = a3.replace(ra, sa);
    z2[b2] = new v5(b2, 1, false, a3, "http://www.w3.org/1999/xlink", false, false);
  });
  ["xml:base", "xml:lang", "xml:space"].forEach(function(a3) {
    var b2 = a3.replace(ra, sa);
    z2[b2] = new v5(b2, 1, false, a3, "http://www.w3.org/XML/1998/namespace", false, false);
  });
  ["tabIndex", "crossOrigin"].forEach(function(a3) {
    z2[a3] = new v5(a3, 1, false, a3.toLowerCase(), null, false, false);
  });
  z2.xlinkHref = new v5("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
  ["src", "href", "action", "formAction"].forEach(function(a3) {
    z2[a3] = new v5(a3, 1, false, a3.toLowerCase(), null, true, true);
  });
  function ta(a3, b2, c2, d2) {
    var e2 = z2.hasOwnProperty(b2) ? z2[b2] : null;
    if (null !== e2 ? 0 !== e2.type : d2 || !(2 < b2.length) || "o" !== b2[0] && "O" !== b2[0] || "n" !== b2[1] && "N" !== b2[1]) qa(b2, c2, e2, d2) && (c2 = null), d2 || null === e2 ? oa(b2) && (null === c2 ? a3.removeAttribute(b2) : a3.setAttribute(b2, "" + c2)) : e2.mustUseProperty ? a3[e2.propertyName] = null === c2 ? 3 === e2.type ? false : "" : c2 : (b2 = e2.attributeName, d2 = e2.attributeNamespace, null === c2 ? a3.removeAttribute(b2) : (e2 = e2.type, c2 = 3 === e2 || 4 === e2 && true === c2 ? "" : "" + c2, d2 ? a3.setAttributeNS(d2, b2, c2) : a3.setAttribute(b2, c2)));
  }
  var ua2 = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, va = Symbol.for("react.element"), wa = Symbol.for("react.portal"), ya = Symbol.for("react.fragment"), za = Symbol.for("react.strict_mode"), Aa = Symbol.for("react.profiler"), Ba = Symbol.for("react.provider"), Ca = Symbol.for("react.context"), Da = Symbol.for("react.forward_ref"), Ea = Symbol.for("react.suspense"), Fa = Symbol.for("react.suspense_list"), Ga = Symbol.for("react.memo"), Ha = Symbol.for("react.lazy");
  var Ia = Symbol.for("react.offscreen");
  var Ja = Symbol.iterator;
  function Ka(a3) {
    if (null === a3 || "object" !== typeof a3) return null;
    a3 = Ja && a3[Ja] || a3["@@iterator"];
    return "function" === typeof a3 ? a3 : null;
  }
  var A2 = Object.assign, La;
  function Ma(a3) {
    if (void 0 === La) try {
      throw Error();
    } catch (c2) {
      var b2 = c2.stack.trim().match(/\n( *(at )?)/);
      La = b2 && b2[1] || "";
    }
    return "\n" + La + a3;
  }
  var Na = false;
  function Oa(a3, b2) {
    if (!a3 || Na) return "";
    Na = true;
    var c2 = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
      if (b2) if (b2 = function() {
        throw Error();
      }, Object.defineProperty(b2.prototype, "props", { set: function() {
        throw Error();
      } }), "object" === typeof Reflect && Reflect.construct) {
        try {
          Reflect.construct(b2, []);
        } catch (l2) {
          var d2 = l2;
        }
        Reflect.construct(a3, [], b2);
      } else {
        try {
          b2.call();
        } catch (l2) {
          d2 = l2;
        }
        a3.call(b2.prototype);
      }
      else {
        try {
          throw Error();
        } catch (l2) {
          d2 = l2;
        }
        a3();
      }
    } catch (l2) {
      if (l2 && d2 && "string" === typeof l2.stack) {
        for (var e2 = l2.stack.split("\n"), f2 = d2.stack.split("\n"), g2 = e2.length - 1, h2 = f2.length - 1; 1 <= g2 && 0 <= h2 && e2[g2] !== f2[h2]; ) h2--;
        for (; 1 <= g2 && 0 <= h2; g2--, h2--) if (e2[g2] !== f2[h2]) {
          if (1 !== g2 || 1 !== h2) {
            do
              if (g2--, h2--, 0 > h2 || e2[g2] !== f2[h2]) {
                var k2 = "\n" + e2[g2].replace(" at new ", " at ");
                a3.displayName && k2.includes("<anonymous>") && (k2 = k2.replace("<anonymous>", a3.displayName));
                return k2;
              }
            while (1 <= g2 && 0 <= h2);
          }
          break;
        }
      }
    } finally {
      Na = false, Error.prepareStackTrace = c2;
    }
    return (a3 = a3 ? a3.displayName || a3.name : "") ? Ma(a3) : "";
  }
  function Pa(a3) {
    switch (a3.tag) {
      case 5:
        return Ma(a3.type);
      case 16:
        return Ma("Lazy");
      case 13:
        return Ma("Suspense");
      case 19:
        return Ma("SuspenseList");
      case 0:
      case 2:
      case 15:
        return a3 = Oa(a3.type, false), a3;
      case 11:
        return a3 = Oa(a3.type.render, false), a3;
      case 1:
        return a3 = Oa(a3.type, true), a3;
      default:
        return "";
    }
  }
  function Qa(a3) {
    if (null == a3) return null;
    if ("function" === typeof a3) return a3.displayName || a3.name || null;
    if ("string" === typeof a3) return a3;
    switch (a3) {
      case ya:
        return "Fragment";
      case wa:
        return "Portal";
      case Aa:
        return "Profiler";
      case za:
        return "StrictMode";
      case Ea:
        return "Suspense";
      case Fa:
        return "SuspenseList";
    }
    if ("object" === typeof a3) switch (a3.$$typeof) {
      case Ca:
        return (a3.displayName || "Context") + ".Consumer";
      case Ba:
        return (a3._context.displayName || "Context") + ".Provider";
      case Da:
        var b2 = a3.render;
        a3 = a3.displayName;
        a3 || (a3 = b2.displayName || b2.name || "", a3 = "" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
        return a3;
      case Ga:
        return b2 = a3.displayName || null, null !== b2 ? b2 : Qa(a3.type) || "Memo";
      case Ha:
        b2 = a3._payload;
        a3 = a3._init;
        try {
          return Qa(a3(b2));
        } catch (c2) {
        }
    }
    return null;
  }
  function Ra(a3) {
    var b2 = a3.type;
    switch (a3.tag) {
      case 24:
        return "Cache";
      case 9:
        return (b2.displayName || "Context") + ".Consumer";
      case 10:
        return (b2._context.displayName || "Context") + ".Provider";
      case 18:
        return "DehydratedFragment";
      case 11:
        return a3 = b2.render, a3 = a3.displayName || a3.name || "", b2.displayName || ("" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
      case 7:
        return "Fragment";
      case 5:
        return b2;
      case 4:
        return "Portal";
      case 3:
        return "Root";
      case 6:
        return "Text";
      case 16:
        return Qa(b2);
      case 8:
        return b2 === za ? "StrictMode" : "Mode";
      case 22:
        return "Offscreen";
      case 12:
        return "Profiler";
      case 21:
        return "Scope";
      case 13:
        return "Suspense";
      case 19:
        return "SuspenseList";
      case 25:
        return "TracingMarker";
      case 1:
      case 0:
      case 17:
      case 2:
      case 14:
      case 15:
        if ("function" === typeof b2) return b2.displayName || b2.name || null;
        if ("string" === typeof b2) return b2;
    }
    return null;
  }
  function Sa(a3) {
    switch (typeof a3) {
      case "boolean":
      case "number":
      case "string":
      case "undefined":
        return a3;
      case "object":
        return a3;
      default:
        return "";
    }
  }
  function Ta(a3) {
    var b2 = a3.type;
    return (a3 = a3.nodeName) && "input" === a3.toLowerCase() && ("checkbox" === b2 || "radio" === b2);
  }
  function Ua(a3) {
    var b2 = Ta(a3) ? "checked" : "value", c2 = Object.getOwnPropertyDescriptor(a3.constructor.prototype, b2), d2 = "" + a3[b2];
    if (!a3.hasOwnProperty(b2) && "undefined" !== typeof c2 && "function" === typeof c2.get && "function" === typeof c2.set) {
      var e2 = c2.get, f2 = c2.set;
      Object.defineProperty(a3, b2, { configurable: true, get: function() {
        return e2.call(this);
      }, set: function(a4) {
        d2 = "" + a4;
        f2.call(this, a4);
      } });
      Object.defineProperty(a3, b2, { enumerable: c2.enumerable });
      return { getValue: function() {
        return d2;
      }, setValue: function(a4) {
        d2 = "" + a4;
      }, stopTracking: function() {
        a3._valueTracker = null;
        delete a3[b2];
      } };
    }
  }
  function Va(a3) {
    a3._valueTracker || (a3._valueTracker = Ua(a3));
  }
  function Wa(a3) {
    if (!a3) return false;
    var b2 = a3._valueTracker;
    if (!b2) return true;
    var c2 = b2.getValue();
    var d2 = "";
    a3 && (d2 = Ta(a3) ? a3.checked ? "true" : "false" : a3.value);
    a3 = d2;
    return a3 !== c2 ? (b2.setValue(a3), true) : false;
  }
  function Xa(a3) {
    a3 = a3 || ("undefined" !== typeof document ? document : void 0);
    if ("undefined" === typeof a3) return null;
    try {
      return a3.activeElement || a3.body;
    } catch (b2) {
      return a3.body;
    }
  }
  function Ya(a3, b2) {
    var c2 = b2.checked;
    return A2({}, b2, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c2 ? c2 : a3._wrapperState.initialChecked });
  }
  function Za(a3, b2) {
    var c2 = null == b2.defaultValue ? "" : b2.defaultValue, d2 = null != b2.checked ? b2.checked : b2.defaultChecked;
    c2 = Sa(null != b2.value ? b2.value : c2);
    a3._wrapperState = { initialChecked: d2, initialValue: c2, controlled: "checkbox" === b2.type || "radio" === b2.type ? null != b2.checked : null != b2.value };
  }
  function ab(a3, b2) {
    b2 = b2.checked;
    null != b2 && ta(a3, "checked", b2, false);
  }
  function bb(a3, b2) {
    ab(a3, b2);
    var c2 = Sa(b2.value), d2 = b2.type;
    if (null != c2) if ("number" === d2) {
      if (0 === c2 && "" === a3.value || a3.value != c2) a3.value = "" + c2;
    } else a3.value !== "" + c2 && (a3.value = "" + c2);
    else if ("submit" === d2 || "reset" === d2) {
      a3.removeAttribute("value");
      return;
    }
    b2.hasOwnProperty("value") ? cb(a3, b2.type, c2) : b2.hasOwnProperty("defaultValue") && cb(a3, b2.type, Sa(b2.defaultValue));
    null == b2.checked && null != b2.defaultChecked && (a3.defaultChecked = !!b2.defaultChecked);
  }
  function db(a3, b2, c2) {
    if (b2.hasOwnProperty("value") || b2.hasOwnProperty("defaultValue")) {
      var d2 = b2.type;
      if (!("submit" !== d2 && "reset" !== d2 || void 0 !== b2.value && null !== b2.value)) return;
      b2 = "" + a3._wrapperState.initialValue;
      c2 || b2 === a3.value || (a3.value = b2);
      a3.defaultValue = b2;
    }
    c2 = a3.name;
    "" !== c2 && (a3.name = "");
    a3.defaultChecked = !!a3._wrapperState.initialChecked;
    "" !== c2 && (a3.name = c2);
  }
  function cb(a3, b2, c2) {
    if ("number" !== b2 || Xa(a3.ownerDocument) !== a3) null == c2 ? a3.defaultValue = "" + a3._wrapperState.initialValue : a3.defaultValue !== "" + c2 && (a3.defaultValue = "" + c2);
  }
  var eb = Array.isArray;
  function fb(a3, b2, c2, d2) {
    a3 = a3.options;
    if (b2) {
      b2 = {};
      for (var e2 = 0; e2 < c2.length; e2++) b2["$" + c2[e2]] = true;
      for (c2 = 0; c2 < a3.length; c2++) e2 = b2.hasOwnProperty("$" + a3[c2].value), a3[c2].selected !== e2 && (a3[c2].selected = e2), e2 && d2 && (a3[c2].defaultSelected = true);
    } else {
      c2 = "" + Sa(c2);
      b2 = null;
      for (e2 = 0; e2 < a3.length; e2++) {
        if (a3[e2].value === c2) {
          a3[e2].selected = true;
          d2 && (a3[e2].defaultSelected = true);
          return;
        }
        null !== b2 || a3[e2].disabled || (b2 = a3[e2]);
      }
      null !== b2 && (b2.selected = true);
    }
  }
  function gb(a3, b2) {
    if (null != b2.dangerouslySetInnerHTML) throw Error(p2(91));
    return A2({}, b2, { value: void 0, defaultValue: void 0, children: "" + a3._wrapperState.initialValue });
  }
  function hb(a3, b2) {
    var c2 = b2.value;
    if (null == c2) {
      c2 = b2.children;
      b2 = b2.defaultValue;
      if (null != c2) {
        if (null != b2) throw Error(p2(92));
        if (eb(c2)) {
          if (1 < c2.length) throw Error(p2(93));
          c2 = c2[0];
        }
        b2 = c2;
      }
      null == b2 && (b2 = "");
      c2 = b2;
    }
    a3._wrapperState = { initialValue: Sa(c2) };
  }
  function ib(a3, b2) {
    var c2 = Sa(b2.value), d2 = Sa(b2.defaultValue);
    null != c2 && (c2 = "" + c2, c2 !== a3.value && (a3.value = c2), null == b2.defaultValue && a3.defaultValue !== c2 && (a3.defaultValue = c2));
    null != d2 && (a3.defaultValue = "" + d2);
  }
  function jb(a3) {
    var b2 = a3.textContent;
    b2 === a3._wrapperState.initialValue && "" !== b2 && null !== b2 && (a3.value = b2);
  }
  function kb(a3) {
    switch (a3) {
      case "svg":
        return "http://www.w3.org/2000/svg";
      case "math":
        return "http://www.w3.org/1998/Math/MathML";
      default:
        return "http://www.w3.org/1999/xhtml";
    }
  }
  function lb(a3, b2) {
    return null == a3 || "http://www.w3.org/1999/xhtml" === a3 ? kb(b2) : "http://www.w3.org/2000/svg" === a3 && "foreignObject" === b2 ? "http://www.w3.org/1999/xhtml" : a3;
  }
  var mb, nb = (function(a3) {
    return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b2, c2, d2, e2) {
      MSApp.execUnsafeLocalFunction(function() {
        return a3(b2, c2, d2, e2);
      });
    } : a3;
  })(function(a3, b2) {
    if ("http://www.w3.org/2000/svg" !== a3.namespaceURI || "innerHTML" in a3) a3.innerHTML = b2;
    else {
      mb = mb || document.createElement("div");
      mb.innerHTML = "<svg>" + b2.valueOf().toString() + "</svg>";
      for (b2 = mb.firstChild; a3.firstChild; ) a3.removeChild(a3.firstChild);
      for (; b2.firstChild; ) a3.appendChild(b2.firstChild);
    }
  });
  function ob(a3, b2) {
    if (b2) {
      var c2 = a3.firstChild;
      if (c2 && c2 === a3.lastChild && 3 === c2.nodeType) {
        c2.nodeValue = b2;
        return;
      }
    }
    a3.textContent = b2;
  }
  var pb = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  }, qb = ["Webkit", "ms", "Moz", "O"];
  Object.keys(pb).forEach(function(a3) {
    qb.forEach(function(b2) {
      b2 = b2 + a3.charAt(0).toUpperCase() + a3.substring(1);
      pb[b2] = pb[a3];
    });
  });
  function rb(a3, b2, c2) {
    return null == b2 || "boolean" === typeof b2 || "" === b2 ? "" : c2 || "number" !== typeof b2 || 0 === b2 || pb.hasOwnProperty(a3) && pb[a3] ? ("" + b2).trim() : b2 + "px";
  }
  function sb(a3, b2) {
    a3 = a3.style;
    for (var c2 in b2) if (b2.hasOwnProperty(c2)) {
      var d2 = 0 === c2.indexOf("--"), e2 = rb(c2, b2[c2], d2);
      "float" === c2 && (c2 = "cssFloat");
      d2 ? a3.setProperty(c2, e2) : a3[c2] = e2;
    }
  }
  var tb = A2({ menuitem: true }, { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true });
  function ub(a3, b2) {
    if (b2) {
      if (tb[a3] && (null != b2.children || null != b2.dangerouslySetInnerHTML)) throw Error(p2(137, a3));
      if (null != b2.dangerouslySetInnerHTML) {
        if (null != b2.children) throw Error(p2(60));
        if ("object" !== typeof b2.dangerouslySetInnerHTML || !("__html" in b2.dangerouslySetInnerHTML)) throw Error(p2(61));
      }
      if (null != b2.style && "object" !== typeof b2.style) throw Error(p2(62));
    }
  }
  function vb(a3, b2) {
    if (-1 === a3.indexOf("-")) return "string" === typeof b2.is;
    switch (a3) {
      case "annotation-xml":
      case "color-profile":
      case "font-face":
      case "font-face-src":
      case "font-face-uri":
      case "font-face-format":
      case "font-face-name":
      case "missing-glyph":
        return false;
      default:
        return true;
    }
  }
  var wb = null;
  function xb(a3) {
    a3 = a3.target || a3.srcElement || window;
    a3.correspondingUseElement && (a3 = a3.correspondingUseElement);
    return 3 === a3.nodeType ? a3.parentNode : a3;
  }
  var yb = null, zb = null, Ab = null;
  function Bb(a3) {
    if (a3 = Cb(a3)) {
      if ("function" !== typeof yb) throw Error(p2(280));
      var b2 = a3.stateNode;
      b2 && (b2 = Db(b2), yb(a3.stateNode, a3.type, b2));
    }
  }
  function Eb(a3) {
    zb ? Ab ? Ab.push(a3) : Ab = [a3] : zb = a3;
  }
  function Fb() {
    if (zb) {
      var a3 = zb, b2 = Ab;
      Ab = zb = null;
      Bb(a3);
      if (b2) for (a3 = 0; a3 < b2.length; a3++) Bb(b2[a3]);
    }
  }
  function Gb(a3, b2) {
    return a3(b2);
  }
  function Hb() {
  }
  var Ib = false;
  function Jb(a3, b2, c2) {
    if (Ib) return a3(b2, c2);
    Ib = true;
    try {
      return Gb(a3, b2, c2);
    } finally {
      if (Ib = false, null !== zb || null !== Ab) Hb(), Fb();
    }
  }
  function Kb(a3, b2) {
    var c2 = a3.stateNode;
    if (null === c2) return null;
    var d2 = Db(c2);
    if (null === d2) return null;
    c2 = d2[b2];
    a: switch (b2) {
      case "onClick":
      case "onClickCapture":
      case "onDoubleClick":
      case "onDoubleClickCapture":
      case "onMouseDown":
      case "onMouseDownCapture":
      case "onMouseMove":
      case "onMouseMoveCapture":
      case "onMouseUp":
      case "onMouseUpCapture":
      case "onMouseEnter":
        (d2 = !d2.disabled) || (a3 = a3.type, d2 = !("button" === a3 || "input" === a3 || "select" === a3 || "textarea" === a3));
        a3 = !d2;
        break a;
      default:
        a3 = false;
    }
    if (a3) return null;
    if (c2 && "function" !== typeof c2) throw Error(p2(231, b2, typeof c2));
    return c2;
  }
  var Lb = false;
  if (ia) try {
    var Mb = {};
    Object.defineProperty(Mb, "passive", { get: function() {
      Lb = true;
    } });
    window.addEventListener("test", Mb, Mb);
    window.removeEventListener("test", Mb, Mb);
  } catch (a3) {
    Lb = false;
  }
  function Nb(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
    var l2 = Array.prototype.slice.call(arguments, 3);
    try {
      b2.apply(c2, l2);
    } catch (m2) {
      this.onError(m2);
    }
  }
  var Ob = false, Pb = null, Qb = false, Rb = null, Sb = { onError: function(a3) {
    Ob = true;
    Pb = a3;
  } };
  function Tb(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
    Ob = false;
    Pb = null;
    Nb.apply(Sb, arguments);
  }
  function Ub(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
    Tb.apply(this, arguments);
    if (Ob) {
      if (Ob) {
        var l2 = Pb;
        Ob = false;
        Pb = null;
      } else throw Error(p2(198));
      Qb || (Qb = true, Rb = l2);
    }
  }
  function Vb(a3) {
    var b2 = a3, c2 = a3;
    if (a3.alternate) for (; b2.return; ) b2 = b2.return;
    else {
      a3 = b2;
      do
        b2 = a3, 0 !== (b2.flags & 4098) && (c2 = b2.return), a3 = b2.return;
      while (a3);
    }
    return 3 === b2.tag ? c2 : null;
  }
  function Wb(a3) {
    if (13 === a3.tag) {
      var b2 = a3.memoizedState;
      null === b2 && (a3 = a3.alternate, null !== a3 && (b2 = a3.memoizedState));
      if (null !== b2) return b2.dehydrated;
    }
    return null;
  }
  function Xb(a3) {
    if (Vb(a3) !== a3) throw Error(p2(188));
  }
  function Yb(a3) {
    var b2 = a3.alternate;
    if (!b2) {
      b2 = Vb(a3);
      if (null === b2) throw Error(p2(188));
      return b2 !== a3 ? null : a3;
    }
    for (var c2 = a3, d2 = b2; ; ) {
      var e2 = c2.return;
      if (null === e2) break;
      var f2 = e2.alternate;
      if (null === f2) {
        d2 = e2.return;
        if (null !== d2) {
          c2 = d2;
          continue;
        }
        break;
      }
      if (e2.child === f2.child) {
        for (f2 = e2.child; f2; ) {
          if (f2 === c2) return Xb(e2), a3;
          if (f2 === d2) return Xb(e2), b2;
          f2 = f2.sibling;
        }
        throw Error(p2(188));
      }
      if (c2.return !== d2.return) c2 = e2, d2 = f2;
      else {
        for (var g2 = false, h2 = e2.child; h2; ) {
          if (h2 === c2) {
            g2 = true;
            c2 = e2;
            d2 = f2;
            break;
          }
          if (h2 === d2) {
            g2 = true;
            d2 = e2;
            c2 = f2;
            break;
          }
          h2 = h2.sibling;
        }
        if (!g2) {
          for (h2 = f2.child; h2; ) {
            if (h2 === c2) {
              g2 = true;
              c2 = f2;
              d2 = e2;
              break;
            }
            if (h2 === d2) {
              g2 = true;
              d2 = f2;
              c2 = e2;
              break;
            }
            h2 = h2.sibling;
          }
          if (!g2) throw Error(p2(189));
        }
      }
      if (c2.alternate !== d2) throw Error(p2(190));
    }
    if (3 !== c2.tag) throw Error(p2(188));
    return c2.stateNode.current === c2 ? a3 : b2;
  }
  function Zb(a3) {
    a3 = Yb(a3);
    return null !== a3 ? $b(a3) : null;
  }
  function $b(a3) {
    if (5 === a3.tag || 6 === a3.tag) return a3;
    for (a3 = a3.child; null !== a3; ) {
      var b2 = $b(a3);
      if (null !== b2) return b2;
      a3 = a3.sibling;
    }
    return null;
  }
  var ac = ca.unstable_scheduleCallback, bc = ca.unstable_cancelCallback, cc = ca.unstable_shouldYield, dc = ca.unstable_requestPaint, B = ca.unstable_now, ec = ca.unstable_getCurrentPriorityLevel, fc = ca.unstable_ImmediatePriority, gc = ca.unstable_UserBlockingPriority, hc = ca.unstable_NormalPriority, ic = ca.unstable_LowPriority, jc = ca.unstable_IdlePriority, kc = null, lc = null;
  function mc(a3) {
    if (lc && "function" === typeof lc.onCommitFiberRoot) try {
      lc.onCommitFiberRoot(kc, a3, void 0, 128 === (a3.current.flags & 128));
    } catch (b2) {
    }
  }
  var oc = Math.clz32 ? Math.clz32 : nc, pc = Math.log, qc = Math.LN2;
  function nc(a3) {
    a3 >>>= 0;
    return 0 === a3 ? 32 : 31 - (pc(a3) / qc | 0) | 0;
  }
  var rc = 64, sc = 4194304;
  function tc(a3) {
    switch (a3 & -a3) {
      case 1:
        return 1;
      case 2:
        return 2;
      case 4:
        return 4;
      case 8:
        return 8;
      case 16:
        return 16;
      case 32:
        return 32;
      case 64:
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return a3 & 4194240;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
      case 67108864:
        return a3 & 130023424;
      case 134217728:
        return 134217728;
      case 268435456:
        return 268435456;
      case 536870912:
        return 536870912;
      case 1073741824:
        return 1073741824;
      default:
        return a3;
    }
  }
  function uc(a3, b2) {
    var c2 = a3.pendingLanes;
    if (0 === c2) return 0;
    var d2 = 0, e2 = a3.suspendedLanes, f2 = a3.pingedLanes, g2 = c2 & 268435455;
    if (0 !== g2) {
      var h2 = g2 & ~e2;
      0 !== h2 ? d2 = tc(h2) : (f2 &= g2, 0 !== f2 && (d2 = tc(f2)));
    } else g2 = c2 & ~e2, 0 !== g2 ? d2 = tc(g2) : 0 !== f2 && (d2 = tc(f2));
    if (0 === d2) return 0;
    if (0 !== b2 && b2 !== d2 && 0 === (b2 & e2) && (e2 = d2 & -d2, f2 = b2 & -b2, e2 >= f2 || 16 === e2 && 0 !== (f2 & 4194240))) return b2;
    0 !== (d2 & 4) && (d2 |= c2 & 16);
    b2 = a3.entangledLanes;
    if (0 !== b2) for (a3 = a3.entanglements, b2 &= d2; 0 < b2; ) c2 = 31 - oc(b2), e2 = 1 << c2, d2 |= a3[c2], b2 &= ~e2;
    return d2;
  }
  function vc(a3, b2) {
    switch (a3) {
      case 1:
      case 2:
      case 4:
        return b2 + 250;
      case 8:
      case 16:
      case 32:
      case 64:
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return b2 + 5e3;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
      case 67108864:
        return -1;
      case 134217728:
      case 268435456:
      case 536870912:
      case 1073741824:
        return -1;
      default:
        return -1;
    }
  }
  function wc(a3, b2) {
    for (var c2 = a3.suspendedLanes, d2 = a3.pingedLanes, e2 = a3.expirationTimes, f2 = a3.pendingLanes; 0 < f2; ) {
      var g2 = 31 - oc(f2), h2 = 1 << g2, k2 = e2[g2];
      if (-1 === k2) {
        if (0 === (h2 & c2) || 0 !== (h2 & d2)) e2[g2] = vc(h2, b2);
      } else k2 <= b2 && (a3.expiredLanes |= h2);
      f2 &= ~h2;
    }
  }
  function xc(a3) {
    a3 = a3.pendingLanes & -1073741825;
    return 0 !== a3 ? a3 : a3 & 1073741824 ? 1073741824 : 0;
  }
  function yc() {
    var a3 = rc;
    rc <<= 1;
    0 === (rc & 4194240) && (rc = 64);
    return a3;
  }
  function zc(a3) {
    for (var b2 = [], c2 = 0; 31 > c2; c2++) b2.push(a3);
    return b2;
  }
  function Ac(a3, b2, c2) {
    a3.pendingLanes |= b2;
    536870912 !== b2 && (a3.suspendedLanes = 0, a3.pingedLanes = 0);
    a3 = a3.eventTimes;
    b2 = 31 - oc(b2);
    a3[b2] = c2;
  }
  function Bc(a3, b2) {
    var c2 = a3.pendingLanes & ~b2;
    a3.pendingLanes = b2;
    a3.suspendedLanes = 0;
    a3.pingedLanes = 0;
    a3.expiredLanes &= b2;
    a3.mutableReadLanes &= b2;
    a3.entangledLanes &= b2;
    b2 = a3.entanglements;
    var d2 = a3.eventTimes;
    for (a3 = a3.expirationTimes; 0 < c2; ) {
      var e2 = 31 - oc(c2), f2 = 1 << e2;
      b2[e2] = 0;
      d2[e2] = -1;
      a3[e2] = -1;
      c2 &= ~f2;
    }
  }
  function Cc(a3, b2) {
    var c2 = a3.entangledLanes |= b2;
    for (a3 = a3.entanglements; c2; ) {
      var d2 = 31 - oc(c2), e2 = 1 << d2;
      e2 & b2 | a3[d2] & b2 && (a3[d2] |= b2);
      c2 &= ~e2;
    }
  }
  var C2 = 0;
  function Dc(a3) {
    a3 &= -a3;
    return 1 < a3 ? 4 < a3 ? 0 !== (a3 & 268435455) ? 16 : 536870912 : 4 : 1;
  }
  var Ec, Fc, Gc, Hc, Ic, Jc = false, Kc = [], Lc = null, Mc = null, Nc = null, Oc = /* @__PURE__ */ new Map(), Pc = /* @__PURE__ */ new Map(), Qc = [], Rc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
  function Sc(a3, b2) {
    switch (a3) {
      case "focusin":
      case "focusout":
        Lc = null;
        break;
      case "dragenter":
      case "dragleave":
        Mc = null;
        break;
      case "mouseover":
      case "mouseout":
        Nc = null;
        break;
      case "pointerover":
      case "pointerout":
        Oc.delete(b2.pointerId);
        break;
      case "gotpointercapture":
      case "lostpointercapture":
        Pc.delete(b2.pointerId);
    }
  }
  function Tc(a3, b2, c2, d2, e2, f2) {
    if (null === a3 || a3.nativeEvent !== f2) return a3 = { blockedOn: b2, domEventName: c2, eventSystemFlags: d2, nativeEvent: f2, targetContainers: [e2] }, null !== b2 && (b2 = Cb(b2), null !== b2 && Fc(b2)), a3;
    a3.eventSystemFlags |= d2;
    b2 = a3.targetContainers;
    null !== e2 && -1 === b2.indexOf(e2) && b2.push(e2);
    return a3;
  }
  function Uc(a3, b2, c2, d2, e2) {
    switch (b2) {
      case "focusin":
        return Lc = Tc(Lc, a3, b2, c2, d2, e2), true;
      case "dragenter":
        return Mc = Tc(Mc, a3, b2, c2, d2, e2), true;
      case "mouseover":
        return Nc = Tc(Nc, a3, b2, c2, d2, e2), true;
      case "pointerover":
        var f2 = e2.pointerId;
        Oc.set(f2, Tc(Oc.get(f2) || null, a3, b2, c2, d2, e2));
        return true;
      case "gotpointercapture":
        return f2 = e2.pointerId, Pc.set(f2, Tc(Pc.get(f2) || null, a3, b2, c2, d2, e2)), true;
    }
    return false;
  }
  function Vc(a3) {
    var b2 = Wc(a3.target);
    if (null !== b2) {
      var c2 = Vb(b2);
      if (null !== c2) {
        if (b2 = c2.tag, 13 === b2) {
          if (b2 = Wb(c2), null !== b2) {
            a3.blockedOn = b2;
            Ic(a3.priority, function() {
              Gc(c2);
            });
            return;
          }
        } else if (3 === b2 && c2.stateNode.current.memoizedState.isDehydrated) {
          a3.blockedOn = 3 === c2.tag ? c2.stateNode.containerInfo : null;
          return;
        }
      }
    }
    a3.blockedOn = null;
  }
  function Xc(a3) {
    if (null !== a3.blockedOn) return false;
    for (var b2 = a3.targetContainers; 0 < b2.length; ) {
      var c2 = Yc(a3.domEventName, a3.eventSystemFlags, b2[0], a3.nativeEvent);
      if (null === c2) {
        c2 = a3.nativeEvent;
        var d2 = new c2.constructor(c2.type, c2);
        wb = d2;
        c2.target.dispatchEvent(d2);
        wb = null;
      } else return b2 = Cb(c2), null !== b2 && Fc(b2), a3.blockedOn = c2, false;
      b2.shift();
    }
    return true;
  }
  function Zc(a3, b2, c2) {
    Xc(a3) && c2.delete(b2);
  }
  function $c() {
    Jc = false;
    null !== Lc && Xc(Lc) && (Lc = null);
    null !== Mc && Xc(Mc) && (Mc = null);
    null !== Nc && Xc(Nc) && (Nc = null);
    Oc.forEach(Zc);
    Pc.forEach(Zc);
  }
  function ad(a3, b2) {
    a3.blockedOn === b2 && (a3.blockedOn = null, Jc || (Jc = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c)));
  }
  function bd(a3) {
    function b2(b3) {
      return ad(b3, a3);
    }
    if (0 < Kc.length) {
      ad(Kc[0], a3);
      for (var c2 = 1; c2 < Kc.length; c2++) {
        var d2 = Kc[c2];
        d2.blockedOn === a3 && (d2.blockedOn = null);
      }
    }
    null !== Lc && ad(Lc, a3);
    null !== Mc && ad(Mc, a3);
    null !== Nc && ad(Nc, a3);
    Oc.forEach(b2);
    Pc.forEach(b2);
    for (c2 = 0; c2 < Qc.length; c2++) d2 = Qc[c2], d2.blockedOn === a3 && (d2.blockedOn = null);
    for (; 0 < Qc.length && (c2 = Qc[0], null === c2.blockedOn); ) Vc(c2), null === c2.blockedOn && Qc.shift();
  }
  var cd = ua2.ReactCurrentBatchConfig, dd = true;
  function ed(a3, b2, c2, d2) {
    var e2 = C2, f2 = cd.transition;
    cd.transition = null;
    try {
      C2 = 1, fd2(a3, b2, c2, d2);
    } finally {
      C2 = e2, cd.transition = f2;
    }
  }
  function gd(a3, b2, c2, d2) {
    var e2 = C2, f2 = cd.transition;
    cd.transition = null;
    try {
      C2 = 4, fd2(a3, b2, c2, d2);
    } finally {
      C2 = e2, cd.transition = f2;
    }
  }
  function fd2(a3, b2, c2, d2) {
    if (dd) {
      var e2 = Yc(a3, b2, c2, d2);
      if (null === e2) hd(a3, b2, d2, id, c2), Sc(a3, d2);
      else if (Uc(e2, a3, b2, c2, d2)) d2.stopPropagation();
      else if (Sc(a3, d2), b2 & 4 && -1 < Rc.indexOf(a3)) {
        for (; null !== e2; ) {
          var f2 = Cb(e2);
          null !== f2 && Ec(f2);
          f2 = Yc(a3, b2, c2, d2);
          null === f2 && hd(a3, b2, d2, id, c2);
          if (f2 === e2) break;
          e2 = f2;
        }
        null !== e2 && d2.stopPropagation();
      } else hd(a3, b2, d2, null, c2);
    }
  }
  var id = null;
  function Yc(a3, b2, c2, d2) {
    id = null;
    a3 = xb(d2);
    a3 = Wc(a3);
    if (null !== a3) if (b2 = Vb(a3), null === b2) a3 = null;
    else if (c2 = b2.tag, 13 === c2) {
      a3 = Wb(b2);
      if (null !== a3) return a3;
      a3 = null;
    } else if (3 === c2) {
      if (b2.stateNode.current.memoizedState.isDehydrated) return 3 === b2.tag ? b2.stateNode.containerInfo : null;
      a3 = null;
    } else b2 !== a3 && (a3 = null);
    id = a3;
    return null;
  }
  function jd(a3) {
    switch (a3) {
      case "cancel":
      case "click":
      case "close":
      case "contextmenu":
      case "copy":
      case "cut":
      case "auxclick":
      case "dblclick":
      case "dragend":
      case "dragstart":
      case "drop":
      case "focusin":
      case "focusout":
      case "input":
      case "invalid":
      case "keydown":
      case "keypress":
      case "keyup":
      case "mousedown":
      case "mouseup":
      case "paste":
      case "pause":
      case "play":
      case "pointercancel":
      case "pointerdown":
      case "pointerup":
      case "ratechange":
      case "reset":
      case "resize":
      case "seeked":
      case "submit":
      case "touchcancel":
      case "touchend":
      case "touchstart":
      case "volumechange":
      case "change":
      case "selectionchange":
      case "textInput":
      case "compositionstart":
      case "compositionend":
      case "compositionupdate":
      case "beforeblur":
      case "afterblur":
      case "beforeinput":
      case "blur":
      case "fullscreenchange":
      case "focus":
      case "hashchange":
      case "popstate":
      case "select":
      case "selectstart":
        return 1;
      case "drag":
      case "dragenter":
      case "dragexit":
      case "dragleave":
      case "dragover":
      case "mousemove":
      case "mouseout":
      case "mouseover":
      case "pointermove":
      case "pointerout":
      case "pointerover":
      case "scroll":
      case "toggle":
      case "touchmove":
      case "wheel":
      case "mouseenter":
      case "mouseleave":
      case "pointerenter":
      case "pointerleave":
        return 4;
      case "message":
        switch (ec()) {
          case fc:
            return 1;
          case gc:
            return 4;
          case hc:
          case ic:
            return 16;
          case jc:
            return 536870912;
          default:
            return 16;
        }
      default:
        return 16;
    }
  }
  var kd = null, ld = null, md = null;
  function nd() {
    if (md) return md;
    var a3, b2 = ld, c2 = b2.length, d2, e2 = "value" in kd ? kd.value : kd.textContent, f2 = e2.length;
    for (a3 = 0; a3 < c2 && b2[a3] === e2[a3]; a3++) ;
    var g2 = c2 - a3;
    for (d2 = 1; d2 <= g2 && b2[c2 - d2] === e2[f2 - d2]; d2++) ;
    return md = e2.slice(a3, 1 < d2 ? 1 - d2 : void 0);
  }
  function od(a3) {
    var b2 = a3.keyCode;
    "charCode" in a3 ? (a3 = a3.charCode, 0 === a3 && 13 === b2 && (a3 = 13)) : a3 = b2;
    10 === a3 && (a3 = 13);
    return 32 <= a3 || 13 === a3 ? a3 : 0;
  }
  function pd() {
    return true;
  }
  function qd() {
    return false;
  }
  function rd(a3) {
    function b2(b3, d2, e2, f2, g2) {
      this._reactName = b3;
      this._targetInst = e2;
      this.type = d2;
      this.nativeEvent = f2;
      this.target = g2;
      this.currentTarget = null;
      for (var c2 in a3) a3.hasOwnProperty(c2) && (b3 = a3[c2], this[c2] = b3 ? b3(f2) : f2[c2]);
      this.isDefaultPrevented = (null != f2.defaultPrevented ? f2.defaultPrevented : false === f2.returnValue) ? pd : qd;
      this.isPropagationStopped = qd;
      return this;
    }
    A2(b2.prototype, { preventDefault: function() {
      this.defaultPrevented = true;
      var a4 = this.nativeEvent;
      a4 && (a4.preventDefault ? a4.preventDefault() : "unknown" !== typeof a4.returnValue && (a4.returnValue = false), this.isDefaultPrevented = pd);
    }, stopPropagation: function() {
      var a4 = this.nativeEvent;
      a4 && (a4.stopPropagation ? a4.stopPropagation() : "unknown" !== typeof a4.cancelBubble && (a4.cancelBubble = true), this.isPropagationStopped = pd);
    }, persist: function() {
    }, isPersistent: pd });
    return b2;
  }
  var sd = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a3) {
    return a3.timeStamp || Date.now();
  }, defaultPrevented: 0, isTrusted: 0 }, td2 = rd(sd), ud = A2({}, sd, { view: 0, detail: 0 }), vd = rd(ud), wd, xd, yd, Ad = A2({}, ud, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a3) {
    return void 0 === a3.relatedTarget ? a3.fromElement === a3.srcElement ? a3.toElement : a3.fromElement : a3.relatedTarget;
  }, movementX: function(a3) {
    if ("movementX" in a3) return a3.movementX;
    a3 !== yd && (yd && "mousemove" === a3.type ? (wd = a3.screenX - yd.screenX, xd = a3.screenY - yd.screenY) : xd = wd = 0, yd = a3);
    return wd;
  }, movementY: function(a3) {
    return "movementY" in a3 ? a3.movementY : xd;
  } }), Bd = rd(Ad), Cd = A2({}, Ad, { dataTransfer: 0 }), Dd = rd(Cd), Ed = A2({}, ud, { relatedTarget: 0 }), Fd = rd(Ed), Gd = A2({}, sd, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }), Hd = rd(Gd), Id = A2({}, sd, { clipboardData: function(a3) {
    return "clipboardData" in a3 ? a3.clipboardData : window.clipboardData;
  } }), Jd = rd(Id), Kd = A2({}, sd, { data: 0 }), Ld = rd(Kd), Md = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
  }, Nd = {
    8: "Backspace",
    9: "Tab",
    12: "Clear",
    13: "Enter",
    16: "Shift",
    17: "Control",
    18: "Alt",
    19: "Pause",
    20: "CapsLock",
    27: "Escape",
    32: " ",
    33: "PageUp",
    34: "PageDown",
    35: "End",
    36: "Home",
    37: "ArrowLeft",
    38: "ArrowUp",
    39: "ArrowRight",
    40: "ArrowDown",
    45: "Insert",
    46: "Delete",
    112: "F1",
    113: "F2",
    114: "F3",
    115: "F4",
    116: "F5",
    117: "F6",
    118: "F7",
    119: "F8",
    120: "F9",
    121: "F10",
    122: "F11",
    123: "F12",
    144: "NumLock",
    145: "ScrollLock",
    224: "Meta"
  }, Od = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" };
  function Pd(a3) {
    var b2 = this.nativeEvent;
    return b2.getModifierState ? b2.getModifierState(a3) : (a3 = Od[a3]) ? !!b2[a3] : false;
  }
  function zd() {
    return Pd;
  }
  var Qd = A2({}, ud, { key: function(a3) {
    if (a3.key) {
      var b2 = Md[a3.key] || a3.key;
      if ("Unidentified" !== b2) return b2;
    }
    return "keypress" === a3.type ? (a3 = od(a3), 13 === a3 ? "Enter" : String.fromCharCode(a3)) : "keydown" === a3.type || "keyup" === a3.type ? Nd[a3.keyCode] || "Unidentified" : "";
  }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a3) {
    return "keypress" === a3.type ? od(a3) : 0;
  }, keyCode: function(a3) {
    return "keydown" === a3.type || "keyup" === a3.type ? a3.keyCode : 0;
  }, which: function(a3) {
    return "keypress" === a3.type ? od(a3) : "keydown" === a3.type || "keyup" === a3.type ? a3.keyCode : 0;
  } }), Rd = rd(Qd), Sd = A2({}, Ad, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }), Td = rd(Sd), Ud = A2({}, ud, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd }), Vd = rd(Ud), Wd = A2({}, sd, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }), Xd = rd(Wd), Yd = A2({}, Ad, {
    deltaX: function(a3) {
      return "deltaX" in a3 ? a3.deltaX : "wheelDeltaX" in a3 ? -a3.wheelDeltaX : 0;
    },
    deltaY: function(a3) {
      return "deltaY" in a3 ? a3.deltaY : "wheelDeltaY" in a3 ? -a3.wheelDeltaY : "wheelDelta" in a3 ? -a3.wheelDelta : 0;
    },
    deltaZ: 0,
    deltaMode: 0
  }), Zd = rd(Yd), $d = [9, 13, 27, 32], ae = ia && "CompositionEvent" in window, be2 = null;
  ia && "documentMode" in document && (be2 = document.documentMode);
  var ce2 = ia && "TextEvent" in window && !be2, de2 = ia && (!ae || be2 && 8 < be2 && 11 >= be2), ee2 = String.fromCharCode(32), fe2 = false;
  function ge2(a3, b2) {
    switch (a3) {
      case "keyup":
        return -1 !== $d.indexOf(b2.keyCode);
      case "keydown":
        return 229 !== b2.keyCode;
      case "keypress":
      case "mousedown":
      case "focusout":
        return true;
      default:
        return false;
    }
  }
  function he2(a3) {
    a3 = a3.detail;
    return "object" === typeof a3 && "data" in a3 ? a3.data : null;
  }
  var ie = false;
  function je2(a3, b2) {
    switch (a3) {
      case "compositionend":
        return he2(b2);
      case "keypress":
        if (32 !== b2.which) return null;
        fe2 = true;
        return ee2;
      case "textInput":
        return a3 = b2.data, a3 === ee2 && fe2 ? null : a3;
      default:
        return null;
    }
  }
  function ke2(a3, b2) {
    if (ie) return "compositionend" === a3 || !ae && ge2(a3, b2) ? (a3 = nd(), md = ld = kd = null, ie = false, a3) : null;
    switch (a3) {
      case "paste":
        return null;
      case "keypress":
        if (!(b2.ctrlKey || b2.altKey || b2.metaKey) || b2.ctrlKey && b2.altKey) {
          if (b2.char && 1 < b2.char.length) return b2.char;
          if (b2.which) return String.fromCharCode(b2.which);
        }
        return null;
      case "compositionend":
        return de2 && "ko" !== b2.locale ? null : b2.data;
      default:
        return null;
    }
  }
  var le2 = { color: true, date: true, datetime: true, "datetime-local": true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true };
  function me2(a3) {
    var b2 = a3 && a3.nodeName && a3.nodeName.toLowerCase();
    return "input" === b2 ? !!le2[a3.type] : "textarea" === b2 ? true : false;
  }
  function ne2(a3, b2, c2, d2) {
    Eb(d2);
    b2 = oe2(b2, "onChange");
    0 < b2.length && (c2 = new td2("onChange", "change", null, c2, d2), a3.push({ event: c2, listeners: b2 }));
  }
  var pe = null, qe2 = null;
  function re2(a3) {
    se(a3, 0);
  }
  function te2(a3) {
    var b2 = ue3(a3);
    if (Wa(b2)) return a3;
  }
  function ve2(a3, b2) {
    if ("change" === a3) return b2;
  }
  var we2 = false;
  if (ia) {
    var xe2;
    if (ia) {
      var ye2 = "oninput" in document;
      if (!ye2) {
        var ze2 = document.createElement("div");
        ze2.setAttribute("oninput", "return;");
        ye2 = "function" === typeof ze2.oninput;
      }
      xe2 = ye2;
    } else xe2 = false;
    we2 = xe2 && (!document.documentMode || 9 < document.documentMode);
  }
  function Ae2() {
    pe && (pe.detachEvent("onpropertychange", Be2), qe2 = pe = null);
  }
  function Be2(a3) {
    if ("value" === a3.propertyName && te2(qe2)) {
      var b2 = [];
      ne2(b2, qe2, a3, xb(a3));
      Jb(re2, b2);
    }
  }
  function Ce2(a3, b2, c2) {
    "focusin" === a3 ? (Ae2(), pe = b2, qe2 = c2, pe.attachEvent("onpropertychange", Be2)) : "focusout" === a3 && Ae2();
  }
  function De2(a3) {
    if ("selectionchange" === a3 || "keyup" === a3 || "keydown" === a3) return te2(qe2);
  }
  function Ee2(a3, b2) {
    if ("click" === a3) return te2(b2);
  }
  function Fe2(a3, b2) {
    if ("input" === a3 || "change" === a3) return te2(b2);
  }
  function Ge2(a3, b2) {
    return a3 === b2 && (0 !== a3 || 1 / a3 === 1 / b2) || a3 !== a3 && b2 !== b2;
  }
  var He2 = "function" === typeof Object.is ? Object.is : Ge2;
  function Ie2(a3, b2) {
    if (He2(a3, b2)) return true;
    if ("object" !== typeof a3 || null === a3 || "object" !== typeof b2 || null === b2) return false;
    var c2 = Object.keys(a3), d2 = Object.keys(b2);
    if (c2.length !== d2.length) return false;
    for (d2 = 0; d2 < c2.length; d2++) {
      var e2 = c2[d2];
      if (!ja.call(b2, e2) || !He2(a3[e2], b2[e2])) return false;
    }
    return true;
  }
  function Je2(a3) {
    for (; a3 && a3.firstChild; ) a3 = a3.firstChild;
    return a3;
  }
  function Ke2(a3, b2) {
    var c2 = Je2(a3);
    a3 = 0;
    for (var d2; c2; ) {
      if (3 === c2.nodeType) {
        d2 = a3 + c2.textContent.length;
        if (a3 <= b2 && d2 >= b2) return { node: c2, offset: b2 - a3 };
        a3 = d2;
      }
      a: {
        for (; c2; ) {
          if (c2.nextSibling) {
            c2 = c2.nextSibling;
            break a;
          }
          c2 = c2.parentNode;
        }
        c2 = void 0;
      }
      c2 = Je2(c2);
    }
  }
  function Le2(a3, b2) {
    return a3 && b2 ? a3 === b2 ? true : a3 && 3 === a3.nodeType ? false : b2 && 3 === b2.nodeType ? Le2(a3, b2.parentNode) : "contains" in a3 ? a3.contains(b2) : a3.compareDocumentPosition ? !!(a3.compareDocumentPosition(b2) & 16) : false : false;
  }
  function Me2() {
    for (var a3 = window, b2 = Xa(); b2 instanceof a3.HTMLIFrameElement; ) {
      try {
        var c2 = "string" === typeof b2.contentWindow.location.href;
      } catch (d2) {
        c2 = false;
      }
      if (c2) a3 = b2.contentWindow;
      else break;
      b2 = Xa(a3.document);
    }
    return b2;
  }
  function Ne2(a3) {
    var b2 = a3 && a3.nodeName && a3.nodeName.toLowerCase();
    return b2 && ("input" === b2 && ("text" === a3.type || "search" === a3.type || "tel" === a3.type || "url" === a3.type || "password" === a3.type) || "textarea" === b2 || "true" === a3.contentEditable);
  }
  function Oe2(a3) {
    var b2 = Me2(), c2 = a3.focusedElem, d2 = a3.selectionRange;
    if (b2 !== c2 && c2 && c2.ownerDocument && Le2(c2.ownerDocument.documentElement, c2)) {
      if (null !== d2 && Ne2(c2)) {
        if (b2 = d2.start, a3 = d2.end, void 0 === a3 && (a3 = b2), "selectionStart" in c2) c2.selectionStart = b2, c2.selectionEnd = Math.min(a3, c2.value.length);
        else if (a3 = (b2 = c2.ownerDocument || document) && b2.defaultView || window, a3.getSelection) {
          a3 = a3.getSelection();
          var e2 = c2.textContent.length, f2 = Math.min(d2.start, e2);
          d2 = void 0 === d2.end ? f2 : Math.min(d2.end, e2);
          !a3.extend && f2 > d2 && (e2 = d2, d2 = f2, f2 = e2);
          e2 = Ke2(c2, f2);
          var g2 = Ke2(
            c2,
            d2
          );
          e2 && g2 && (1 !== a3.rangeCount || a3.anchorNode !== e2.node || a3.anchorOffset !== e2.offset || a3.focusNode !== g2.node || a3.focusOffset !== g2.offset) && (b2 = b2.createRange(), b2.setStart(e2.node, e2.offset), a3.removeAllRanges(), f2 > d2 ? (a3.addRange(b2), a3.extend(g2.node, g2.offset)) : (b2.setEnd(g2.node, g2.offset), a3.addRange(b2)));
        }
      }
      b2 = [];
      for (a3 = c2; a3 = a3.parentNode; ) 1 === a3.nodeType && b2.push({ element: a3, left: a3.scrollLeft, top: a3.scrollTop });
      "function" === typeof c2.focus && c2.focus();
      for (c2 = 0; c2 < b2.length; c2++) a3 = b2[c2], a3.element.scrollLeft = a3.left, a3.element.scrollTop = a3.top;
    }
  }
  var Pe2 = ia && "documentMode" in document && 11 >= document.documentMode, Qe2 = null, Re2 = null, Se2 = null, Te2 = false;
  function Ue2(a3, b2, c2) {
    var d2 = c2.window === c2 ? c2.document : 9 === c2.nodeType ? c2 : c2.ownerDocument;
    Te2 || null == Qe2 || Qe2 !== Xa(d2) || (d2 = Qe2, "selectionStart" in d2 && Ne2(d2) ? d2 = { start: d2.selectionStart, end: d2.selectionEnd } : (d2 = (d2.ownerDocument && d2.ownerDocument.defaultView || window).getSelection(), d2 = { anchorNode: d2.anchorNode, anchorOffset: d2.anchorOffset, focusNode: d2.focusNode, focusOffset: d2.focusOffset }), Se2 && Ie2(Se2, d2) || (Se2 = d2, d2 = oe2(Re2, "onSelect"), 0 < d2.length && (b2 = new td2("onSelect", "select", null, b2, c2), a3.push({ event: b2, listeners: d2 }), b2.target = Qe2)));
  }
  function Ve2(a3, b2) {
    var c2 = {};
    c2[a3.toLowerCase()] = b2.toLowerCase();
    c2["Webkit" + a3] = "webkit" + b2;
    c2["Moz" + a3] = "moz" + b2;
    return c2;
  }
  var We2 = { animationend: Ve2("Animation", "AnimationEnd"), animationiteration: Ve2("Animation", "AnimationIteration"), animationstart: Ve2("Animation", "AnimationStart"), transitionend: Ve2("Transition", "TransitionEnd") }, Xe2 = {}, Ye2 = {};
  ia && (Ye2 = document.createElement("div").style, "AnimationEvent" in window || (delete We2.animationend.animation, delete We2.animationiteration.animation, delete We2.animationstart.animation), "TransitionEvent" in window || delete We2.transitionend.transition);
  function Ze2(a3) {
    if (Xe2[a3]) return Xe2[a3];
    if (!We2[a3]) return a3;
    var b2 = We2[a3], c2;
    for (c2 in b2) if (b2.hasOwnProperty(c2) && c2 in Ye2) return Xe2[a3] = b2[c2];
    return a3;
  }
  var $e2 = Ze2("animationend"), af = Ze2("animationiteration"), bf = Ze2("animationstart"), cf = Ze2("transitionend"), df = /* @__PURE__ */ new Map(), ef = "abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
  function ff(a3, b2) {
    df.set(a3, b2);
    fa(b2, [a3]);
  }
  for (var gf = 0; gf < ef.length; gf++) {
    var hf = ef[gf], jf = hf.toLowerCase(), kf = hf[0].toUpperCase() + hf.slice(1);
    ff(jf, "on" + kf);
  }
  ff($e2, "onAnimationEnd");
  ff(af, "onAnimationIteration");
  ff(bf, "onAnimationStart");
  ff("dblclick", "onDoubleClick");
  ff("focusin", "onFocus");
  ff("focusout", "onBlur");
  ff(cf, "onTransitionEnd");
  ha("onMouseEnter", ["mouseout", "mouseover"]);
  ha("onMouseLeave", ["mouseout", "mouseover"]);
  ha("onPointerEnter", ["pointerout", "pointerover"]);
  ha("onPointerLeave", ["pointerout", "pointerover"]);
  fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
  fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
  fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
  fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
  fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
  fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
  var lf = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "), mf = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
  function nf(a3, b2, c2) {
    var d2 = a3.type || "unknown-event";
    a3.currentTarget = c2;
    Ub(d2, b2, void 0, a3);
    a3.currentTarget = null;
  }
  function se(a3, b2) {
    b2 = 0 !== (b2 & 4);
    for (var c2 = 0; c2 < a3.length; c2++) {
      var d2 = a3[c2], e2 = d2.event;
      d2 = d2.listeners;
      a: {
        var f2 = void 0;
        if (b2) for (var g2 = d2.length - 1; 0 <= g2; g2--) {
          var h2 = d2[g2], k2 = h2.instance, l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped()) break a;
          nf(e2, h2, l2);
          f2 = k2;
        }
        else for (g2 = 0; g2 < d2.length; g2++) {
          h2 = d2[g2];
          k2 = h2.instance;
          l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped()) break a;
          nf(e2, h2, l2);
          f2 = k2;
        }
      }
    }
    if (Qb) throw a3 = Rb, Qb = false, Rb = null, a3;
  }
  function D2(a3, b2) {
    var c2 = b2[of];
    void 0 === c2 && (c2 = b2[of] = /* @__PURE__ */ new Set());
    var d2 = a3 + "__bubble";
    c2.has(d2) || (pf(b2, a3, 2, false), c2.add(d2));
  }
  function qf(a3, b2, c2) {
    var d2 = 0;
    b2 && (d2 |= 4);
    pf(c2, a3, d2, b2);
  }
  var rf = "_reactListening" + Math.random().toString(36).slice(2);
  function sf(a3) {
    if (!a3[rf]) {
      a3[rf] = true;
      da2.forEach(function(b3) {
        "selectionchange" !== b3 && (mf.has(b3) || qf(b3, false, a3), qf(b3, true, a3));
      });
      var b2 = 9 === a3.nodeType ? a3 : a3.ownerDocument;
      null === b2 || b2[rf] || (b2[rf] = true, qf("selectionchange", false, b2));
    }
  }
  function pf(a3, b2, c2, d2) {
    switch (jd(b2)) {
      case 1:
        var e2 = ed;
        break;
      case 4:
        e2 = gd;
        break;
      default:
        e2 = fd2;
    }
    c2 = e2.bind(null, b2, c2, a3);
    e2 = void 0;
    !Lb || "touchstart" !== b2 && "touchmove" !== b2 && "wheel" !== b2 || (e2 = true);
    d2 ? void 0 !== e2 ? a3.addEventListener(b2, c2, { capture: true, passive: e2 }) : a3.addEventListener(b2, c2, true) : void 0 !== e2 ? a3.addEventListener(b2, c2, { passive: e2 }) : a3.addEventListener(b2, c2, false);
  }
  function hd(a3, b2, c2, d2, e2) {
    var f2 = d2;
    if (0 === (b2 & 1) && 0 === (b2 & 2) && null !== d2) a: for (; ; ) {
      if (null === d2) return;
      var g2 = d2.tag;
      if (3 === g2 || 4 === g2) {
        var h2 = d2.stateNode.containerInfo;
        if (h2 === e2 || 8 === h2.nodeType && h2.parentNode === e2) break;
        if (4 === g2) for (g2 = d2.return; null !== g2; ) {
          var k2 = g2.tag;
          if (3 === k2 || 4 === k2) {
            if (k2 = g2.stateNode.containerInfo, k2 === e2 || 8 === k2.nodeType && k2.parentNode === e2) return;
          }
          g2 = g2.return;
        }
        for (; null !== h2; ) {
          g2 = Wc(h2);
          if (null === g2) return;
          k2 = g2.tag;
          if (5 === k2 || 6 === k2) {
            d2 = f2 = g2;
            continue a;
          }
          h2 = h2.parentNode;
        }
      }
      d2 = d2.return;
    }
    Jb(function() {
      var d3 = f2, e3 = xb(c2), g3 = [];
      a: {
        var h3 = df.get(a3);
        if (void 0 !== h3) {
          var k3 = td2, n2 = a3;
          switch (a3) {
            case "keypress":
              if (0 === od(c2)) break a;
            case "keydown":
            case "keyup":
              k3 = Rd;
              break;
            case "focusin":
              n2 = "focus";
              k3 = Fd;
              break;
            case "focusout":
              n2 = "blur";
              k3 = Fd;
              break;
            case "beforeblur":
            case "afterblur":
              k3 = Fd;
              break;
            case "click":
              if (2 === c2.button) break a;
            case "auxclick":
            case "dblclick":
            case "mousedown":
            case "mousemove":
            case "mouseup":
            case "mouseout":
            case "mouseover":
            case "contextmenu":
              k3 = Bd;
              break;
            case "drag":
            case "dragend":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "dragstart":
            case "drop":
              k3 = Dd;
              break;
            case "touchcancel":
            case "touchend":
            case "touchmove":
            case "touchstart":
              k3 = Vd;
              break;
            case $e2:
            case af:
            case bf:
              k3 = Hd;
              break;
            case cf:
              k3 = Xd;
              break;
            case "scroll":
              k3 = vd;
              break;
            case "wheel":
              k3 = Zd;
              break;
            case "copy":
            case "cut":
            case "paste":
              k3 = Jd;
              break;
            case "gotpointercapture":
            case "lostpointercapture":
            case "pointercancel":
            case "pointerdown":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "pointerup":
              k3 = Td;
          }
          var t2 = 0 !== (b2 & 4), J2 = !t2 && "scroll" === a3, x = t2 ? null !== h3 ? h3 + "Capture" : null : h3;
          t2 = [];
          for (var w2 = d3, u2; null !== w2; ) {
            u2 = w2;
            var F2 = u2.stateNode;
            5 === u2.tag && null !== F2 && (u2 = F2, null !== x && (F2 = Kb(w2, x), null != F2 && t2.push(tf(w2, F2, u2))));
            if (J2) break;
            w2 = w2.return;
          }
          0 < t2.length && (h3 = new k3(h3, n2, null, c2, e3), g3.push({ event: h3, listeners: t2 }));
        }
      }
      if (0 === (b2 & 7)) {
        a: {
          h3 = "mouseover" === a3 || "pointerover" === a3;
          k3 = "mouseout" === a3 || "pointerout" === a3;
          if (h3 && c2 !== wb && (n2 = c2.relatedTarget || c2.fromElement) && (Wc(n2) || n2[uf])) break a;
          if (k3 || h3) {
            h3 = e3.window === e3 ? e3 : (h3 = e3.ownerDocument) ? h3.defaultView || h3.parentWindow : window;
            if (k3) {
              if (n2 = c2.relatedTarget || c2.toElement, k3 = d3, n2 = n2 ? Wc(n2) : null, null !== n2 && (J2 = Vb(n2), n2 !== J2 || 5 !== n2.tag && 6 !== n2.tag)) n2 = null;
            } else k3 = null, n2 = d3;
            if (k3 !== n2) {
              t2 = Bd;
              F2 = "onMouseLeave";
              x = "onMouseEnter";
              w2 = "mouse";
              if ("pointerout" === a3 || "pointerover" === a3) t2 = Td, F2 = "onPointerLeave", x = "onPointerEnter", w2 = "pointer";
              J2 = null == k3 ? h3 : ue3(k3);
              u2 = null == n2 ? h3 : ue3(n2);
              h3 = new t2(F2, w2 + "leave", k3, c2, e3);
              h3.target = J2;
              h3.relatedTarget = u2;
              F2 = null;
              Wc(e3) === d3 && (t2 = new t2(x, w2 + "enter", n2, c2, e3), t2.target = u2, t2.relatedTarget = J2, F2 = t2);
              J2 = F2;
              if (k3 && n2) b: {
                t2 = k3;
                x = n2;
                w2 = 0;
                for (u2 = t2; u2; u2 = vf(u2)) w2++;
                u2 = 0;
                for (F2 = x; F2; F2 = vf(F2)) u2++;
                for (; 0 < w2 - u2; ) t2 = vf(t2), w2--;
                for (; 0 < u2 - w2; ) x = vf(x), u2--;
                for (; w2--; ) {
                  if (t2 === x || null !== x && t2 === x.alternate) break b;
                  t2 = vf(t2);
                  x = vf(x);
                }
                t2 = null;
              }
              else t2 = null;
              null !== k3 && wf(g3, h3, k3, t2, false);
              null !== n2 && null !== J2 && wf(g3, J2, n2, t2, true);
            }
          }
        }
        a: {
          h3 = d3 ? ue3(d3) : window;
          k3 = h3.nodeName && h3.nodeName.toLowerCase();
          if ("select" === k3 || "input" === k3 && "file" === h3.type) var na = ve2;
          else if (me2(h3)) if (we2) na = Fe2;
          else {
            na = De2;
            var xa = Ce2;
          }
          else (k3 = h3.nodeName) && "input" === k3.toLowerCase() && ("checkbox" === h3.type || "radio" === h3.type) && (na = Ee2);
          if (na && (na = na(a3, d3))) {
            ne2(g3, na, c2, e3);
            break a;
          }
          xa && xa(a3, h3, d3);
          "focusout" === a3 && (xa = h3._wrapperState) && xa.controlled && "number" === h3.type && cb(h3, "number", h3.value);
        }
        xa = d3 ? ue3(d3) : window;
        switch (a3) {
          case "focusin":
            if (me2(xa) || "true" === xa.contentEditable) Qe2 = xa, Re2 = d3, Se2 = null;
            break;
          case "focusout":
            Se2 = Re2 = Qe2 = null;
            break;
          case "mousedown":
            Te2 = true;
            break;
          case "contextmenu":
          case "mouseup":
          case "dragend":
            Te2 = false;
            Ue2(g3, c2, e3);
            break;
          case "selectionchange":
            if (Pe2) break;
          case "keydown":
          case "keyup":
            Ue2(g3, c2, e3);
        }
        var $a;
        if (ae) b: {
          switch (a3) {
            case "compositionstart":
              var ba = "onCompositionStart";
              break b;
            case "compositionend":
              ba = "onCompositionEnd";
              break b;
            case "compositionupdate":
              ba = "onCompositionUpdate";
              break b;
          }
          ba = void 0;
        }
        else ie ? ge2(a3, c2) && (ba = "onCompositionEnd") : "keydown" === a3 && 229 === c2.keyCode && (ba = "onCompositionStart");
        ba && (de2 && "ko" !== c2.locale && (ie || "onCompositionStart" !== ba ? "onCompositionEnd" === ba && ie && ($a = nd()) : (kd = e3, ld = "value" in kd ? kd.value : kd.textContent, ie = true)), xa = oe2(d3, ba), 0 < xa.length && (ba = new Ld(ba, a3, null, c2, e3), g3.push({ event: ba, listeners: xa }), $a ? ba.data = $a : ($a = he2(c2), null !== $a && (ba.data = $a))));
        if ($a = ce2 ? je2(a3, c2) : ke2(a3, c2)) d3 = oe2(d3, "onBeforeInput"), 0 < d3.length && (e3 = new Ld("onBeforeInput", "beforeinput", null, c2, e3), g3.push({ event: e3, listeners: d3 }), e3.data = $a);
      }
      se(g3, b2);
    });
  }
  function tf(a3, b2, c2) {
    return { instance: a3, listener: b2, currentTarget: c2 };
  }
  function oe2(a3, b2) {
    for (var c2 = b2 + "Capture", d2 = []; null !== a3; ) {
      var e2 = a3, f2 = e2.stateNode;
      5 === e2.tag && null !== f2 && (e2 = f2, f2 = Kb(a3, c2), null != f2 && d2.unshift(tf(a3, f2, e2)), f2 = Kb(a3, b2), null != f2 && d2.push(tf(a3, f2, e2)));
      a3 = a3.return;
    }
    return d2;
  }
  function vf(a3) {
    if (null === a3) return null;
    do
      a3 = a3.return;
    while (a3 && 5 !== a3.tag);
    return a3 ? a3 : null;
  }
  function wf(a3, b2, c2, d2, e2) {
    for (var f2 = b2._reactName, g2 = []; null !== c2 && c2 !== d2; ) {
      var h2 = c2, k2 = h2.alternate, l2 = h2.stateNode;
      if (null !== k2 && k2 === d2) break;
      5 === h2.tag && null !== l2 && (h2 = l2, e2 ? (k2 = Kb(c2, f2), null != k2 && g2.unshift(tf(c2, k2, h2))) : e2 || (k2 = Kb(c2, f2), null != k2 && g2.push(tf(c2, k2, h2))));
      c2 = c2.return;
    }
    0 !== g2.length && a3.push({ event: b2, listeners: g2 });
  }
  var xf = /\r\n?/g, yf = /\u0000|\uFFFD/g;
  function zf(a3) {
    return ("string" === typeof a3 ? a3 : "" + a3).replace(xf, "\n").replace(yf, "");
  }
  function Af(a3, b2, c2) {
    b2 = zf(b2);
    if (zf(a3) !== b2 && c2) throw Error(p2(425));
  }
  function Bf() {
  }
  var Cf = null, Df = null;
  function Ef(a3, b2) {
    return "textarea" === a3 || "noscript" === a3 || "string" === typeof b2.children || "number" === typeof b2.children || "object" === typeof b2.dangerouslySetInnerHTML && null !== b2.dangerouslySetInnerHTML && null != b2.dangerouslySetInnerHTML.__html;
  }
  var Ff = "function" === typeof setTimeout ? setTimeout : void 0, Gf = "function" === typeof clearTimeout ? clearTimeout : void 0, Hf = "function" === typeof Promise ? Promise : void 0, Jf = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf ? function(a3) {
    return Hf.resolve(null).then(a3).catch(If);
  } : Ff;
  function If(a3) {
    setTimeout(function() {
      throw a3;
    });
  }
  function Kf(a3, b2) {
    var c2 = b2, d2 = 0;
    do {
      var e2 = c2.nextSibling;
      a3.removeChild(c2);
      if (e2 && 8 === e2.nodeType) if (c2 = e2.data, "/$" === c2) {
        if (0 === d2) {
          a3.removeChild(e2);
          bd(b2);
          return;
        }
        d2--;
      } else "$" !== c2 && "$?" !== c2 && "$!" !== c2 || d2++;
      c2 = e2;
    } while (c2);
    bd(b2);
  }
  function Lf(a3) {
    for (; null != a3; a3 = a3.nextSibling) {
      var b2 = a3.nodeType;
      if (1 === b2 || 3 === b2) break;
      if (8 === b2) {
        b2 = a3.data;
        if ("$" === b2 || "$!" === b2 || "$?" === b2) break;
        if ("/$" === b2) return null;
      }
    }
    return a3;
  }
  function Mf(a3) {
    a3 = a3.previousSibling;
    for (var b2 = 0; a3; ) {
      if (8 === a3.nodeType) {
        var c2 = a3.data;
        if ("$" === c2 || "$!" === c2 || "$?" === c2) {
          if (0 === b2) return a3;
          b2--;
        } else "/$" === c2 && b2++;
      }
      a3 = a3.previousSibling;
    }
    return null;
  }
  var Nf = Math.random().toString(36).slice(2), Of = "__reactFiber$" + Nf, Pf = "__reactProps$" + Nf, uf = "__reactContainer$" + Nf, of = "__reactEvents$" + Nf, Qf = "__reactListeners$" + Nf, Rf = "__reactHandles$" + Nf;
  function Wc(a3) {
    var b2 = a3[Of];
    if (b2) return b2;
    for (var c2 = a3.parentNode; c2; ) {
      if (b2 = c2[uf] || c2[Of]) {
        c2 = b2.alternate;
        if (null !== b2.child || null !== c2 && null !== c2.child) for (a3 = Mf(a3); null !== a3; ) {
          if (c2 = a3[Of]) return c2;
          a3 = Mf(a3);
        }
        return b2;
      }
      a3 = c2;
      c2 = a3.parentNode;
    }
    return null;
  }
  function Cb(a3) {
    a3 = a3[Of] || a3[uf];
    return !a3 || 5 !== a3.tag && 6 !== a3.tag && 13 !== a3.tag && 3 !== a3.tag ? null : a3;
  }
  function ue3(a3) {
    if (5 === a3.tag || 6 === a3.tag) return a3.stateNode;
    throw Error(p2(33));
  }
  function Db(a3) {
    return a3[Pf] || null;
  }
  var Sf = [], Tf = -1;
  function Uf(a3) {
    return { current: a3 };
  }
  function E2(a3) {
    0 > Tf || (a3.current = Sf[Tf], Sf[Tf] = null, Tf--);
  }
  function G2(a3, b2) {
    Tf++;
    Sf[Tf] = a3.current;
    a3.current = b2;
  }
  var Vf = {}, H2 = Uf(Vf), Wf = Uf(false), Xf = Vf;
  function Yf(a3, b2) {
    var c2 = a3.type.contextTypes;
    if (!c2) return Vf;
    var d2 = a3.stateNode;
    if (d2 && d2.__reactInternalMemoizedUnmaskedChildContext === b2) return d2.__reactInternalMemoizedMaskedChildContext;
    var e2 = {}, f2;
    for (f2 in c2) e2[f2] = b2[f2];
    d2 && (a3 = a3.stateNode, a3.__reactInternalMemoizedUnmaskedChildContext = b2, a3.__reactInternalMemoizedMaskedChildContext = e2);
    return e2;
  }
  function Zf(a3) {
    a3 = a3.childContextTypes;
    return null !== a3 && void 0 !== a3;
  }
  function $f() {
    E2(Wf);
    E2(H2);
  }
  function ag(a3, b2, c2) {
    if (H2.current !== Vf) throw Error(p2(168));
    G2(H2, b2);
    G2(Wf, c2);
  }
  function bg(a3, b2, c2) {
    var d2 = a3.stateNode;
    b2 = b2.childContextTypes;
    if ("function" !== typeof d2.getChildContext) return c2;
    d2 = d2.getChildContext();
    for (var e2 in d2) if (!(e2 in b2)) throw Error(p2(108, Ra(a3) || "Unknown", e2));
    return A2({}, c2, d2);
  }
  function cg(a3) {
    a3 = (a3 = a3.stateNode) && a3.__reactInternalMemoizedMergedChildContext || Vf;
    Xf = H2.current;
    G2(H2, a3);
    G2(Wf, Wf.current);
    return true;
  }
  function dg(a3, b2, c2) {
    var d2 = a3.stateNode;
    if (!d2) throw Error(p2(169));
    c2 ? (a3 = bg(a3, b2, Xf), d2.__reactInternalMemoizedMergedChildContext = a3, E2(Wf), E2(H2), G2(H2, a3)) : E2(Wf);
    G2(Wf, c2);
  }
  var eg = null, fg = false, gg = false;
  function hg(a3) {
    null === eg ? eg = [a3] : eg.push(a3);
  }
  function ig(a3) {
    fg = true;
    hg(a3);
  }
  function jg() {
    if (!gg && null !== eg) {
      gg = true;
      var a3 = 0, b2 = C2;
      try {
        var c2 = eg;
        for (C2 = 1; a3 < c2.length; a3++) {
          var d2 = c2[a3];
          do
            d2 = d2(true);
          while (null !== d2);
        }
        eg = null;
        fg = false;
      } catch (e2) {
        throw null !== eg && (eg = eg.slice(a3 + 1)), ac(fc, jg), e2;
      } finally {
        C2 = b2, gg = false;
      }
    }
    return null;
  }
  var kg = [], lg = 0, mg = null, ng = 0, og = [], pg = 0, qg = null, rg = 1, sg = "";
  function tg(a3, b2) {
    kg[lg++] = ng;
    kg[lg++] = mg;
    mg = a3;
    ng = b2;
  }
  function ug(a3, b2, c2) {
    og[pg++] = rg;
    og[pg++] = sg;
    og[pg++] = qg;
    qg = a3;
    var d2 = rg;
    a3 = sg;
    var e2 = 32 - oc(d2) - 1;
    d2 &= ~(1 << e2);
    c2 += 1;
    var f2 = 32 - oc(b2) + e2;
    if (30 < f2) {
      var g2 = e2 - e2 % 5;
      f2 = (d2 & (1 << g2) - 1).toString(32);
      d2 >>= g2;
      e2 -= g2;
      rg = 1 << 32 - oc(b2) + e2 | c2 << e2 | d2;
      sg = f2 + a3;
    } else rg = 1 << f2 | c2 << e2 | d2, sg = a3;
  }
  function vg(a3) {
    null !== a3.return && (tg(a3, 1), ug(a3, 1, 0));
  }
  function wg(a3) {
    for (; a3 === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null;
    for (; a3 === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null;
  }
  var xg = null, yg = null, I2 = false, zg = null;
  function Ag(a3, b2) {
    var c2 = Bg(5, null, null, 0);
    c2.elementType = "DELETED";
    c2.stateNode = b2;
    c2.return = a3;
    b2 = a3.deletions;
    null === b2 ? (a3.deletions = [c2], a3.flags |= 16) : b2.push(c2);
  }
  function Cg(a3, b2) {
    switch (a3.tag) {
      case 5:
        var c2 = a3.type;
        b2 = 1 !== b2.nodeType || c2.toLowerCase() !== b2.nodeName.toLowerCase() ? null : b2;
        return null !== b2 ? (a3.stateNode = b2, xg = a3, yg = Lf(b2.firstChild), true) : false;
      case 6:
        return b2 = "" === a3.pendingProps || 3 !== b2.nodeType ? null : b2, null !== b2 ? (a3.stateNode = b2, xg = a3, yg = null, true) : false;
      case 13:
        return b2 = 8 !== b2.nodeType ? null : b2, null !== b2 ? (c2 = null !== qg ? { id: rg, overflow: sg } : null, a3.memoizedState = { dehydrated: b2, treeContext: c2, retryLane: 1073741824 }, c2 = Bg(18, null, null, 0), c2.stateNode = b2, c2.return = a3, a3.child = c2, xg = a3, yg = null, true) : false;
      default:
        return false;
    }
  }
  function Dg(a3) {
    return 0 !== (a3.mode & 1) && 0 === (a3.flags & 128);
  }
  function Eg(a3) {
    if (I2) {
      var b2 = yg;
      if (b2) {
        var c2 = b2;
        if (!Cg(a3, b2)) {
          if (Dg(a3)) throw Error(p2(418));
          b2 = Lf(c2.nextSibling);
          var d2 = xg;
          b2 && Cg(a3, b2) ? Ag(d2, c2) : (a3.flags = a3.flags & -4097 | 2, I2 = false, xg = a3);
        }
      } else {
        if (Dg(a3)) throw Error(p2(418));
        a3.flags = a3.flags & -4097 | 2;
        I2 = false;
        xg = a3;
      }
    }
  }
  function Fg(a3) {
    for (a3 = a3.return; null !== a3 && 5 !== a3.tag && 3 !== a3.tag && 13 !== a3.tag; ) a3 = a3.return;
    xg = a3;
  }
  function Gg(a3) {
    if (a3 !== xg) return false;
    if (!I2) return Fg(a3), I2 = true, false;
    var b2;
    (b2 = 3 !== a3.tag) && !(b2 = 5 !== a3.tag) && (b2 = a3.type, b2 = "head" !== b2 && "body" !== b2 && !Ef(a3.type, a3.memoizedProps));
    if (b2 && (b2 = yg)) {
      if (Dg(a3)) throw Hg(), Error(p2(418));
      for (; b2; ) Ag(a3, b2), b2 = Lf(b2.nextSibling);
    }
    Fg(a3);
    if (13 === a3.tag) {
      a3 = a3.memoizedState;
      a3 = null !== a3 ? a3.dehydrated : null;
      if (!a3) throw Error(p2(317));
      a: {
        a3 = a3.nextSibling;
        for (b2 = 0; a3; ) {
          if (8 === a3.nodeType) {
            var c2 = a3.data;
            if ("/$" === c2) {
              if (0 === b2) {
                yg = Lf(a3.nextSibling);
                break a;
              }
              b2--;
            } else "$" !== c2 && "$!" !== c2 && "$?" !== c2 || b2++;
          }
          a3 = a3.nextSibling;
        }
        yg = null;
      }
    } else yg = xg ? Lf(a3.stateNode.nextSibling) : null;
    return true;
  }
  function Hg() {
    for (var a3 = yg; a3; ) a3 = Lf(a3.nextSibling);
  }
  function Ig() {
    yg = xg = null;
    I2 = false;
  }
  function Jg(a3) {
    null === zg ? zg = [a3] : zg.push(a3);
  }
  var Kg = ua2.ReactCurrentBatchConfig;
  function Lg(a3, b2, c2) {
    a3 = c2.ref;
    if (null !== a3 && "function" !== typeof a3 && "object" !== typeof a3) {
      if (c2._owner) {
        c2 = c2._owner;
        if (c2) {
          if (1 !== c2.tag) throw Error(p2(309));
          var d2 = c2.stateNode;
        }
        if (!d2) throw Error(p2(147, a3));
        var e2 = d2, f2 = "" + a3;
        if (null !== b2 && null !== b2.ref && "function" === typeof b2.ref && b2.ref._stringRef === f2) return b2.ref;
        b2 = function(a4) {
          var b3 = e2.refs;
          null === a4 ? delete b3[f2] : b3[f2] = a4;
        };
        b2._stringRef = f2;
        return b2;
      }
      if ("string" !== typeof a3) throw Error(p2(284));
      if (!c2._owner) throw Error(p2(290, a3));
    }
    return a3;
  }
  function Mg(a3, b2) {
    a3 = Object.prototype.toString.call(b2);
    throw Error(p2(31, "[object Object]" === a3 ? "object with keys {" + Object.keys(b2).join(", ") + "}" : a3));
  }
  function Ng(a3) {
    var b2 = a3._init;
    return b2(a3._payload);
  }
  function Og(a3) {
    function b2(b3, c3) {
      if (a3) {
        var d3 = b3.deletions;
        null === d3 ? (b3.deletions = [c3], b3.flags |= 16) : d3.push(c3);
      }
    }
    function c2(c3, d3) {
      if (!a3) return null;
      for (; null !== d3; ) b2(c3, d3), d3 = d3.sibling;
      return null;
    }
    function d2(a4, b3) {
      for (a4 = /* @__PURE__ */ new Map(); null !== b3; ) null !== b3.key ? a4.set(b3.key, b3) : a4.set(b3.index, b3), b3 = b3.sibling;
      return a4;
    }
    function e2(a4, b3) {
      a4 = Pg(a4, b3);
      a4.index = 0;
      a4.sibling = null;
      return a4;
    }
    function f2(b3, c3, d3) {
      b3.index = d3;
      if (!a3) return b3.flags |= 1048576, c3;
      d3 = b3.alternate;
      if (null !== d3) return d3 = d3.index, d3 < c3 ? (b3.flags |= 2, c3) : d3;
      b3.flags |= 2;
      return c3;
    }
    function g2(b3) {
      a3 && null === b3.alternate && (b3.flags |= 2);
      return b3;
    }
    function h2(a4, b3, c3, d3) {
      if (null === b3 || 6 !== b3.tag) return b3 = Qg(c3, a4.mode, d3), b3.return = a4, b3;
      b3 = e2(b3, c3);
      b3.return = a4;
      return b3;
    }
    function k2(a4, b3, c3, d3) {
      var f3 = c3.type;
      if (f3 === ya) return m2(a4, b3, c3.props.children, d3, c3.key);
      if (null !== b3 && (b3.elementType === f3 || "object" === typeof f3 && null !== f3 && f3.$$typeof === Ha && Ng(f3) === b3.type)) return d3 = e2(b3, c3.props), d3.ref = Lg(a4, b3, c3), d3.return = a4, d3;
      d3 = Rg(c3.type, c3.key, c3.props, null, a4.mode, d3);
      d3.ref = Lg(a4, b3, c3);
      d3.return = a4;
      return d3;
    }
    function l2(a4, b3, c3, d3) {
      if (null === b3 || 4 !== b3.tag || b3.stateNode.containerInfo !== c3.containerInfo || b3.stateNode.implementation !== c3.implementation) return b3 = Sg(c3, a4.mode, d3), b3.return = a4, b3;
      b3 = e2(b3, c3.children || []);
      b3.return = a4;
      return b3;
    }
    function m2(a4, b3, c3, d3, f3) {
      if (null === b3 || 7 !== b3.tag) return b3 = Tg(c3, a4.mode, d3, f3), b3.return = a4, b3;
      b3 = e2(b3, c3);
      b3.return = a4;
      return b3;
    }
    function q3(a4, b3, c3) {
      if ("string" === typeof b3 && "" !== b3 || "number" === typeof b3) return b3 = Qg("" + b3, a4.mode, c3), b3.return = a4, b3;
      if ("object" === typeof b3 && null !== b3) {
        switch (b3.$$typeof) {
          case va:
            return c3 = Rg(b3.type, b3.key, b3.props, null, a4.mode, c3), c3.ref = Lg(a4, null, b3), c3.return = a4, c3;
          case wa:
            return b3 = Sg(b3, a4.mode, c3), b3.return = a4, b3;
          case Ha:
            var d3 = b3._init;
            return q3(a4, d3(b3._payload), c3);
        }
        if (eb(b3) || Ka(b3)) return b3 = Tg(b3, a4.mode, c3, null), b3.return = a4, b3;
        Mg(a4, b3);
      }
      return null;
    }
    function r2(a4, b3, c3, d3) {
      var e3 = null !== b3 ? b3.key : null;
      if ("string" === typeof c3 && "" !== c3 || "number" === typeof c3) return null !== e3 ? null : h2(a4, b3, "" + c3, d3);
      if ("object" === typeof c3 && null !== c3) {
        switch (c3.$$typeof) {
          case va:
            return c3.key === e3 ? k2(a4, b3, c3, d3) : null;
          case wa:
            return c3.key === e3 ? l2(a4, b3, c3, d3) : null;
          case Ha:
            return e3 = c3._init, r2(
              a4,
              b3,
              e3(c3._payload),
              d3
            );
        }
        if (eb(c3) || Ka(c3)) return null !== e3 ? null : m2(a4, b3, c3, d3, null);
        Mg(a4, c3);
      }
      return null;
    }
    function y2(a4, b3, c3, d3, e3) {
      if ("string" === typeof d3 && "" !== d3 || "number" === typeof d3) return a4 = a4.get(c3) || null, h2(b3, a4, "" + d3, e3);
      if ("object" === typeof d3 && null !== d3) {
        switch (d3.$$typeof) {
          case va:
            return a4 = a4.get(null === d3.key ? c3 : d3.key) || null, k2(b3, a4, d3, e3);
          case wa:
            return a4 = a4.get(null === d3.key ? c3 : d3.key) || null, l2(b3, a4, d3, e3);
          case Ha:
            var f3 = d3._init;
            return y2(a4, b3, c3, f3(d3._payload), e3);
        }
        if (eb(d3) || Ka(d3)) return a4 = a4.get(c3) || null, m2(b3, a4, d3, e3, null);
        Mg(b3, d3);
      }
      return null;
    }
    function n2(e3, g3, h3, k3) {
      for (var l3 = null, m3 = null, u2 = g3, w2 = g3 = 0, x = null; null !== u2 && w2 < h3.length; w2++) {
        u2.index > w2 ? (x = u2, u2 = null) : x = u2.sibling;
        var n3 = r2(e3, u2, h3[w2], k3);
        if (null === n3) {
          null === u2 && (u2 = x);
          break;
        }
        a3 && u2 && null === n3.alternate && b2(e3, u2);
        g3 = f2(n3, g3, w2);
        null === m3 ? l3 = n3 : m3.sibling = n3;
        m3 = n3;
        u2 = x;
      }
      if (w2 === h3.length) return c2(e3, u2), I2 && tg(e3, w2), l3;
      if (null === u2) {
        for (; w2 < h3.length; w2++) u2 = q3(e3, h3[w2], k3), null !== u2 && (g3 = f2(u2, g3, w2), null === m3 ? l3 = u2 : m3.sibling = u2, m3 = u2);
        I2 && tg(e3, w2);
        return l3;
      }
      for (u2 = d2(e3, u2); w2 < h3.length; w2++) x = y2(u2, e3, w2, h3[w2], k3), null !== x && (a3 && null !== x.alternate && u2.delete(null === x.key ? w2 : x.key), g3 = f2(x, g3, w2), null === m3 ? l3 = x : m3.sibling = x, m3 = x);
      a3 && u2.forEach(function(a4) {
        return b2(e3, a4);
      });
      I2 && tg(e3, w2);
      return l3;
    }
    function t2(e3, g3, h3, k3) {
      var l3 = Ka(h3);
      if ("function" !== typeof l3) throw Error(p2(150));
      h3 = l3.call(h3);
      if (null == h3) throw Error(p2(151));
      for (var u2 = l3 = null, m3 = g3, w2 = g3 = 0, x = null, n3 = h3.next(); null !== m3 && !n3.done; w2++, n3 = h3.next()) {
        m3.index > w2 ? (x = m3, m3 = null) : x = m3.sibling;
        var t3 = r2(e3, m3, n3.value, k3);
        if (null === t3) {
          null === m3 && (m3 = x);
          break;
        }
        a3 && m3 && null === t3.alternate && b2(e3, m3);
        g3 = f2(t3, g3, w2);
        null === u2 ? l3 = t3 : u2.sibling = t3;
        u2 = t3;
        m3 = x;
      }
      if (n3.done) return c2(
        e3,
        m3
      ), I2 && tg(e3, w2), l3;
      if (null === m3) {
        for (; !n3.done; w2++, n3 = h3.next()) n3 = q3(e3, n3.value, k3), null !== n3 && (g3 = f2(n3, g3, w2), null === u2 ? l3 = n3 : u2.sibling = n3, u2 = n3);
        I2 && tg(e3, w2);
        return l3;
      }
      for (m3 = d2(e3, m3); !n3.done; w2++, n3 = h3.next()) n3 = y2(m3, e3, w2, n3.value, k3), null !== n3 && (a3 && null !== n3.alternate && m3.delete(null === n3.key ? w2 : n3.key), g3 = f2(n3, g3, w2), null === u2 ? l3 = n3 : u2.sibling = n3, u2 = n3);
      a3 && m3.forEach(function(a4) {
        return b2(e3, a4);
      });
      I2 && tg(e3, w2);
      return l3;
    }
    function J2(a4, d3, f3, h3) {
      "object" === typeof f3 && null !== f3 && f3.type === ya && null === f3.key && (f3 = f3.props.children);
      if ("object" === typeof f3 && null !== f3) {
        switch (f3.$$typeof) {
          case va:
            a: {
              for (var k3 = f3.key, l3 = d3; null !== l3; ) {
                if (l3.key === k3) {
                  k3 = f3.type;
                  if (k3 === ya) {
                    if (7 === l3.tag) {
                      c2(a4, l3.sibling);
                      d3 = e2(l3, f3.props.children);
                      d3.return = a4;
                      a4 = d3;
                      break a;
                    }
                  } else if (l3.elementType === k3 || "object" === typeof k3 && null !== k3 && k3.$$typeof === Ha && Ng(k3) === l3.type) {
                    c2(a4, l3.sibling);
                    d3 = e2(l3, f3.props);
                    d3.ref = Lg(a4, l3, f3);
                    d3.return = a4;
                    a4 = d3;
                    break a;
                  }
                  c2(a4, l3);
                  break;
                } else b2(a4, l3);
                l3 = l3.sibling;
              }
              f3.type === ya ? (d3 = Tg(f3.props.children, a4.mode, h3, f3.key), d3.return = a4, a4 = d3) : (h3 = Rg(f3.type, f3.key, f3.props, null, a4.mode, h3), h3.ref = Lg(a4, d3, f3), h3.return = a4, a4 = h3);
            }
            return g2(a4);
          case wa:
            a: {
              for (l3 = f3.key; null !== d3; ) {
                if (d3.key === l3) if (4 === d3.tag && d3.stateNode.containerInfo === f3.containerInfo && d3.stateNode.implementation === f3.implementation) {
                  c2(a4, d3.sibling);
                  d3 = e2(d3, f3.children || []);
                  d3.return = a4;
                  a4 = d3;
                  break a;
                } else {
                  c2(a4, d3);
                  break;
                }
                else b2(a4, d3);
                d3 = d3.sibling;
              }
              d3 = Sg(f3, a4.mode, h3);
              d3.return = a4;
              a4 = d3;
            }
            return g2(a4);
          case Ha:
            return l3 = f3._init, J2(a4, d3, l3(f3._payload), h3);
        }
        if (eb(f3)) return n2(a4, d3, f3, h3);
        if (Ka(f3)) return t2(a4, d3, f3, h3);
        Mg(a4, f3);
      }
      return "string" === typeof f3 && "" !== f3 || "number" === typeof f3 ? (f3 = "" + f3, null !== d3 && 6 === d3.tag ? (c2(a4, d3.sibling), d3 = e2(d3, f3), d3.return = a4, a4 = d3) : (c2(a4, d3), d3 = Qg(f3, a4.mode, h3), d3.return = a4, a4 = d3), g2(a4)) : c2(a4, d3);
    }
    return J2;
  }
  var Ug = Og(true), Vg = Og(false), Wg = Uf(null), Xg = null, Yg = null, Zg = null;
  function $g() {
    Zg = Yg = Xg = null;
  }
  function ah(a3) {
    var b2 = Wg.current;
    E2(Wg);
    a3._currentValue = b2;
  }
  function bh(a3, b2, c2) {
    for (; null !== a3; ) {
      var d2 = a3.alternate;
      (a3.childLanes & b2) !== b2 ? (a3.childLanes |= b2, null !== d2 && (d2.childLanes |= b2)) : null !== d2 && (d2.childLanes & b2) !== b2 && (d2.childLanes |= b2);
      if (a3 === c2) break;
      a3 = a3.return;
    }
  }
  function ch(a3, b2) {
    Xg = a3;
    Zg = Yg = null;
    a3 = a3.dependencies;
    null !== a3 && null !== a3.firstContext && (0 !== (a3.lanes & b2) && (dh = true), a3.firstContext = null);
  }
  function eh(a3) {
    var b2 = a3._currentValue;
    if (Zg !== a3) if (a3 = { context: a3, memoizedValue: b2, next: null }, null === Yg) {
      if (null === Xg) throw Error(p2(308));
      Yg = a3;
      Xg.dependencies = { lanes: 0, firstContext: a3 };
    } else Yg = Yg.next = a3;
    return b2;
  }
  var fh = null;
  function gh(a3) {
    null === fh ? fh = [a3] : fh.push(a3);
  }
  function hh(a3, b2, c2, d2) {
    var e2 = b2.interleaved;
    null === e2 ? (c2.next = c2, gh(b2)) : (c2.next = e2.next, e2.next = c2);
    b2.interleaved = c2;
    return ih(a3, d2);
  }
  function ih(a3, b2) {
    a3.lanes |= b2;
    var c2 = a3.alternate;
    null !== c2 && (c2.lanes |= b2);
    c2 = a3;
    for (a3 = a3.return; null !== a3; ) a3.childLanes |= b2, c2 = a3.alternate, null !== c2 && (c2.childLanes |= b2), c2 = a3, a3 = a3.return;
    return 3 === c2.tag ? c2.stateNode : null;
  }
  var jh = false;
  function kh(a3) {
    a3.updateQueue = { baseState: a3.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null };
  }
  function lh(a3, b2) {
    a3 = a3.updateQueue;
    b2.updateQueue === a3 && (b2.updateQueue = { baseState: a3.baseState, firstBaseUpdate: a3.firstBaseUpdate, lastBaseUpdate: a3.lastBaseUpdate, shared: a3.shared, effects: a3.effects });
  }
  function mh(a3, b2) {
    return { eventTime: a3, lane: b2, tag: 0, payload: null, callback: null, next: null };
  }
  function nh(a3, b2, c2) {
    var d2 = a3.updateQueue;
    if (null === d2) return null;
    d2 = d2.shared;
    if (0 !== (K2 & 2)) {
      var e2 = d2.pending;
      null === e2 ? b2.next = b2 : (b2.next = e2.next, e2.next = b2);
      d2.pending = b2;
      return ih(a3, c2);
    }
    e2 = d2.interleaved;
    null === e2 ? (b2.next = b2, gh(d2)) : (b2.next = e2.next, e2.next = b2);
    d2.interleaved = b2;
    return ih(a3, c2);
  }
  function oh(a3, b2, c2) {
    b2 = b2.updateQueue;
    if (null !== b2 && (b2 = b2.shared, 0 !== (c2 & 4194240))) {
      var d2 = b2.lanes;
      d2 &= a3.pendingLanes;
      c2 |= d2;
      b2.lanes = c2;
      Cc(a3, c2);
    }
  }
  function ph(a3, b2) {
    var c2 = a3.updateQueue, d2 = a3.alternate;
    if (null !== d2 && (d2 = d2.updateQueue, c2 === d2)) {
      var e2 = null, f2 = null;
      c2 = c2.firstBaseUpdate;
      if (null !== c2) {
        do {
          var g2 = { eventTime: c2.eventTime, lane: c2.lane, tag: c2.tag, payload: c2.payload, callback: c2.callback, next: null };
          null === f2 ? e2 = f2 = g2 : f2 = f2.next = g2;
          c2 = c2.next;
        } while (null !== c2);
        null === f2 ? e2 = f2 = b2 : f2 = f2.next = b2;
      } else e2 = f2 = b2;
      c2 = { baseState: d2.baseState, firstBaseUpdate: e2, lastBaseUpdate: f2, shared: d2.shared, effects: d2.effects };
      a3.updateQueue = c2;
      return;
    }
    a3 = c2.lastBaseUpdate;
    null === a3 ? c2.firstBaseUpdate = b2 : a3.next = b2;
    c2.lastBaseUpdate = b2;
  }
  function qh(a3, b2, c2, d2) {
    var e2 = a3.updateQueue;
    jh = false;
    var f2 = e2.firstBaseUpdate, g2 = e2.lastBaseUpdate, h2 = e2.shared.pending;
    if (null !== h2) {
      e2.shared.pending = null;
      var k2 = h2, l2 = k2.next;
      k2.next = null;
      null === g2 ? f2 = l2 : g2.next = l2;
      g2 = k2;
      var m2 = a3.alternate;
      null !== m2 && (m2 = m2.updateQueue, h2 = m2.lastBaseUpdate, h2 !== g2 && (null === h2 ? m2.firstBaseUpdate = l2 : h2.next = l2, m2.lastBaseUpdate = k2));
    }
    if (null !== f2) {
      var q3 = e2.baseState;
      g2 = 0;
      m2 = l2 = k2 = null;
      h2 = f2;
      do {
        var r2 = h2.lane, y2 = h2.eventTime;
        if ((d2 & r2) === r2) {
          null !== m2 && (m2 = m2.next = {
            eventTime: y2,
            lane: 0,
            tag: h2.tag,
            payload: h2.payload,
            callback: h2.callback,
            next: null
          });
          a: {
            var n2 = a3, t2 = h2;
            r2 = b2;
            y2 = c2;
            switch (t2.tag) {
              case 1:
                n2 = t2.payload;
                if ("function" === typeof n2) {
                  q3 = n2.call(y2, q3, r2);
                  break a;
                }
                q3 = n2;
                break a;
              case 3:
                n2.flags = n2.flags & -65537 | 128;
              case 0:
                n2 = t2.payload;
                r2 = "function" === typeof n2 ? n2.call(y2, q3, r2) : n2;
                if (null === r2 || void 0 === r2) break a;
                q3 = A2({}, q3, r2);
                break a;
              case 2:
                jh = true;
            }
          }
          null !== h2.callback && 0 !== h2.lane && (a3.flags |= 64, r2 = e2.effects, null === r2 ? e2.effects = [h2] : r2.push(h2));
        } else y2 = { eventTime: y2, lane: r2, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }, null === m2 ? (l2 = m2 = y2, k2 = q3) : m2 = m2.next = y2, g2 |= r2;
        h2 = h2.next;
        if (null === h2) if (h2 = e2.shared.pending, null === h2) break;
        else r2 = h2, h2 = r2.next, r2.next = null, e2.lastBaseUpdate = r2, e2.shared.pending = null;
      } while (1);
      null === m2 && (k2 = q3);
      e2.baseState = k2;
      e2.firstBaseUpdate = l2;
      e2.lastBaseUpdate = m2;
      b2 = e2.shared.interleaved;
      if (null !== b2) {
        e2 = b2;
        do
          g2 |= e2.lane, e2 = e2.next;
        while (e2 !== b2);
      } else null === f2 && (e2.shared.lanes = 0);
      rh |= g2;
      a3.lanes = g2;
      a3.memoizedState = q3;
    }
  }
  function sh(a3, b2, c2) {
    a3 = b2.effects;
    b2.effects = null;
    if (null !== a3) for (b2 = 0; b2 < a3.length; b2++) {
      var d2 = a3[b2], e2 = d2.callback;
      if (null !== e2) {
        d2.callback = null;
        d2 = c2;
        if ("function" !== typeof e2) throw Error(p2(191, e2));
        e2.call(d2);
      }
    }
  }
  var th = {}, uh = Uf(th), vh = Uf(th), wh = Uf(th);
  function xh(a3) {
    if (a3 === th) throw Error(p2(174));
    return a3;
  }
  function yh(a3, b2) {
    G2(wh, b2);
    G2(vh, a3);
    G2(uh, th);
    a3 = b2.nodeType;
    switch (a3) {
      case 9:
      case 11:
        b2 = (b2 = b2.documentElement) ? b2.namespaceURI : lb(null, "");
        break;
      default:
        a3 = 8 === a3 ? b2.parentNode : b2, b2 = a3.namespaceURI || null, a3 = a3.tagName, b2 = lb(b2, a3);
    }
    E2(uh);
    G2(uh, b2);
  }
  function zh() {
    E2(uh);
    E2(vh);
    E2(wh);
  }
  function Ah(a3) {
    xh(wh.current);
    var b2 = xh(uh.current);
    var c2 = lb(b2, a3.type);
    b2 !== c2 && (G2(vh, a3), G2(uh, c2));
  }
  function Bh(a3) {
    vh.current === a3 && (E2(uh), E2(vh));
  }
  var L2 = Uf(0);
  function Ch(a3) {
    for (var b2 = a3; null !== b2; ) {
      if (13 === b2.tag) {
        var c2 = b2.memoizedState;
        if (null !== c2 && (c2 = c2.dehydrated, null === c2 || "$?" === c2.data || "$!" === c2.data)) return b2;
      } else if (19 === b2.tag && void 0 !== b2.memoizedProps.revealOrder) {
        if (0 !== (b2.flags & 128)) return b2;
      } else if (null !== b2.child) {
        b2.child.return = b2;
        b2 = b2.child;
        continue;
      }
      if (b2 === a3) break;
      for (; null === b2.sibling; ) {
        if (null === b2.return || b2.return === a3) return null;
        b2 = b2.return;
      }
      b2.sibling.return = b2.return;
      b2 = b2.sibling;
    }
    return null;
  }
  var Dh = [];
  function Eh() {
    for (var a3 = 0; a3 < Dh.length; a3++) Dh[a3]._workInProgressVersionPrimary = null;
    Dh.length = 0;
  }
  var Fh = ua2.ReactCurrentDispatcher, Gh = ua2.ReactCurrentBatchConfig, Hh = 0, M2 = null, N2 = null, O2 = null, Ih = false, Jh = false, Kh = 0, Lh = 0;
  function P2() {
    throw Error(p2(321));
  }
  function Mh(a3, b2) {
    if (null === b2) return false;
    for (var c2 = 0; c2 < b2.length && c2 < a3.length; c2++) if (!He2(a3[c2], b2[c2])) return false;
    return true;
  }
  function Nh(a3, b2, c2, d2, e2, f2) {
    Hh = f2;
    M2 = b2;
    b2.memoizedState = null;
    b2.updateQueue = null;
    b2.lanes = 0;
    Fh.current = null === a3 || null === a3.memoizedState ? Oh : Ph;
    a3 = c2(d2, e2);
    if (Jh) {
      f2 = 0;
      do {
        Jh = false;
        Kh = 0;
        if (25 <= f2) throw Error(p2(301));
        f2 += 1;
        O2 = N2 = null;
        b2.updateQueue = null;
        Fh.current = Qh;
        a3 = c2(d2, e2);
      } while (Jh);
    }
    Fh.current = Rh;
    b2 = null !== N2 && null !== N2.next;
    Hh = 0;
    O2 = N2 = M2 = null;
    Ih = false;
    if (b2) throw Error(p2(300));
    return a3;
  }
  function Sh() {
    var a3 = 0 !== Kh;
    Kh = 0;
    return a3;
  }
  function Th() {
    var a3 = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
    null === O2 ? M2.memoizedState = O2 = a3 : O2 = O2.next = a3;
    return O2;
  }
  function Uh() {
    if (null === N2) {
      var a3 = M2.alternate;
      a3 = null !== a3 ? a3.memoizedState : null;
    } else a3 = N2.next;
    var b2 = null === O2 ? M2.memoizedState : O2.next;
    if (null !== b2) O2 = b2, N2 = a3;
    else {
      if (null === a3) throw Error(p2(310));
      N2 = a3;
      a3 = { memoizedState: N2.memoizedState, baseState: N2.baseState, baseQueue: N2.baseQueue, queue: N2.queue, next: null };
      null === O2 ? M2.memoizedState = O2 = a3 : O2 = O2.next = a3;
    }
    return O2;
  }
  function Vh(a3, b2) {
    return "function" === typeof b2 ? b2(a3) : b2;
  }
  function Wh(a3) {
    var b2 = Uh(), c2 = b2.queue;
    if (null === c2) throw Error(p2(311));
    c2.lastRenderedReducer = a3;
    var d2 = N2, e2 = d2.baseQueue, f2 = c2.pending;
    if (null !== f2) {
      if (null !== e2) {
        var g2 = e2.next;
        e2.next = f2.next;
        f2.next = g2;
      }
      d2.baseQueue = e2 = f2;
      c2.pending = null;
    }
    if (null !== e2) {
      f2 = e2.next;
      d2 = d2.baseState;
      var h2 = g2 = null, k2 = null, l2 = f2;
      do {
        var m2 = l2.lane;
        if ((Hh & m2) === m2) null !== k2 && (k2 = k2.next = { lane: 0, action: l2.action, hasEagerState: l2.hasEagerState, eagerState: l2.eagerState, next: null }), d2 = l2.hasEagerState ? l2.eagerState : a3(d2, l2.action);
        else {
          var q3 = {
            lane: m2,
            action: l2.action,
            hasEagerState: l2.hasEagerState,
            eagerState: l2.eagerState,
            next: null
          };
          null === k2 ? (h2 = k2 = q3, g2 = d2) : k2 = k2.next = q3;
          M2.lanes |= m2;
          rh |= m2;
        }
        l2 = l2.next;
      } while (null !== l2 && l2 !== f2);
      null === k2 ? g2 = d2 : k2.next = h2;
      He2(d2, b2.memoizedState) || (dh = true);
      b2.memoizedState = d2;
      b2.baseState = g2;
      b2.baseQueue = k2;
      c2.lastRenderedState = d2;
    }
    a3 = c2.interleaved;
    if (null !== a3) {
      e2 = a3;
      do
        f2 = e2.lane, M2.lanes |= f2, rh |= f2, e2 = e2.next;
      while (e2 !== a3);
    } else null === e2 && (c2.lanes = 0);
    return [b2.memoizedState, c2.dispatch];
  }
  function Xh(a3) {
    var b2 = Uh(), c2 = b2.queue;
    if (null === c2) throw Error(p2(311));
    c2.lastRenderedReducer = a3;
    var d2 = c2.dispatch, e2 = c2.pending, f2 = b2.memoizedState;
    if (null !== e2) {
      c2.pending = null;
      var g2 = e2 = e2.next;
      do
        f2 = a3(f2, g2.action), g2 = g2.next;
      while (g2 !== e2);
      He2(f2, b2.memoizedState) || (dh = true);
      b2.memoizedState = f2;
      null === b2.baseQueue && (b2.baseState = f2);
      c2.lastRenderedState = f2;
    }
    return [f2, d2];
  }
  function Yh() {
  }
  function Zh(a3, b2) {
    var c2 = M2, d2 = Uh(), e2 = b2(), f2 = !He2(d2.memoizedState, e2);
    f2 && (d2.memoizedState = e2, dh = true);
    d2 = d2.queue;
    $h(ai.bind(null, c2, d2, a3), [a3]);
    if (d2.getSnapshot !== b2 || f2 || null !== O2 && O2.memoizedState.tag & 1) {
      c2.flags |= 2048;
      bi(9, ci.bind(null, c2, d2, e2, b2), void 0, null);
      if (null === Q2) throw Error(p2(349));
      0 !== (Hh & 30) || di(c2, b2, e2);
    }
    return e2;
  }
  function di(a3, b2, c2) {
    a3.flags |= 16384;
    a3 = { getSnapshot: b2, value: c2 };
    b2 = M2.updateQueue;
    null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.stores = [a3]) : (c2 = b2.stores, null === c2 ? b2.stores = [a3] : c2.push(a3));
  }
  function ci(a3, b2, c2, d2) {
    b2.value = c2;
    b2.getSnapshot = d2;
    ei(b2) && fi(a3);
  }
  function ai(a3, b2, c2) {
    return c2(function() {
      ei(b2) && fi(a3);
    });
  }
  function ei(a3) {
    var b2 = a3.getSnapshot;
    a3 = a3.value;
    try {
      var c2 = b2();
      return !He2(a3, c2);
    } catch (d2) {
      return true;
    }
  }
  function fi(a3) {
    var b2 = ih(a3, 1);
    null !== b2 && gi(b2, a3, 1, -1);
  }
  function hi(a3) {
    var b2 = Th();
    "function" === typeof a3 && (a3 = a3());
    b2.memoizedState = b2.baseState = a3;
    a3 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a3 };
    b2.queue = a3;
    a3 = a3.dispatch = ii.bind(null, M2, a3);
    return [b2.memoizedState, a3];
  }
  function bi(a3, b2, c2, d2) {
    a3 = { tag: a3, create: b2, destroy: c2, deps: d2, next: null };
    b2 = M2.updateQueue;
    null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.lastEffect = a3.next = a3) : (c2 = b2.lastEffect, null === c2 ? b2.lastEffect = a3.next = a3 : (d2 = c2.next, c2.next = a3, a3.next = d2, b2.lastEffect = a3));
    return a3;
  }
  function ji() {
    return Uh().memoizedState;
  }
  function ki(a3, b2, c2, d2) {
    var e2 = Th();
    M2.flags |= a3;
    e2.memoizedState = bi(1 | b2, c2, void 0, void 0 === d2 ? null : d2);
  }
  function li(a3, b2, c2, d2) {
    var e2 = Uh();
    d2 = void 0 === d2 ? null : d2;
    var f2 = void 0;
    if (null !== N2) {
      var g2 = N2.memoizedState;
      f2 = g2.destroy;
      if (null !== d2 && Mh(d2, g2.deps)) {
        e2.memoizedState = bi(b2, c2, f2, d2);
        return;
      }
    }
    M2.flags |= a3;
    e2.memoizedState = bi(1 | b2, c2, f2, d2);
  }
  function mi(a3, b2) {
    return ki(8390656, 8, a3, b2);
  }
  function $h(a3, b2) {
    return li(2048, 8, a3, b2);
  }
  function ni(a3, b2) {
    return li(4, 2, a3, b2);
  }
  function oi(a3, b2) {
    return li(4, 4, a3, b2);
  }
  function pi(a3, b2) {
    if ("function" === typeof b2) return a3 = a3(), b2(a3), function() {
      b2(null);
    };
    if (null !== b2 && void 0 !== b2) return a3 = a3(), b2.current = a3, function() {
      b2.current = null;
    };
  }
  function qi(a3, b2, c2) {
    c2 = null !== c2 && void 0 !== c2 ? c2.concat([a3]) : null;
    return li(4, 4, pi.bind(null, b2, a3), c2);
  }
  function ri() {
  }
  function si(a3, b2) {
    var c2 = Uh();
    b2 = void 0 === b2 ? null : b2;
    var d2 = c2.memoizedState;
    if (null !== d2 && null !== b2 && Mh(b2, d2[1])) return d2[0];
    c2.memoizedState = [a3, b2];
    return a3;
  }
  function ti(a3, b2) {
    var c2 = Uh();
    b2 = void 0 === b2 ? null : b2;
    var d2 = c2.memoizedState;
    if (null !== d2 && null !== b2 && Mh(b2, d2[1])) return d2[0];
    a3 = a3();
    c2.memoizedState = [a3, b2];
    return a3;
  }
  function ui(a3, b2, c2) {
    if (0 === (Hh & 21)) return a3.baseState && (a3.baseState = false, dh = true), a3.memoizedState = c2;
    He2(c2, b2) || (c2 = yc(), M2.lanes |= c2, rh |= c2, a3.baseState = true);
    return b2;
  }
  function vi(a3, b2) {
    var c2 = C2;
    C2 = 0 !== c2 && 4 > c2 ? c2 : 4;
    a3(true);
    var d2 = Gh.transition;
    Gh.transition = {};
    try {
      a3(false), b2();
    } finally {
      C2 = c2, Gh.transition = d2;
    }
  }
  function wi() {
    return Uh().memoizedState;
  }
  function xi(a3, b2, c2) {
    var d2 = yi(a3);
    c2 = { lane: d2, action: c2, hasEagerState: false, eagerState: null, next: null };
    if (zi(a3)) Ai(b2, c2);
    else if (c2 = hh(a3, b2, c2, d2), null !== c2) {
      var e2 = R2();
      gi(c2, a3, d2, e2);
      Bi(c2, b2, d2);
    }
  }
  function ii(a3, b2, c2) {
    var d2 = yi(a3), e2 = { lane: d2, action: c2, hasEagerState: false, eagerState: null, next: null };
    if (zi(a3)) Ai(b2, e2);
    else {
      var f2 = a3.alternate;
      if (0 === a3.lanes && (null === f2 || 0 === f2.lanes) && (f2 = b2.lastRenderedReducer, null !== f2)) try {
        var g2 = b2.lastRenderedState, h2 = f2(g2, c2);
        e2.hasEagerState = true;
        e2.eagerState = h2;
        if (He2(h2, g2)) {
          var k2 = b2.interleaved;
          null === k2 ? (e2.next = e2, gh(b2)) : (e2.next = k2.next, k2.next = e2);
          b2.interleaved = e2;
          return;
        }
      } catch (l2) {
      } finally {
      }
      c2 = hh(a3, b2, e2, d2);
      null !== c2 && (e2 = R2(), gi(c2, a3, d2, e2), Bi(c2, b2, d2));
    }
  }
  function zi(a3) {
    var b2 = a3.alternate;
    return a3 === M2 || null !== b2 && b2 === M2;
  }
  function Ai(a3, b2) {
    Jh = Ih = true;
    var c2 = a3.pending;
    null === c2 ? b2.next = b2 : (b2.next = c2.next, c2.next = b2);
    a3.pending = b2;
  }
  function Bi(a3, b2, c2) {
    if (0 !== (c2 & 4194240)) {
      var d2 = b2.lanes;
      d2 &= a3.pendingLanes;
      c2 |= d2;
      b2.lanes = c2;
      Cc(a3, c2);
    }
  }
  var Rh = { readContext: eh, useCallback: P2, useContext: P2, useEffect: P2, useImperativeHandle: P2, useInsertionEffect: P2, useLayoutEffect: P2, useMemo: P2, useReducer: P2, useRef: P2, useState: P2, useDebugValue: P2, useDeferredValue: P2, useTransition: P2, useMutableSource: P2, useSyncExternalStore: P2, useId: P2, unstable_isNewReconciler: false }, Oh = { readContext: eh, useCallback: function(a3, b2) {
    Th().memoizedState = [a3, void 0 === b2 ? null : b2];
    return a3;
  }, useContext: eh, useEffect: mi, useImperativeHandle: function(a3, b2, c2) {
    c2 = null !== c2 && void 0 !== c2 ? c2.concat([a3]) : null;
    return ki(
      4194308,
      4,
      pi.bind(null, b2, a3),
      c2
    );
  }, useLayoutEffect: function(a3, b2) {
    return ki(4194308, 4, a3, b2);
  }, useInsertionEffect: function(a3, b2) {
    return ki(4, 2, a3, b2);
  }, useMemo: function(a3, b2) {
    var c2 = Th();
    b2 = void 0 === b2 ? null : b2;
    a3 = a3();
    c2.memoizedState = [a3, b2];
    return a3;
  }, useReducer: function(a3, b2, c2) {
    var d2 = Th();
    b2 = void 0 !== c2 ? c2(b2) : b2;
    d2.memoizedState = d2.baseState = b2;
    a3 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a3, lastRenderedState: b2 };
    d2.queue = a3;
    a3 = a3.dispatch = xi.bind(null, M2, a3);
    return [d2.memoizedState, a3];
  }, useRef: function(a3) {
    var b2 = Th();
    a3 = { current: a3 };
    return b2.memoizedState = a3;
  }, useState: hi, useDebugValue: ri, useDeferredValue: function(a3) {
    return Th().memoizedState = a3;
  }, useTransition: function() {
    var a3 = hi(false), b2 = a3[0];
    a3 = vi.bind(null, a3[1]);
    Th().memoizedState = a3;
    return [b2, a3];
  }, useMutableSource: function() {
  }, useSyncExternalStore: function(a3, b2, c2) {
    var d2 = M2, e2 = Th();
    if (I2) {
      if (void 0 === c2) throw Error(p2(407));
      c2 = c2();
    } else {
      c2 = b2();
      if (null === Q2) throw Error(p2(349));
      0 !== (Hh & 30) || di(d2, b2, c2);
    }
    e2.memoizedState = c2;
    var f2 = { value: c2, getSnapshot: b2 };
    e2.queue = f2;
    mi(ai.bind(
      null,
      d2,
      f2,
      a3
    ), [a3]);
    d2.flags |= 2048;
    bi(9, ci.bind(null, d2, f2, c2, b2), void 0, null);
    return c2;
  }, useId: function() {
    var a3 = Th(), b2 = Q2.identifierPrefix;
    if (I2) {
      var c2 = sg;
      var d2 = rg;
      c2 = (d2 & ~(1 << 32 - oc(d2) - 1)).toString(32) + c2;
      b2 = ":" + b2 + "R" + c2;
      c2 = Kh++;
      0 < c2 && (b2 += "H" + c2.toString(32));
      b2 += ":";
    } else c2 = Lh++, b2 = ":" + b2 + "r" + c2.toString(32) + ":";
    return a3.memoizedState = b2;
  }, unstable_isNewReconciler: false }, Ph = {
    readContext: eh,
    useCallback: si,
    useContext: eh,
    useEffect: $h,
    useImperativeHandle: qi,
    useInsertionEffect: ni,
    useLayoutEffect: oi,
    useMemo: ti,
    useReducer: Wh,
    useRef: ji,
    useState: function() {
      return Wh(Vh);
    },
    useDebugValue: ri,
    useDeferredValue: function(a3) {
      var b2 = Uh();
      return ui(b2, N2.memoizedState, a3);
    },
    useTransition: function() {
      var a3 = Wh(Vh)[0], b2 = Uh().memoizedState;
      return [a3, b2];
    },
    useMutableSource: Yh,
    useSyncExternalStore: Zh,
    useId: wi,
    unstable_isNewReconciler: false
  }, Qh = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Xh, useRef: ji, useState: function() {
    return Xh(Vh);
  }, useDebugValue: ri, useDeferredValue: function(a3) {
    var b2 = Uh();
    return null === N2 ? b2.memoizedState = a3 : ui(b2, N2.memoizedState, a3);
  }, useTransition: function() {
    var a3 = Xh(Vh)[0], b2 = Uh().memoizedState;
    return [a3, b2];
  }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false };
  function Ci(a3, b2) {
    if (a3 && a3.defaultProps) {
      b2 = A2({}, b2);
      a3 = a3.defaultProps;
      for (var c2 in a3) void 0 === b2[c2] && (b2[c2] = a3[c2]);
      return b2;
    }
    return b2;
  }
  function Di(a3, b2, c2, d2) {
    b2 = a3.memoizedState;
    c2 = c2(d2, b2);
    c2 = null === c2 || void 0 === c2 ? b2 : A2({}, b2, c2);
    a3.memoizedState = c2;
    0 === a3.lanes && (a3.updateQueue.baseState = c2);
  }
  var Ei = { isMounted: function(a3) {
    return (a3 = a3._reactInternals) ? Vb(a3) === a3 : false;
  }, enqueueSetState: function(a3, b2, c2) {
    a3 = a3._reactInternals;
    var d2 = R2(), e2 = yi(a3), f2 = mh(d2, e2);
    f2.payload = b2;
    void 0 !== c2 && null !== c2 && (f2.callback = c2);
    b2 = nh(a3, f2, e2);
    null !== b2 && (gi(b2, a3, e2, d2), oh(b2, a3, e2));
  }, enqueueReplaceState: function(a3, b2, c2) {
    a3 = a3._reactInternals;
    var d2 = R2(), e2 = yi(a3), f2 = mh(d2, e2);
    f2.tag = 1;
    f2.payload = b2;
    void 0 !== c2 && null !== c2 && (f2.callback = c2);
    b2 = nh(a3, f2, e2);
    null !== b2 && (gi(b2, a3, e2, d2), oh(b2, a3, e2));
  }, enqueueForceUpdate: function(a3, b2) {
    a3 = a3._reactInternals;
    var c2 = R2(), d2 = yi(a3), e2 = mh(c2, d2);
    e2.tag = 2;
    void 0 !== b2 && null !== b2 && (e2.callback = b2);
    b2 = nh(a3, e2, d2);
    null !== b2 && (gi(b2, a3, d2, c2), oh(b2, a3, d2));
  } };
  function Fi(a3, b2, c2, d2, e2, f2, g2) {
    a3 = a3.stateNode;
    return "function" === typeof a3.shouldComponentUpdate ? a3.shouldComponentUpdate(d2, f2, g2) : b2.prototype && b2.prototype.isPureReactComponent ? !Ie2(c2, d2) || !Ie2(e2, f2) : true;
  }
  function Gi(a3, b2, c2) {
    var d2 = false, e2 = Vf;
    var f2 = b2.contextType;
    "object" === typeof f2 && null !== f2 ? f2 = eh(f2) : (e2 = Zf(b2) ? Xf : H2.current, d2 = b2.contextTypes, f2 = (d2 = null !== d2 && void 0 !== d2) ? Yf(a3, e2) : Vf);
    b2 = new b2(c2, f2);
    a3.memoizedState = null !== b2.state && void 0 !== b2.state ? b2.state : null;
    b2.updater = Ei;
    a3.stateNode = b2;
    b2._reactInternals = a3;
    d2 && (a3 = a3.stateNode, a3.__reactInternalMemoizedUnmaskedChildContext = e2, a3.__reactInternalMemoizedMaskedChildContext = f2);
    return b2;
  }
  function Hi(a3, b2, c2, d2) {
    a3 = b2.state;
    "function" === typeof b2.componentWillReceiveProps && b2.componentWillReceiveProps(c2, d2);
    "function" === typeof b2.UNSAFE_componentWillReceiveProps && b2.UNSAFE_componentWillReceiveProps(c2, d2);
    b2.state !== a3 && Ei.enqueueReplaceState(b2, b2.state, null);
  }
  function Ii(a3, b2, c2, d2) {
    var e2 = a3.stateNode;
    e2.props = c2;
    e2.state = a3.memoizedState;
    e2.refs = {};
    kh(a3);
    var f2 = b2.contextType;
    "object" === typeof f2 && null !== f2 ? e2.context = eh(f2) : (f2 = Zf(b2) ? Xf : H2.current, e2.context = Yf(a3, f2));
    e2.state = a3.memoizedState;
    f2 = b2.getDerivedStateFromProps;
    "function" === typeof f2 && (Di(a3, b2, f2, c2), e2.state = a3.memoizedState);
    "function" === typeof b2.getDerivedStateFromProps || "function" === typeof e2.getSnapshotBeforeUpdate || "function" !== typeof e2.UNSAFE_componentWillMount && "function" !== typeof e2.componentWillMount || (b2 = e2.state, "function" === typeof e2.componentWillMount && e2.componentWillMount(), "function" === typeof e2.UNSAFE_componentWillMount && e2.UNSAFE_componentWillMount(), b2 !== e2.state && Ei.enqueueReplaceState(e2, e2.state, null), qh(a3, c2, e2, d2), e2.state = a3.memoizedState);
    "function" === typeof e2.componentDidMount && (a3.flags |= 4194308);
  }
  function Ji(a3, b2) {
    try {
      var c2 = "", d2 = b2;
      do
        c2 += Pa(d2), d2 = d2.return;
      while (d2);
      var e2 = c2;
    } catch (f2) {
      e2 = "\nError generating stack: " + f2.message + "\n" + f2.stack;
    }
    return { value: a3, source: b2, stack: e2, digest: null };
  }
  function Ki(a3, b2, c2) {
    return { value: a3, source: null, stack: null != c2 ? c2 : null, digest: null != b2 ? b2 : null };
  }
  function Li(a3, b2) {
    try {
      console.error(b2.value);
    } catch (c2) {
      setTimeout(function() {
        throw c2;
      });
    }
  }
  var Mi = "function" === typeof WeakMap ? WeakMap : Map;
  function Ni(a3, b2, c2) {
    c2 = mh(-1, c2);
    c2.tag = 3;
    c2.payload = { element: null };
    var d2 = b2.value;
    c2.callback = function() {
      Oi || (Oi = true, Pi = d2);
      Li(a3, b2);
    };
    return c2;
  }
  function Qi(a3, b2, c2) {
    c2 = mh(-1, c2);
    c2.tag = 3;
    var d2 = a3.type.getDerivedStateFromError;
    if ("function" === typeof d2) {
      var e2 = b2.value;
      c2.payload = function() {
        return d2(e2);
      };
      c2.callback = function() {
        Li(a3, b2);
      };
    }
    var f2 = a3.stateNode;
    null !== f2 && "function" === typeof f2.componentDidCatch && (c2.callback = function() {
      Li(a3, b2);
      "function" !== typeof d2 && (null === Ri ? Ri = /* @__PURE__ */ new Set([this]) : Ri.add(this));
      var c3 = b2.stack;
      this.componentDidCatch(b2.value, { componentStack: null !== c3 ? c3 : "" });
    });
    return c2;
  }
  function Si(a3, b2, c2) {
    var d2 = a3.pingCache;
    if (null === d2) {
      d2 = a3.pingCache = new Mi();
      var e2 = /* @__PURE__ */ new Set();
      d2.set(b2, e2);
    } else e2 = d2.get(b2), void 0 === e2 && (e2 = /* @__PURE__ */ new Set(), d2.set(b2, e2));
    e2.has(c2) || (e2.add(c2), a3 = Ti.bind(null, a3, b2, c2), b2.then(a3, a3));
  }
  function Ui(a3) {
    do {
      var b2;
      if (b2 = 13 === a3.tag) b2 = a3.memoizedState, b2 = null !== b2 ? null !== b2.dehydrated ? true : false : true;
      if (b2) return a3;
      a3 = a3.return;
    } while (null !== a3);
    return null;
  }
  function Vi(a3, b2, c2, d2, e2) {
    if (0 === (a3.mode & 1)) return a3 === b2 ? a3.flags |= 65536 : (a3.flags |= 128, c2.flags |= 131072, c2.flags &= -52805, 1 === c2.tag && (null === c2.alternate ? c2.tag = 17 : (b2 = mh(-1, 1), b2.tag = 2, nh(c2, b2, 1))), c2.lanes |= 1), a3;
    a3.flags |= 65536;
    a3.lanes = e2;
    return a3;
  }
  var Wi = ua2.ReactCurrentOwner, dh = false;
  function Xi(a3, b2, c2, d2) {
    b2.child = null === a3 ? Vg(b2, null, c2, d2) : Ug(b2, a3.child, c2, d2);
  }
  function Yi(a3, b2, c2, d2, e2) {
    c2 = c2.render;
    var f2 = b2.ref;
    ch(b2, e2);
    d2 = Nh(a3, b2, c2, d2, f2, e2);
    c2 = Sh();
    if (null !== a3 && !dh) return b2.updateQueue = a3.updateQueue, b2.flags &= -2053, a3.lanes &= ~e2, Zi(a3, b2, e2);
    I2 && c2 && vg(b2);
    b2.flags |= 1;
    Xi(a3, b2, d2, e2);
    return b2.child;
  }
  function $i(a3, b2, c2, d2, e2) {
    if (null === a3) {
      var f2 = c2.type;
      if ("function" === typeof f2 && !aj(f2) && void 0 === f2.defaultProps && null === c2.compare && void 0 === c2.defaultProps) return b2.tag = 15, b2.type = f2, bj(a3, b2, f2, d2, e2);
      a3 = Rg(c2.type, null, d2, b2, b2.mode, e2);
      a3.ref = b2.ref;
      a3.return = b2;
      return b2.child = a3;
    }
    f2 = a3.child;
    if (0 === (a3.lanes & e2)) {
      var g2 = f2.memoizedProps;
      c2 = c2.compare;
      c2 = null !== c2 ? c2 : Ie2;
      if (c2(g2, d2) && a3.ref === b2.ref) return Zi(a3, b2, e2);
    }
    b2.flags |= 1;
    a3 = Pg(f2, d2);
    a3.ref = b2.ref;
    a3.return = b2;
    return b2.child = a3;
  }
  function bj(a3, b2, c2, d2, e2) {
    if (null !== a3) {
      var f2 = a3.memoizedProps;
      if (Ie2(f2, d2) && a3.ref === b2.ref) if (dh = false, b2.pendingProps = d2 = f2, 0 !== (a3.lanes & e2)) 0 !== (a3.flags & 131072) && (dh = true);
      else return b2.lanes = a3.lanes, Zi(a3, b2, e2);
    }
    return cj(a3, b2, c2, d2, e2);
  }
  function dj(a3, b2, c2) {
    var d2 = b2.pendingProps, e2 = d2.children, f2 = null !== a3 ? a3.memoizedState : null;
    if ("hidden" === d2.mode) if (0 === (b2.mode & 1)) b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G2(ej, fj), fj |= c2;
    else {
      if (0 === (c2 & 1073741824)) return a3 = null !== f2 ? f2.baseLanes | c2 : c2, b2.lanes = b2.childLanes = 1073741824, b2.memoizedState = { baseLanes: a3, cachePool: null, transitions: null }, b2.updateQueue = null, G2(ej, fj), fj |= a3, null;
      b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null };
      d2 = null !== f2 ? f2.baseLanes : c2;
      G2(ej, fj);
      fj |= d2;
    }
    else null !== f2 ? (d2 = f2.baseLanes | c2, b2.memoizedState = null) : d2 = c2, G2(ej, fj), fj |= d2;
    Xi(a3, b2, e2, c2);
    return b2.child;
  }
  function gj(a3, b2) {
    var c2 = b2.ref;
    if (null === a3 && null !== c2 || null !== a3 && a3.ref !== c2) b2.flags |= 512, b2.flags |= 2097152;
  }
  function cj(a3, b2, c2, d2, e2) {
    var f2 = Zf(c2) ? Xf : H2.current;
    f2 = Yf(b2, f2);
    ch(b2, e2);
    c2 = Nh(a3, b2, c2, d2, f2, e2);
    d2 = Sh();
    if (null !== a3 && !dh) return b2.updateQueue = a3.updateQueue, b2.flags &= -2053, a3.lanes &= ~e2, Zi(a3, b2, e2);
    I2 && d2 && vg(b2);
    b2.flags |= 1;
    Xi(a3, b2, c2, e2);
    return b2.child;
  }
  function hj(a3, b2, c2, d2, e2) {
    if (Zf(c2)) {
      var f2 = true;
      cg(b2);
    } else f2 = false;
    ch(b2, e2);
    if (null === b2.stateNode) ij(a3, b2), Gi(b2, c2, d2), Ii(b2, c2, d2, e2), d2 = true;
    else if (null === a3) {
      var g2 = b2.stateNode, h2 = b2.memoizedProps;
      g2.props = h2;
      var k2 = g2.context, l2 = c2.contextType;
      "object" === typeof l2 && null !== l2 ? l2 = eh(l2) : (l2 = Zf(c2) ? Xf : H2.current, l2 = Yf(b2, l2));
      var m2 = c2.getDerivedStateFromProps, q3 = "function" === typeof m2 || "function" === typeof g2.getSnapshotBeforeUpdate;
      q3 || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== d2 || k2 !== l2) && Hi(b2, g2, d2, l2);
      jh = false;
      var r2 = b2.memoizedState;
      g2.state = r2;
      qh(b2, d2, g2, e2);
      k2 = b2.memoizedState;
      h2 !== d2 || r2 !== k2 || Wf.current || jh ? ("function" === typeof m2 && (Di(b2, c2, m2, d2), k2 = b2.memoizedState), (h2 = jh || Fi(b2, c2, h2, d2, r2, k2, l2)) ? (q3 || "function" !== typeof g2.UNSAFE_componentWillMount && "function" !== typeof g2.componentWillMount || ("function" === typeof g2.componentWillMount && g2.componentWillMount(), "function" === typeof g2.UNSAFE_componentWillMount && g2.UNSAFE_componentWillMount()), "function" === typeof g2.componentDidMount && (b2.flags |= 4194308)) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), b2.memoizedProps = d2, b2.memoizedState = k2), g2.props = d2, g2.state = k2, g2.context = l2, d2 = h2) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), d2 = false);
    } else {
      g2 = b2.stateNode;
      lh(a3, b2);
      h2 = b2.memoizedProps;
      l2 = b2.type === b2.elementType ? h2 : Ci(b2.type, h2);
      g2.props = l2;
      q3 = b2.pendingProps;
      r2 = g2.context;
      k2 = c2.contextType;
      "object" === typeof k2 && null !== k2 ? k2 = eh(k2) : (k2 = Zf(c2) ? Xf : H2.current, k2 = Yf(b2, k2));
      var y2 = c2.getDerivedStateFromProps;
      (m2 = "function" === typeof y2 || "function" === typeof g2.getSnapshotBeforeUpdate) || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== q3 || r2 !== k2) && Hi(b2, g2, d2, k2);
      jh = false;
      r2 = b2.memoizedState;
      g2.state = r2;
      qh(b2, d2, g2, e2);
      var n2 = b2.memoizedState;
      h2 !== q3 || r2 !== n2 || Wf.current || jh ? ("function" === typeof y2 && (Di(b2, c2, y2, d2), n2 = b2.memoizedState), (l2 = jh || Fi(b2, c2, l2, d2, r2, n2, k2) || false) ? (m2 || "function" !== typeof g2.UNSAFE_componentWillUpdate && "function" !== typeof g2.componentWillUpdate || ("function" === typeof g2.componentWillUpdate && g2.componentWillUpdate(d2, n2, k2), "function" === typeof g2.UNSAFE_componentWillUpdate && g2.UNSAFE_componentWillUpdate(d2, n2, k2)), "function" === typeof g2.componentDidUpdate && (b2.flags |= 4), "function" === typeof g2.getSnapshotBeforeUpdate && (b2.flags |= 1024)) : ("function" !== typeof g2.componentDidUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 1024), b2.memoizedProps = d2, b2.memoizedState = n2), g2.props = d2, g2.state = n2, g2.context = k2, d2 = l2) : ("function" !== typeof g2.componentDidUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 1024), d2 = false);
    }
    return jj(a3, b2, c2, d2, f2, e2);
  }
  function jj(a3, b2, c2, d2, e2, f2) {
    gj(a3, b2);
    var g2 = 0 !== (b2.flags & 128);
    if (!d2 && !g2) return e2 && dg(b2, c2, false), Zi(a3, b2, f2);
    d2 = b2.stateNode;
    Wi.current = b2;
    var h2 = g2 && "function" !== typeof c2.getDerivedStateFromError ? null : d2.render();
    b2.flags |= 1;
    null !== a3 && g2 ? (b2.child = Ug(b2, a3.child, null, f2), b2.child = Ug(b2, null, h2, f2)) : Xi(a3, b2, h2, f2);
    b2.memoizedState = d2.state;
    e2 && dg(b2, c2, true);
    return b2.child;
  }
  function kj(a3) {
    var b2 = a3.stateNode;
    b2.pendingContext ? ag(a3, b2.pendingContext, b2.pendingContext !== b2.context) : b2.context && ag(a3, b2.context, false);
    yh(a3, b2.containerInfo);
  }
  function lj(a3, b2, c2, d2, e2) {
    Ig();
    Jg(e2);
    b2.flags |= 256;
    Xi(a3, b2, c2, d2);
    return b2.child;
  }
  var mj = { dehydrated: null, treeContext: null, retryLane: 0 };
  function nj(a3) {
    return { baseLanes: a3, cachePool: null, transitions: null };
  }
  function oj(a3, b2, c2) {
    var d2 = b2.pendingProps, e2 = L2.current, f2 = false, g2 = 0 !== (b2.flags & 128), h2;
    (h2 = g2) || (h2 = null !== a3 && null === a3.memoizedState ? false : 0 !== (e2 & 2));
    if (h2) f2 = true, b2.flags &= -129;
    else if (null === a3 || null !== a3.memoizedState) e2 |= 1;
    G2(L2, e2 & 1);
    if (null === a3) {
      Eg(b2);
      a3 = b2.memoizedState;
      if (null !== a3 && (a3 = a3.dehydrated, null !== a3)) return 0 === (b2.mode & 1) ? b2.lanes = 1 : "$!" === a3.data ? b2.lanes = 8 : b2.lanes = 1073741824, null;
      g2 = d2.children;
      a3 = d2.fallback;
      return f2 ? (d2 = b2.mode, f2 = b2.child, g2 = { mode: "hidden", children: g2 }, 0 === (d2 & 1) && null !== f2 ? (f2.childLanes = 0, f2.pendingProps = g2) : f2 = pj(g2, d2, 0, null), a3 = Tg(a3, d2, c2, null), f2.return = b2, a3.return = b2, f2.sibling = a3, b2.child = f2, b2.child.memoizedState = nj(c2), b2.memoizedState = mj, a3) : qj(b2, g2);
    }
    e2 = a3.memoizedState;
    if (null !== e2 && (h2 = e2.dehydrated, null !== h2)) return rj(a3, b2, g2, d2, h2, e2, c2);
    if (f2) {
      f2 = d2.fallback;
      g2 = b2.mode;
      e2 = a3.child;
      h2 = e2.sibling;
      var k2 = { mode: "hidden", children: d2.children };
      0 === (g2 & 1) && b2.child !== e2 ? (d2 = b2.child, d2.childLanes = 0, d2.pendingProps = k2, b2.deletions = null) : (d2 = Pg(e2, k2), d2.subtreeFlags = e2.subtreeFlags & 14680064);
      null !== h2 ? f2 = Pg(h2, f2) : (f2 = Tg(f2, g2, c2, null), f2.flags |= 2);
      f2.return = b2;
      d2.return = b2;
      d2.sibling = f2;
      b2.child = d2;
      d2 = f2;
      f2 = b2.child;
      g2 = a3.child.memoizedState;
      g2 = null === g2 ? nj(c2) : { baseLanes: g2.baseLanes | c2, cachePool: null, transitions: g2.transitions };
      f2.memoizedState = g2;
      f2.childLanes = a3.childLanes & ~c2;
      b2.memoizedState = mj;
      return d2;
    }
    f2 = a3.child;
    a3 = f2.sibling;
    d2 = Pg(f2, { mode: "visible", children: d2.children });
    0 === (b2.mode & 1) && (d2.lanes = c2);
    d2.return = b2;
    d2.sibling = null;
    null !== a3 && (c2 = b2.deletions, null === c2 ? (b2.deletions = [a3], b2.flags |= 16) : c2.push(a3));
    b2.child = d2;
    b2.memoizedState = null;
    return d2;
  }
  function qj(a3, b2) {
    b2 = pj({ mode: "visible", children: b2 }, a3.mode, 0, null);
    b2.return = a3;
    return a3.child = b2;
  }
  function sj(a3, b2, c2, d2) {
    null !== d2 && Jg(d2);
    Ug(b2, a3.child, null, c2);
    a3 = qj(b2, b2.pendingProps.children);
    a3.flags |= 2;
    b2.memoizedState = null;
    return a3;
  }
  function rj(a3, b2, c2, d2, e2, f2, g2) {
    if (c2) {
      if (b2.flags & 256) return b2.flags &= -257, d2 = Ki(Error(p2(422))), sj(a3, b2, g2, d2);
      if (null !== b2.memoizedState) return b2.child = a3.child, b2.flags |= 128, null;
      f2 = d2.fallback;
      e2 = b2.mode;
      d2 = pj({ mode: "visible", children: d2.children }, e2, 0, null);
      f2 = Tg(f2, e2, g2, null);
      f2.flags |= 2;
      d2.return = b2;
      f2.return = b2;
      d2.sibling = f2;
      b2.child = d2;
      0 !== (b2.mode & 1) && Ug(b2, a3.child, null, g2);
      b2.child.memoizedState = nj(g2);
      b2.memoizedState = mj;
      return f2;
    }
    if (0 === (b2.mode & 1)) return sj(a3, b2, g2, null);
    if ("$!" === e2.data) {
      d2 = e2.nextSibling && e2.nextSibling.dataset;
      if (d2) var h2 = d2.dgst;
      d2 = h2;
      f2 = Error(p2(419));
      d2 = Ki(f2, d2, void 0);
      return sj(a3, b2, g2, d2);
    }
    h2 = 0 !== (g2 & a3.childLanes);
    if (dh || h2) {
      d2 = Q2;
      if (null !== d2) {
        switch (g2 & -g2) {
          case 4:
            e2 = 2;
            break;
          case 16:
            e2 = 8;
            break;
          case 64:
          case 128:
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
          case 67108864:
            e2 = 32;
            break;
          case 536870912:
            e2 = 268435456;
            break;
          default:
            e2 = 0;
        }
        e2 = 0 !== (e2 & (d2.suspendedLanes | g2)) ? 0 : e2;
        0 !== e2 && e2 !== f2.retryLane && (f2.retryLane = e2, ih(a3, e2), gi(d2, a3, e2, -1));
      }
      tj();
      d2 = Ki(Error(p2(421)));
      return sj(a3, b2, g2, d2);
    }
    if ("$?" === e2.data) return b2.flags |= 128, b2.child = a3.child, b2 = uj.bind(null, a3), e2._reactRetry = b2, null;
    a3 = f2.treeContext;
    yg = Lf(e2.nextSibling);
    xg = b2;
    I2 = true;
    zg = null;
    null !== a3 && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a3.id, sg = a3.overflow, qg = b2);
    b2 = qj(b2, d2.children);
    b2.flags |= 4096;
    return b2;
  }
  function vj(a3, b2, c2) {
    a3.lanes |= b2;
    var d2 = a3.alternate;
    null !== d2 && (d2.lanes |= b2);
    bh(a3.return, b2, c2);
  }
  function wj(a3, b2, c2, d2, e2) {
    var f2 = a3.memoizedState;
    null === f2 ? a3.memoizedState = { isBackwards: b2, rendering: null, renderingStartTime: 0, last: d2, tail: c2, tailMode: e2 } : (f2.isBackwards = b2, f2.rendering = null, f2.renderingStartTime = 0, f2.last = d2, f2.tail = c2, f2.tailMode = e2);
  }
  function xj(a3, b2, c2) {
    var d2 = b2.pendingProps, e2 = d2.revealOrder, f2 = d2.tail;
    Xi(a3, b2, d2.children, c2);
    d2 = L2.current;
    if (0 !== (d2 & 2)) d2 = d2 & 1 | 2, b2.flags |= 128;
    else {
      if (null !== a3 && 0 !== (a3.flags & 128)) a: for (a3 = b2.child; null !== a3; ) {
        if (13 === a3.tag) null !== a3.memoizedState && vj(a3, c2, b2);
        else if (19 === a3.tag) vj(a3, c2, b2);
        else if (null !== a3.child) {
          a3.child.return = a3;
          a3 = a3.child;
          continue;
        }
        if (a3 === b2) break a;
        for (; null === a3.sibling; ) {
          if (null === a3.return || a3.return === b2) break a;
          a3 = a3.return;
        }
        a3.sibling.return = a3.return;
        a3 = a3.sibling;
      }
      d2 &= 1;
    }
    G2(L2, d2);
    if (0 === (b2.mode & 1)) b2.memoizedState = null;
    else switch (e2) {
      case "forwards":
        c2 = b2.child;
        for (e2 = null; null !== c2; ) a3 = c2.alternate, null !== a3 && null === Ch(a3) && (e2 = c2), c2 = c2.sibling;
        c2 = e2;
        null === c2 ? (e2 = b2.child, b2.child = null) : (e2 = c2.sibling, c2.sibling = null);
        wj(b2, false, e2, c2, f2);
        break;
      case "backwards":
        c2 = null;
        e2 = b2.child;
        for (b2.child = null; null !== e2; ) {
          a3 = e2.alternate;
          if (null !== a3 && null === Ch(a3)) {
            b2.child = e2;
            break;
          }
          a3 = e2.sibling;
          e2.sibling = c2;
          c2 = e2;
          e2 = a3;
        }
        wj(b2, true, c2, null, f2);
        break;
      case "together":
        wj(b2, false, null, null, void 0);
        break;
      default:
        b2.memoizedState = null;
    }
    return b2.child;
  }
  function ij(a3, b2) {
    0 === (b2.mode & 1) && null !== a3 && (a3.alternate = null, b2.alternate = null, b2.flags |= 2);
  }
  function Zi(a3, b2, c2) {
    null !== a3 && (b2.dependencies = a3.dependencies);
    rh |= b2.lanes;
    if (0 === (c2 & b2.childLanes)) return null;
    if (null !== a3 && b2.child !== a3.child) throw Error(p2(153));
    if (null !== b2.child) {
      a3 = b2.child;
      c2 = Pg(a3, a3.pendingProps);
      b2.child = c2;
      for (c2.return = b2; null !== a3.sibling; ) a3 = a3.sibling, c2 = c2.sibling = Pg(a3, a3.pendingProps), c2.return = b2;
      c2.sibling = null;
    }
    return b2.child;
  }
  function yj(a3, b2, c2) {
    switch (b2.tag) {
      case 3:
        kj(b2);
        Ig();
        break;
      case 5:
        Ah(b2);
        break;
      case 1:
        Zf(b2.type) && cg(b2);
        break;
      case 4:
        yh(b2, b2.stateNode.containerInfo);
        break;
      case 10:
        var d2 = b2.type._context, e2 = b2.memoizedProps.value;
        G2(Wg, d2._currentValue);
        d2._currentValue = e2;
        break;
      case 13:
        d2 = b2.memoizedState;
        if (null !== d2) {
          if (null !== d2.dehydrated) return G2(L2, L2.current & 1), b2.flags |= 128, null;
          if (0 !== (c2 & b2.child.childLanes)) return oj(a3, b2, c2);
          G2(L2, L2.current & 1);
          a3 = Zi(a3, b2, c2);
          return null !== a3 ? a3.sibling : null;
        }
        G2(L2, L2.current & 1);
        break;
      case 19:
        d2 = 0 !== (c2 & b2.childLanes);
        if (0 !== (a3.flags & 128)) {
          if (d2) return xj(a3, b2, c2);
          b2.flags |= 128;
        }
        e2 = b2.memoizedState;
        null !== e2 && (e2.rendering = null, e2.tail = null, e2.lastEffect = null);
        G2(L2, L2.current);
        if (d2) break;
        else return null;
      case 22:
      case 23:
        return b2.lanes = 0, dj(a3, b2, c2);
    }
    return Zi(a3, b2, c2);
  }
  var zj, Aj, Bj, Cj;
  zj = function(a3, b2) {
    for (var c2 = b2.child; null !== c2; ) {
      if (5 === c2.tag || 6 === c2.tag) a3.appendChild(c2.stateNode);
      else if (4 !== c2.tag && null !== c2.child) {
        c2.child.return = c2;
        c2 = c2.child;
        continue;
      }
      if (c2 === b2) break;
      for (; null === c2.sibling; ) {
        if (null === c2.return || c2.return === b2) return;
        c2 = c2.return;
      }
      c2.sibling.return = c2.return;
      c2 = c2.sibling;
    }
  };
  Aj = function() {
  };
  Bj = function(a3, b2, c2, d2) {
    var e2 = a3.memoizedProps;
    if (e2 !== d2) {
      a3 = b2.stateNode;
      xh(uh.current);
      var f2 = null;
      switch (c2) {
        case "input":
          e2 = Ya(a3, e2);
          d2 = Ya(a3, d2);
          f2 = [];
          break;
        case "select":
          e2 = A2({}, e2, { value: void 0 });
          d2 = A2({}, d2, { value: void 0 });
          f2 = [];
          break;
        case "textarea":
          e2 = gb(a3, e2);
          d2 = gb(a3, d2);
          f2 = [];
          break;
        default:
          "function" !== typeof e2.onClick && "function" === typeof d2.onClick && (a3.onclick = Bf);
      }
      ub(c2, d2);
      var g2;
      c2 = null;
      for (l2 in e2) if (!d2.hasOwnProperty(l2) && e2.hasOwnProperty(l2) && null != e2[l2]) if ("style" === l2) {
        var h2 = e2[l2];
        for (g2 in h2) h2.hasOwnProperty(g2) && (c2 || (c2 = {}), c2[g2] = "");
      } else "dangerouslySetInnerHTML" !== l2 && "children" !== l2 && "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && "autoFocus" !== l2 && (ea2.hasOwnProperty(l2) ? f2 || (f2 = []) : (f2 = f2 || []).push(l2, null));
      for (l2 in d2) {
        var k2 = d2[l2];
        h2 = null != e2 ? e2[l2] : void 0;
        if (d2.hasOwnProperty(l2) && k2 !== h2 && (null != k2 || null != h2)) if ("style" === l2) if (h2) {
          for (g2 in h2) !h2.hasOwnProperty(g2) || k2 && k2.hasOwnProperty(g2) || (c2 || (c2 = {}), c2[g2] = "");
          for (g2 in k2) k2.hasOwnProperty(g2) && h2[g2] !== k2[g2] && (c2 || (c2 = {}), c2[g2] = k2[g2]);
        } else c2 || (f2 || (f2 = []), f2.push(
          l2,
          c2
        )), c2 = k2;
        else "dangerouslySetInnerHTML" === l2 ? (k2 = k2 ? k2.__html : void 0, h2 = h2 ? h2.__html : void 0, null != k2 && h2 !== k2 && (f2 = f2 || []).push(l2, k2)) : "children" === l2 ? "string" !== typeof k2 && "number" !== typeof k2 || (f2 = f2 || []).push(l2, "" + k2) : "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && (ea2.hasOwnProperty(l2) ? (null != k2 && "onScroll" === l2 && D2("scroll", a3), f2 || h2 === k2 || (f2 = [])) : (f2 = f2 || []).push(l2, k2));
      }
      c2 && (f2 = f2 || []).push("style", c2);
      var l2 = f2;
      if (b2.updateQueue = l2) b2.flags |= 4;
    }
  };
  Cj = function(a3, b2, c2, d2) {
    c2 !== d2 && (b2.flags |= 4);
  };
  function Dj(a3, b2) {
    if (!I2) switch (a3.tailMode) {
      case "hidden":
        b2 = a3.tail;
        for (var c2 = null; null !== b2; ) null !== b2.alternate && (c2 = b2), b2 = b2.sibling;
        null === c2 ? a3.tail = null : c2.sibling = null;
        break;
      case "collapsed":
        c2 = a3.tail;
        for (var d2 = null; null !== c2; ) null !== c2.alternate && (d2 = c2), c2 = c2.sibling;
        null === d2 ? b2 || null === a3.tail ? a3.tail = null : a3.tail.sibling = null : d2.sibling = null;
    }
  }
  function S2(a3) {
    var b2 = null !== a3.alternate && a3.alternate.child === a3.child, c2 = 0, d2 = 0;
    if (b2) for (var e2 = a3.child; null !== e2; ) c2 |= e2.lanes | e2.childLanes, d2 |= e2.subtreeFlags & 14680064, d2 |= e2.flags & 14680064, e2.return = a3, e2 = e2.sibling;
    else for (e2 = a3.child; null !== e2; ) c2 |= e2.lanes | e2.childLanes, d2 |= e2.subtreeFlags, d2 |= e2.flags, e2.return = a3, e2 = e2.sibling;
    a3.subtreeFlags |= d2;
    a3.childLanes = c2;
    return b2;
  }
  function Ej(a3, b2, c2) {
    var d2 = b2.pendingProps;
    wg(b2);
    switch (b2.tag) {
      case 2:
      case 16:
      case 15:
      case 0:
      case 11:
      case 7:
      case 8:
      case 12:
      case 9:
      case 14:
        return S2(b2), null;
      case 1:
        return Zf(b2.type) && $f(), S2(b2), null;
      case 3:
        d2 = b2.stateNode;
        zh();
        E2(Wf);
        E2(H2);
        Eh();
        d2.pendingContext && (d2.context = d2.pendingContext, d2.pendingContext = null);
        if (null === a3 || null === a3.child) Gg(b2) ? b2.flags |= 4 : null === a3 || a3.memoizedState.isDehydrated && 0 === (b2.flags & 256) || (b2.flags |= 1024, null !== zg && (Fj(zg), zg = null));
        Aj(a3, b2);
        S2(b2);
        return null;
      case 5:
        Bh(b2);
        var e2 = xh(wh.current);
        c2 = b2.type;
        if (null !== a3 && null != b2.stateNode) Bj(a3, b2, c2, d2, e2), a3.ref !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
        else {
          if (!d2) {
            if (null === b2.stateNode) throw Error(p2(166));
            S2(b2);
            return null;
          }
          a3 = xh(uh.current);
          if (Gg(b2)) {
            d2 = b2.stateNode;
            c2 = b2.type;
            var f2 = b2.memoizedProps;
            d2[Of] = b2;
            d2[Pf] = f2;
            a3 = 0 !== (b2.mode & 1);
            switch (c2) {
              case "dialog":
                D2("cancel", d2);
                D2("close", d2);
                break;
              case "iframe":
              case "object":
              case "embed":
                D2("load", d2);
                break;
              case "video":
              case "audio":
                for (e2 = 0; e2 < lf.length; e2++) D2(lf[e2], d2);
                break;
              case "source":
                D2("error", d2);
                break;
              case "img":
              case "image":
              case "link":
                D2(
                  "error",
                  d2
                );
                D2("load", d2);
                break;
              case "details":
                D2("toggle", d2);
                break;
              case "input":
                Za(d2, f2);
                D2("invalid", d2);
                break;
              case "select":
                d2._wrapperState = { wasMultiple: !!f2.multiple };
                D2("invalid", d2);
                break;
              case "textarea":
                hb(d2, f2), D2("invalid", d2);
            }
            ub(c2, f2);
            e2 = null;
            for (var g2 in f2) if (f2.hasOwnProperty(g2)) {
              var h2 = f2[g2];
              "children" === g2 ? "string" === typeof h2 ? d2.textContent !== h2 && (true !== f2.suppressHydrationWarning && Af(d2.textContent, h2, a3), e2 = ["children", h2]) : "number" === typeof h2 && d2.textContent !== "" + h2 && (true !== f2.suppressHydrationWarning && Af(
                d2.textContent,
                h2,
                a3
              ), e2 = ["children", "" + h2]) : ea2.hasOwnProperty(g2) && null != h2 && "onScroll" === g2 && D2("scroll", d2);
            }
            switch (c2) {
              case "input":
                Va(d2);
                db(d2, f2, true);
                break;
              case "textarea":
                Va(d2);
                jb(d2);
                break;
              case "select":
              case "option":
                break;
              default:
                "function" === typeof f2.onClick && (d2.onclick = Bf);
            }
            d2 = e2;
            b2.updateQueue = d2;
            null !== d2 && (b2.flags |= 4);
          } else {
            g2 = 9 === e2.nodeType ? e2 : e2.ownerDocument;
            "http://www.w3.org/1999/xhtml" === a3 && (a3 = kb(c2));
            "http://www.w3.org/1999/xhtml" === a3 ? "script" === c2 ? (a3 = g2.createElement("div"), a3.innerHTML = "<script><\/script>", a3 = a3.removeChild(a3.firstChild)) : "string" === typeof d2.is ? a3 = g2.createElement(c2, { is: d2.is }) : (a3 = g2.createElement(c2), "select" === c2 && (g2 = a3, d2.multiple ? g2.multiple = true : d2.size && (g2.size = d2.size))) : a3 = g2.createElementNS(a3, c2);
            a3[Of] = b2;
            a3[Pf] = d2;
            zj(a3, b2, false, false);
            b2.stateNode = a3;
            a: {
              g2 = vb(c2, d2);
              switch (c2) {
                case "dialog":
                  D2("cancel", a3);
                  D2("close", a3);
                  e2 = d2;
                  break;
                case "iframe":
                case "object":
                case "embed":
                  D2("load", a3);
                  e2 = d2;
                  break;
                case "video":
                case "audio":
                  for (e2 = 0; e2 < lf.length; e2++) D2(lf[e2], a3);
                  e2 = d2;
                  break;
                case "source":
                  D2("error", a3);
                  e2 = d2;
                  break;
                case "img":
                case "image":
                case "link":
                  D2(
                    "error",
                    a3
                  );
                  D2("load", a3);
                  e2 = d2;
                  break;
                case "details":
                  D2("toggle", a3);
                  e2 = d2;
                  break;
                case "input":
                  Za(a3, d2);
                  e2 = Ya(a3, d2);
                  D2("invalid", a3);
                  break;
                case "option":
                  e2 = d2;
                  break;
                case "select":
                  a3._wrapperState = { wasMultiple: !!d2.multiple };
                  e2 = A2({}, d2, { value: void 0 });
                  D2("invalid", a3);
                  break;
                case "textarea":
                  hb(a3, d2);
                  e2 = gb(a3, d2);
                  D2("invalid", a3);
                  break;
                default:
                  e2 = d2;
              }
              ub(c2, e2);
              h2 = e2;
              for (f2 in h2) if (h2.hasOwnProperty(f2)) {
                var k2 = h2[f2];
                "style" === f2 ? sb(a3, k2) : "dangerouslySetInnerHTML" === f2 ? (k2 = k2 ? k2.__html : void 0, null != k2 && nb(a3, k2)) : "children" === f2 ? "string" === typeof k2 ? ("textarea" !== c2 || "" !== k2) && ob(a3, k2) : "number" === typeof k2 && ob(a3, "" + k2) : "suppressContentEditableWarning" !== f2 && "suppressHydrationWarning" !== f2 && "autoFocus" !== f2 && (ea2.hasOwnProperty(f2) ? null != k2 && "onScroll" === f2 && D2("scroll", a3) : null != k2 && ta(a3, f2, k2, g2));
              }
              switch (c2) {
                case "input":
                  Va(a3);
                  db(a3, d2, false);
                  break;
                case "textarea":
                  Va(a3);
                  jb(a3);
                  break;
                case "option":
                  null != d2.value && a3.setAttribute("value", "" + Sa(d2.value));
                  break;
                case "select":
                  a3.multiple = !!d2.multiple;
                  f2 = d2.value;
                  null != f2 ? fb(a3, !!d2.multiple, f2, false) : null != d2.defaultValue && fb(
                    a3,
                    !!d2.multiple,
                    d2.defaultValue,
                    true
                  );
                  break;
                default:
                  "function" === typeof e2.onClick && (a3.onclick = Bf);
              }
              switch (c2) {
                case "button":
                case "input":
                case "select":
                case "textarea":
                  d2 = !!d2.autoFocus;
                  break a;
                case "img":
                  d2 = true;
                  break a;
                default:
                  d2 = false;
              }
            }
            d2 && (b2.flags |= 4);
          }
          null !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
        }
        S2(b2);
        return null;
      case 6:
        if (a3 && null != b2.stateNode) Cj(a3, b2, a3.memoizedProps, d2);
        else {
          if ("string" !== typeof d2 && null === b2.stateNode) throw Error(p2(166));
          c2 = xh(wh.current);
          xh(uh.current);
          if (Gg(b2)) {
            d2 = b2.stateNode;
            c2 = b2.memoizedProps;
            d2[Of] = b2;
            if (f2 = d2.nodeValue !== c2) {
              if (a3 = xg, null !== a3) switch (a3.tag) {
                case 3:
                  Af(d2.nodeValue, c2, 0 !== (a3.mode & 1));
                  break;
                case 5:
                  true !== a3.memoizedProps.suppressHydrationWarning && Af(d2.nodeValue, c2, 0 !== (a3.mode & 1));
              }
            }
            f2 && (b2.flags |= 4);
          } else d2 = (9 === c2.nodeType ? c2 : c2.ownerDocument).createTextNode(d2), d2[Of] = b2, b2.stateNode = d2;
        }
        S2(b2);
        return null;
      case 13:
        E2(L2);
        d2 = b2.memoizedState;
        if (null === a3 || null !== a3.memoizedState && null !== a3.memoizedState.dehydrated) {
          if (I2 && null !== yg && 0 !== (b2.mode & 1) && 0 === (b2.flags & 128)) Hg(), Ig(), b2.flags |= 98560, f2 = false;
          else if (f2 = Gg(b2), null !== d2 && null !== d2.dehydrated) {
            if (null === a3) {
              if (!f2) throw Error(p2(318));
              f2 = b2.memoizedState;
              f2 = null !== f2 ? f2.dehydrated : null;
              if (!f2) throw Error(p2(317));
              f2[Of] = b2;
            } else Ig(), 0 === (b2.flags & 128) && (b2.memoizedState = null), b2.flags |= 4;
            S2(b2);
            f2 = false;
          } else null !== zg && (Fj(zg), zg = null), f2 = true;
          if (!f2) return b2.flags & 65536 ? b2 : null;
        }
        if (0 !== (b2.flags & 128)) return b2.lanes = c2, b2;
        d2 = null !== d2;
        d2 !== (null !== a3 && null !== a3.memoizedState) && d2 && (b2.child.flags |= 8192, 0 !== (b2.mode & 1) && (null === a3 || 0 !== (L2.current & 1) ? 0 === T3 && (T3 = 3) : tj()));
        null !== b2.updateQueue && (b2.flags |= 4);
        S2(b2);
        return null;
      case 4:
        return zh(), Aj(a3, b2), null === a3 && sf(b2.stateNode.containerInfo), S2(b2), null;
      case 10:
        return ah(b2.type._context), S2(b2), null;
      case 17:
        return Zf(b2.type) && $f(), S2(b2), null;
      case 19:
        E2(L2);
        f2 = b2.memoizedState;
        if (null === f2) return S2(b2), null;
        d2 = 0 !== (b2.flags & 128);
        g2 = f2.rendering;
        if (null === g2) if (d2) Dj(f2, false);
        else {
          if (0 !== T3 || null !== a3 && 0 !== (a3.flags & 128)) for (a3 = b2.child; null !== a3; ) {
            g2 = Ch(a3);
            if (null !== g2) {
              b2.flags |= 128;
              Dj(f2, false);
              d2 = g2.updateQueue;
              null !== d2 && (b2.updateQueue = d2, b2.flags |= 4);
              b2.subtreeFlags = 0;
              d2 = c2;
              for (c2 = b2.child; null !== c2; ) f2 = c2, a3 = d2, f2.flags &= 14680066, g2 = f2.alternate, null === g2 ? (f2.childLanes = 0, f2.lanes = a3, f2.child = null, f2.subtreeFlags = 0, f2.memoizedProps = null, f2.memoizedState = null, f2.updateQueue = null, f2.dependencies = null, f2.stateNode = null) : (f2.childLanes = g2.childLanes, f2.lanes = g2.lanes, f2.child = g2.child, f2.subtreeFlags = 0, f2.deletions = null, f2.memoizedProps = g2.memoizedProps, f2.memoizedState = g2.memoizedState, f2.updateQueue = g2.updateQueue, f2.type = g2.type, a3 = g2.dependencies, f2.dependencies = null === a3 ? null : { lanes: a3.lanes, firstContext: a3.firstContext }), c2 = c2.sibling;
              G2(L2, L2.current & 1 | 2);
              return b2.child;
            }
            a3 = a3.sibling;
          }
          null !== f2.tail && B() > Gj && (b2.flags |= 128, d2 = true, Dj(f2, false), b2.lanes = 4194304);
        }
        else {
          if (!d2) if (a3 = Ch(g2), null !== a3) {
            if (b2.flags |= 128, d2 = true, c2 = a3.updateQueue, null !== c2 && (b2.updateQueue = c2, b2.flags |= 4), Dj(f2, true), null === f2.tail && "hidden" === f2.tailMode && !g2.alternate && !I2) return S2(b2), null;
          } else 2 * B() - f2.renderingStartTime > Gj && 1073741824 !== c2 && (b2.flags |= 128, d2 = true, Dj(f2, false), b2.lanes = 4194304);
          f2.isBackwards ? (g2.sibling = b2.child, b2.child = g2) : (c2 = f2.last, null !== c2 ? c2.sibling = g2 : b2.child = g2, f2.last = g2);
        }
        if (null !== f2.tail) return b2 = f2.tail, f2.rendering = b2, f2.tail = b2.sibling, f2.renderingStartTime = B(), b2.sibling = null, c2 = L2.current, G2(L2, d2 ? c2 & 1 | 2 : c2 & 1), b2;
        S2(b2);
        return null;
      case 22:
      case 23:
        return Hj(), d2 = null !== b2.memoizedState, null !== a3 && null !== a3.memoizedState !== d2 && (b2.flags |= 8192), d2 && 0 !== (b2.mode & 1) ? 0 !== (fj & 1073741824) && (S2(b2), b2.subtreeFlags & 6 && (b2.flags |= 8192)) : S2(b2), null;
      case 24:
        return null;
      case 25:
        return null;
    }
    throw Error(p2(156, b2.tag));
  }
  function Ij(a3, b2) {
    wg(b2);
    switch (b2.tag) {
      case 1:
        return Zf(b2.type) && $f(), a3 = b2.flags, a3 & 65536 ? (b2.flags = a3 & -65537 | 128, b2) : null;
      case 3:
        return zh(), E2(Wf), E2(H2), Eh(), a3 = b2.flags, 0 !== (a3 & 65536) && 0 === (a3 & 128) ? (b2.flags = a3 & -65537 | 128, b2) : null;
      case 5:
        return Bh(b2), null;
      case 13:
        E2(L2);
        a3 = b2.memoizedState;
        if (null !== a3 && null !== a3.dehydrated) {
          if (null === b2.alternate) throw Error(p2(340));
          Ig();
        }
        a3 = b2.flags;
        return a3 & 65536 ? (b2.flags = a3 & -65537 | 128, b2) : null;
      case 19:
        return E2(L2), null;
      case 4:
        return zh(), null;
      case 10:
        return ah(b2.type._context), null;
      case 22:
      case 23:
        return Hj(), null;
      case 24:
        return null;
      default:
        return null;
    }
  }
  var Jj = false, U2 = false, Kj = "function" === typeof WeakSet ? WeakSet : Set, V2 = null;
  function Lj(a3, b2) {
    var c2 = a3.ref;
    if (null !== c2) if ("function" === typeof c2) try {
      c2(null);
    } catch (d2) {
      W2(a3, b2, d2);
    }
    else c2.current = null;
  }
  function Mj(a3, b2, c2) {
    try {
      c2();
    } catch (d2) {
      W2(a3, b2, d2);
    }
  }
  var Nj = false;
  function Oj(a3, b2) {
    Cf = dd;
    a3 = Me2();
    if (Ne2(a3)) {
      if ("selectionStart" in a3) var c2 = { start: a3.selectionStart, end: a3.selectionEnd };
      else a: {
        c2 = (c2 = a3.ownerDocument) && c2.defaultView || window;
        var d2 = c2.getSelection && c2.getSelection();
        if (d2 && 0 !== d2.rangeCount) {
          c2 = d2.anchorNode;
          var e2 = d2.anchorOffset, f2 = d2.focusNode;
          d2 = d2.focusOffset;
          try {
            c2.nodeType, f2.nodeType;
          } catch (F2) {
            c2 = null;
            break a;
          }
          var g2 = 0, h2 = -1, k2 = -1, l2 = 0, m2 = 0, q3 = a3, r2 = null;
          b: for (; ; ) {
            for (var y2; ; ) {
              q3 !== c2 || 0 !== e2 && 3 !== q3.nodeType || (h2 = g2 + e2);
              q3 !== f2 || 0 !== d2 && 3 !== q3.nodeType || (k2 = g2 + d2);
              3 === q3.nodeType && (g2 += q3.nodeValue.length);
              if (null === (y2 = q3.firstChild)) break;
              r2 = q3;
              q3 = y2;
            }
            for (; ; ) {
              if (q3 === a3) break b;
              r2 === c2 && ++l2 === e2 && (h2 = g2);
              r2 === f2 && ++m2 === d2 && (k2 = g2);
              if (null !== (y2 = q3.nextSibling)) break;
              q3 = r2;
              r2 = q3.parentNode;
            }
            q3 = y2;
          }
          c2 = -1 === h2 || -1 === k2 ? null : { start: h2, end: k2 };
        } else c2 = null;
      }
      c2 = c2 || { start: 0, end: 0 };
    } else c2 = null;
    Df = { focusedElem: a3, selectionRange: c2 };
    dd = false;
    for (V2 = b2; null !== V2; ) if (b2 = V2, a3 = b2.child, 0 !== (b2.subtreeFlags & 1028) && null !== a3) a3.return = b2, V2 = a3;
    else for (; null !== V2; ) {
      b2 = V2;
      try {
        var n2 = b2.alternate;
        if (0 !== (b2.flags & 1024)) switch (b2.tag) {
          case 0:
          case 11:
          case 15:
            break;
          case 1:
            if (null !== n2) {
              var t2 = n2.memoizedProps, J2 = n2.memoizedState, x = b2.stateNode, w2 = x.getSnapshotBeforeUpdate(b2.elementType === b2.type ? t2 : Ci(b2.type, t2), J2);
              x.__reactInternalSnapshotBeforeUpdate = w2;
            }
            break;
          case 3:
            var u2 = b2.stateNode.containerInfo;
            1 === u2.nodeType ? u2.textContent = "" : 9 === u2.nodeType && u2.documentElement && u2.removeChild(u2.documentElement);
            break;
          case 5:
          case 6:
          case 4:
          case 17:
            break;
          default:
            throw Error(p2(163));
        }
      } catch (F2) {
        W2(b2, b2.return, F2);
      }
      a3 = b2.sibling;
      if (null !== a3) {
        a3.return = b2.return;
        V2 = a3;
        break;
      }
      V2 = b2.return;
    }
    n2 = Nj;
    Nj = false;
    return n2;
  }
  function Pj(a3, b2, c2) {
    var d2 = b2.updateQueue;
    d2 = null !== d2 ? d2.lastEffect : null;
    if (null !== d2) {
      var e2 = d2 = d2.next;
      do {
        if ((e2.tag & a3) === a3) {
          var f2 = e2.destroy;
          e2.destroy = void 0;
          void 0 !== f2 && Mj(b2, c2, f2);
        }
        e2 = e2.next;
      } while (e2 !== d2);
    }
  }
  function Qj(a3, b2) {
    b2 = b2.updateQueue;
    b2 = null !== b2 ? b2.lastEffect : null;
    if (null !== b2) {
      var c2 = b2 = b2.next;
      do {
        if ((c2.tag & a3) === a3) {
          var d2 = c2.create;
          c2.destroy = d2();
        }
        c2 = c2.next;
      } while (c2 !== b2);
    }
  }
  function Rj(a3) {
    var b2 = a3.ref;
    if (null !== b2) {
      var c2 = a3.stateNode;
      switch (a3.tag) {
        case 5:
          a3 = c2;
          break;
        default:
          a3 = c2;
      }
      "function" === typeof b2 ? b2(a3) : b2.current = a3;
    }
  }
  function Sj(a3) {
    var b2 = a3.alternate;
    null !== b2 && (a3.alternate = null, Sj(b2));
    a3.child = null;
    a3.deletions = null;
    a3.sibling = null;
    5 === a3.tag && (b2 = a3.stateNode, null !== b2 && (delete b2[Of], delete b2[Pf], delete b2[of], delete b2[Qf], delete b2[Rf]));
    a3.stateNode = null;
    a3.return = null;
    a3.dependencies = null;
    a3.memoizedProps = null;
    a3.memoizedState = null;
    a3.pendingProps = null;
    a3.stateNode = null;
    a3.updateQueue = null;
  }
  function Tj(a3) {
    return 5 === a3.tag || 3 === a3.tag || 4 === a3.tag;
  }
  function Uj(a3) {
    a: for (; ; ) {
      for (; null === a3.sibling; ) {
        if (null === a3.return || Tj(a3.return)) return null;
        a3 = a3.return;
      }
      a3.sibling.return = a3.return;
      for (a3 = a3.sibling; 5 !== a3.tag && 6 !== a3.tag && 18 !== a3.tag; ) {
        if (a3.flags & 2) continue a;
        if (null === a3.child || 4 === a3.tag) continue a;
        else a3.child.return = a3, a3 = a3.child;
      }
      if (!(a3.flags & 2)) return a3.stateNode;
    }
  }
  function Vj(a3, b2, c2) {
    var d2 = a3.tag;
    if (5 === d2 || 6 === d2) a3 = a3.stateNode, b2 ? 8 === c2.nodeType ? c2.parentNode.insertBefore(a3, b2) : c2.insertBefore(a3, b2) : (8 === c2.nodeType ? (b2 = c2.parentNode, b2.insertBefore(a3, c2)) : (b2 = c2, b2.appendChild(a3)), c2 = c2._reactRootContainer, null !== c2 && void 0 !== c2 || null !== b2.onclick || (b2.onclick = Bf));
    else if (4 !== d2 && (a3 = a3.child, null !== a3)) for (Vj(a3, b2, c2), a3 = a3.sibling; null !== a3; ) Vj(a3, b2, c2), a3 = a3.sibling;
  }
  function Wj(a3, b2, c2) {
    var d2 = a3.tag;
    if (5 === d2 || 6 === d2) a3 = a3.stateNode, b2 ? c2.insertBefore(a3, b2) : c2.appendChild(a3);
    else if (4 !== d2 && (a3 = a3.child, null !== a3)) for (Wj(a3, b2, c2), a3 = a3.sibling; null !== a3; ) Wj(a3, b2, c2), a3 = a3.sibling;
  }
  var X2 = null, Xj = false;
  function Yj(a3, b2, c2) {
    for (c2 = c2.child; null !== c2; ) Zj(a3, b2, c2), c2 = c2.sibling;
  }
  function Zj(a3, b2, c2) {
    if (lc && "function" === typeof lc.onCommitFiberUnmount) try {
      lc.onCommitFiberUnmount(kc, c2);
    } catch (h2) {
    }
    switch (c2.tag) {
      case 5:
        U2 || Lj(c2, b2);
      case 6:
        var d2 = X2, e2 = Xj;
        X2 = null;
        Yj(a3, b2, c2);
        X2 = d2;
        Xj = e2;
        null !== X2 && (Xj ? (a3 = X2, c2 = c2.stateNode, 8 === a3.nodeType ? a3.parentNode.removeChild(c2) : a3.removeChild(c2)) : X2.removeChild(c2.stateNode));
        break;
      case 18:
        null !== X2 && (Xj ? (a3 = X2, c2 = c2.stateNode, 8 === a3.nodeType ? Kf(a3.parentNode, c2) : 1 === a3.nodeType && Kf(a3, c2), bd(a3)) : Kf(X2, c2.stateNode));
        break;
      case 4:
        d2 = X2;
        e2 = Xj;
        X2 = c2.stateNode.containerInfo;
        Xj = true;
        Yj(a3, b2, c2);
        X2 = d2;
        Xj = e2;
        break;
      case 0:
      case 11:
      case 14:
      case 15:
        if (!U2 && (d2 = c2.updateQueue, null !== d2 && (d2 = d2.lastEffect, null !== d2))) {
          e2 = d2 = d2.next;
          do {
            var f2 = e2, g2 = f2.destroy;
            f2 = f2.tag;
            void 0 !== g2 && (0 !== (f2 & 2) ? Mj(c2, b2, g2) : 0 !== (f2 & 4) && Mj(c2, b2, g2));
            e2 = e2.next;
          } while (e2 !== d2);
        }
        Yj(a3, b2, c2);
        break;
      case 1:
        if (!U2 && (Lj(c2, b2), d2 = c2.stateNode, "function" === typeof d2.componentWillUnmount)) try {
          d2.props = c2.memoizedProps, d2.state = c2.memoizedState, d2.componentWillUnmount();
        } catch (h2) {
          W2(c2, b2, h2);
        }
        Yj(a3, b2, c2);
        break;
      case 21:
        Yj(a3, b2, c2);
        break;
      case 22:
        c2.mode & 1 ? (U2 = (d2 = U2) || null !== c2.memoizedState, Yj(a3, b2, c2), U2 = d2) : Yj(a3, b2, c2);
        break;
      default:
        Yj(a3, b2, c2);
    }
  }
  function ak(a3) {
    var b2 = a3.updateQueue;
    if (null !== b2) {
      a3.updateQueue = null;
      var c2 = a3.stateNode;
      null === c2 && (c2 = a3.stateNode = new Kj());
      b2.forEach(function(b3) {
        var d2 = bk.bind(null, a3, b3);
        c2.has(b3) || (c2.add(b3), b3.then(d2, d2));
      });
    }
  }
  function ck(a3, b2) {
    var c2 = b2.deletions;
    if (null !== c2) for (var d2 = 0; d2 < c2.length; d2++) {
      var e2 = c2[d2];
      try {
        var f2 = a3, g2 = b2, h2 = g2;
        a: for (; null !== h2; ) {
          switch (h2.tag) {
            case 5:
              X2 = h2.stateNode;
              Xj = false;
              break a;
            case 3:
              X2 = h2.stateNode.containerInfo;
              Xj = true;
              break a;
            case 4:
              X2 = h2.stateNode.containerInfo;
              Xj = true;
              break a;
          }
          h2 = h2.return;
        }
        if (null === X2) throw Error(p2(160));
        Zj(f2, g2, e2);
        X2 = null;
        Xj = false;
        var k2 = e2.alternate;
        null !== k2 && (k2.return = null);
        e2.return = null;
      } catch (l2) {
        W2(e2, b2, l2);
      }
    }
    if (b2.subtreeFlags & 12854) for (b2 = b2.child; null !== b2; ) dk(b2, a3), b2 = b2.sibling;
  }
  function dk(a3, b2) {
    var c2 = a3.alternate, d2 = a3.flags;
    switch (a3.tag) {
      case 0:
      case 11:
      case 14:
      case 15:
        ck(b2, a3);
        ek(a3);
        if (d2 & 4) {
          try {
            Pj(3, a3, a3.return), Qj(3, a3);
          } catch (t2) {
            W2(a3, a3.return, t2);
          }
          try {
            Pj(5, a3, a3.return);
          } catch (t2) {
            W2(a3, a3.return, t2);
          }
        }
        break;
      case 1:
        ck(b2, a3);
        ek(a3);
        d2 & 512 && null !== c2 && Lj(c2, c2.return);
        break;
      case 5:
        ck(b2, a3);
        ek(a3);
        d2 & 512 && null !== c2 && Lj(c2, c2.return);
        if (a3.flags & 32) {
          var e2 = a3.stateNode;
          try {
            ob(e2, "");
          } catch (t2) {
            W2(a3, a3.return, t2);
          }
        }
        if (d2 & 4 && (e2 = a3.stateNode, null != e2)) {
          var f2 = a3.memoizedProps, g2 = null !== c2 ? c2.memoizedProps : f2, h2 = a3.type, k2 = a3.updateQueue;
          a3.updateQueue = null;
          if (null !== k2) try {
            "input" === h2 && "radio" === f2.type && null != f2.name && ab(e2, f2);
            vb(h2, g2);
            var l2 = vb(h2, f2);
            for (g2 = 0; g2 < k2.length; g2 += 2) {
              var m2 = k2[g2], q3 = k2[g2 + 1];
              "style" === m2 ? sb(e2, q3) : "dangerouslySetInnerHTML" === m2 ? nb(e2, q3) : "children" === m2 ? ob(e2, q3) : ta(e2, m2, q3, l2);
            }
            switch (h2) {
              case "input":
                bb(e2, f2);
                break;
              case "textarea":
                ib(e2, f2);
                break;
              case "select":
                var r2 = e2._wrapperState.wasMultiple;
                e2._wrapperState.wasMultiple = !!f2.multiple;
                var y2 = f2.value;
                null != y2 ? fb(e2, !!f2.multiple, y2, false) : r2 !== !!f2.multiple && (null != f2.defaultValue ? fb(
                  e2,
                  !!f2.multiple,
                  f2.defaultValue,
                  true
                ) : fb(e2, !!f2.multiple, f2.multiple ? [] : "", false));
            }
            e2[Pf] = f2;
          } catch (t2) {
            W2(a3, a3.return, t2);
          }
        }
        break;
      case 6:
        ck(b2, a3);
        ek(a3);
        if (d2 & 4) {
          if (null === a3.stateNode) throw Error(p2(162));
          e2 = a3.stateNode;
          f2 = a3.memoizedProps;
          try {
            e2.nodeValue = f2;
          } catch (t2) {
            W2(a3, a3.return, t2);
          }
        }
        break;
      case 3:
        ck(b2, a3);
        ek(a3);
        if (d2 & 4 && null !== c2 && c2.memoizedState.isDehydrated) try {
          bd(b2.containerInfo);
        } catch (t2) {
          W2(a3, a3.return, t2);
        }
        break;
      case 4:
        ck(b2, a3);
        ek(a3);
        break;
      case 13:
        ck(b2, a3);
        ek(a3);
        e2 = a3.child;
        e2.flags & 8192 && (f2 = null !== e2.memoizedState, e2.stateNode.isHidden = f2, !f2 || null !== e2.alternate && null !== e2.alternate.memoizedState || (fk = B()));
        d2 & 4 && ak(a3);
        break;
      case 22:
        m2 = null !== c2 && null !== c2.memoizedState;
        a3.mode & 1 ? (U2 = (l2 = U2) || m2, ck(b2, a3), U2 = l2) : ck(b2, a3);
        ek(a3);
        if (d2 & 8192) {
          l2 = null !== a3.memoizedState;
          if ((a3.stateNode.isHidden = l2) && !m2 && 0 !== (a3.mode & 1)) for (V2 = a3, m2 = a3.child; null !== m2; ) {
            for (q3 = V2 = m2; null !== V2; ) {
              r2 = V2;
              y2 = r2.child;
              switch (r2.tag) {
                case 0:
                case 11:
                case 14:
                case 15:
                  Pj(4, r2, r2.return);
                  break;
                case 1:
                  Lj(r2, r2.return);
                  var n2 = r2.stateNode;
                  if ("function" === typeof n2.componentWillUnmount) {
                    d2 = r2;
                    c2 = r2.return;
                    try {
                      b2 = d2, n2.props = b2.memoizedProps, n2.state = b2.memoizedState, n2.componentWillUnmount();
                    } catch (t2) {
                      W2(d2, c2, t2);
                    }
                  }
                  break;
                case 5:
                  Lj(r2, r2.return);
                  break;
                case 22:
                  if (null !== r2.memoizedState) {
                    gk(q3);
                    continue;
                  }
              }
              null !== y2 ? (y2.return = r2, V2 = y2) : gk(q3);
            }
            m2 = m2.sibling;
          }
          a: for (m2 = null, q3 = a3; ; ) {
            if (5 === q3.tag) {
              if (null === m2) {
                m2 = q3;
                try {
                  e2 = q3.stateNode, l2 ? (f2 = e2.style, "function" === typeof f2.setProperty ? f2.setProperty("display", "none", "important") : f2.display = "none") : (h2 = q3.stateNode, k2 = q3.memoizedProps.style, g2 = void 0 !== k2 && null !== k2 && k2.hasOwnProperty("display") ? k2.display : null, h2.style.display = rb("display", g2));
                } catch (t2) {
                  W2(a3, a3.return, t2);
                }
              }
            } else if (6 === q3.tag) {
              if (null === m2) try {
                q3.stateNode.nodeValue = l2 ? "" : q3.memoizedProps;
              } catch (t2) {
                W2(a3, a3.return, t2);
              }
            } else if ((22 !== q3.tag && 23 !== q3.tag || null === q3.memoizedState || q3 === a3) && null !== q3.child) {
              q3.child.return = q3;
              q3 = q3.child;
              continue;
            }
            if (q3 === a3) break a;
            for (; null === q3.sibling; ) {
              if (null === q3.return || q3.return === a3) break a;
              m2 === q3 && (m2 = null);
              q3 = q3.return;
            }
            m2 === q3 && (m2 = null);
            q3.sibling.return = q3.return;
            q3 = q3.sibling;
          }
        }
        break;
      case 19:
        ck(b2, a3);
        ek(a3);
        d2 & 4 && ak(a3);
        break;
      case 21:
        break;
      default:
        ck(
          b2,
          a3
        ), ek(a3);
    }
  }
  function ek(a3) {
    var b2 = a3.flags;
    if (b2 & 2) {
      try {
        a: {
          for (var c2 = a3.return; null !== c2; ) {
            if (Tj(c2)) {
              var d2 = c2;
              break a;
            }
            c2 = c2.return;
          }
          throw Error(p2(160));
        }
        switch (d2.tag) {
          case 5:
            var e2 = d2.stateNode;
            d2.flags & 32 && (ob(e2, ""), d2.flags &= -33);
            var f2 = Uj(a3);
            Wj(a3, f2, e2);
            break;
          case 3:
          case 4:
            var g2 = d2.stateNode.containerInfo, h2 = Uj(a3);
            Vj(a3, h2, g2);
            break;
          default:
            throw Error(p2(161));
        }
      } catch (k2) {
        W2(a3, a3.return, k2);
      }
      a3.flags &= -3;
    }
    b2 & 4096 && (a3.flags &= -4097);
  }
  function hk(a3, b2, c2) {
    V2 = a3;
    ik(a3);
  }
  function ik(a3, b2, c2) {
    for (var d2 = 0 !== (a3.mode & 1); null !== V2; ) {
      var e2 = V2, f2 = e2.child;
      if (22 === e2.tag && d2) {
        var g2 = null !== e2.memoizedState || Jj;
        if (!g2) {
          var h2 = e2.alternate, k2 = null !== h2 && null !== h2.memoizedState || U2;
          h2 = Jj;
          var l2 = U2;
          Jj = g2;
          if ((U2 = k2) && !l2) for (V2 = e2; null !== V2; ) g2 = V2, k2 = g2.child, 22 === g2.tag && null !== g2.memoizedState ? jk(e2) : null !== k2 ? (k2.return = g2, V2 = k2) : jk(e2);
          for (; null !== f2; ) V2 = f2, ik(f2), f2 = f2.sibling;
          V2 = e2;
          Jj = h2;
          U2 = l2;
        }
        kk(a3);
      } else 0 !== (e2.subtreeFlags & 8772) && null !== f2 ? (f2.return = e2, V2 = f2) : kk(a3);
    }
  }
  function kk(a3) {
    for (; null !== V2; ) {
      var b2 = V2;
      if (0 !== (b2.flags & 8772)) {
        var c2 = b2.alternate;
        try {
          if (0 !== (b2.flags & 8772)) switch (b2.tag) {
            case 0:
            case 11:
            case 15:
              U2 || Qj(5, b2);
              break;
            case 1:
              var d2 = b2.stateNode;
              if (b2.flags & 4 && !U2) if (null === c2) d2.componentDidMount();
              else {
                var e2 = b2.elementType === b2.type ? c2.memoizedProps : Ci(b2.type, c2.memoizedProps);
                d2.componentDidUpdate(e2, c2.memoizedState, d2.__reactInternalSnapshotBeforeUpdate);
              }
              var f2 = b2.updateQueue;
              null !== f2 && sh(b2, f2, d2);
              break;
            case 3:
              var g2 = b2.updateQueue;
              if (null !== g2) {
                c2 = null;
                if (null !== b2.child) switch (b2.child.tag) {
                  case 5:
                    c2 = b2.child.stateNode;
                    break;
                  case 1:
                    c2 = b2.child.stateNode;
                }
                sh(b2, g2, c2);
              }
              break;
            case 5:
              var h2 = b2.stateNode;
              if (null === c2 && b2.flags & 4) {
                c2 = h2;
                var k2 = b2.memoizedProps;
                switch (b2.type) {
                  case "button":
                  case "input":
                  case "select":
                  case "textarea":
                    k2.autoFocus && c2.focus();
                    break;
                  case "img":
                    k2.src && (c2.src = k2.src);
                }
              }
              break;
            case 6:
              break;
            case 4:
              break;
            case 12:
              break;
            case 13:
              if (null === b2.memoizedState) {
                var l2 = b2.alternate;
                if (null !== l2) {
                  var m2 = l2.memoizedState;
                  if (null !== m2) {
                    var q3 = m2.dehydrated;
                    null !== q3 && bd(q3);
                  }
                }
              }
              break;
            case 19:
            case 17:
            case 21:
            case 22:
            case 23:
            case 25:
              break;
            default:
              throw Error(p2(163));
          }
          U2 || b2.flags & 512 && Rj(b2);
        } catch (r2) {
          W2(b2, b2.return, r2);
        }
      }
      if (b2 === a3) {
        V2 = null;
        break;
      }
      c2 = b2.sibling;
      if (null !== c2) {
        c2.return = b2.return;
        V2 = c2;
        break;
      }
      V2 = b2.return;
    }
  }
  function gk(a3) {
    for (; null !== V2; ) {
      var b2 = V2;
      if (b2 === a3) {
        V2 = null;
        break;
      }
      var c2 = b2.sibling;
      if (null !== c2) {
        c2.return = b2.return;
        V2 = c2;
        break;
      }
      V2 = b2.return;
    }
  }
  function jk(a3) {
    for (; null !== V2; ) {
      var b2 = V2;
      try {
        switch (b2.tag) {
          case 0:
          case 11:
          case 15:
            var c2 = b2.return;
            try {
              Qj(4, b2);
            } catch (k2) {
              W2(b2, c2, k2);
            }
            break;
          case 1:
            var d2 = b2.stateNode;
            if ("function" === typeof d2.componentDidMount) {
              var e2 = b2.return;
              try {
                d2.componentDidMount();
              } catch (k2) {
                W2(b2, e2, k2);
              }
            }
            var f2 = b2.return;
            try {
              Rj(b2);
            } catch (k2) {
              W2(b2, f2, k2);
            }
            break;
          case 5:
            var g2 = b2.return;
            try {
              Rj(b2);
            } catch (k2) {
              W2(b2, g2, k2);
            }
        }
      } catch (k2) {
        W2(b2, b2.return, k2);
      }
      if (b2 === a3) {
        V2 = null;
        break;
      }
      var h2 = b2.sibling;
      if (null !== h2) {
        h2.return = b2.return;
        V2 = h2;
        break;
      }
      V2 = b2.return;
    }
  }
  var lk = Math.ceil, mk = ua2.ReactCurrentDispatcher, nk = ua2.ReactCurrentOwner, ok = ua2.ReactCurrentBatchConfig, K2 = 0, Q2 = null, Y2 = null, Z2 = 0, fj = 0, ej = Uf(0), T3 = 0, pk = null, rh = 0, qk = 0, rk = 0, sk = null, tk = null, fk = 0, Gj = Infinity, uk = null, Oi = false, Pi = null, Ri = null, vk = false, wk = null, xk = 0, yk = 0, zk = null, Ak = -1, Bk = 0;
  function R2() {
    return 0 !== (K2 & 6) ? B() : -1 !== Ak ? Ak : Ak = B();
  }
  function yi(a3) {
    if (0 === (a3.mode & 1)) return 1;
    if (0 !== (K2 & 2) && 0 !== Z2) return Z2 & -Z2;
    if (null !== Kg.transition) return 0 === Bk && (Bk = yc()), Bk;
    a3 = C2;
    if (0 !== a3) return a3;
    a3 = window.event;
    a3 = void 0 === a3 ? 16 : jd(a3.type);
    return a3;
  }
  function gi(a3, b2, c2, d2) {
    if (50 < yk) throw yk = 0, zk = null, Error(p2(185));
    Ac(a3, c2, d2);
    if (0 === (K2 & 2) || a3 !== Q2) a3 === Q2 && (0 === (K2 & 2) && (qk |= c2), 4 === T3 && Ck(a3, Z2)), Dk(a3, d2), 1 === c2 && 0 === K2 && 0 === (b2.mode & 1) && (Gj = B() + 500, fg && jg());
  }
  function Dk(a3, b2) {
    var c2 = a3.callbackNode;
    wc(a3, b2);
    var d2 = uc(a3, a3 === Q2 ? Z2 : 0);
    if (0 === d2) null !== c2 && bc(c2), a3.callbackNode = null, a3.callbackPriority = 0;
    else if (b2 = d2 & -d2, a3.callbackPriority !== b2) {
      null != c2 && bc(c2);
      if (1 === b2) 0 === a3.tag ? ig(Ek.bind(null, a3)) : hg(Ek.bind(null, a3)), Jf(function() {
        0 === (K2 & 6) && jg();
      }), c2 = null;
      else {
        switch (Dc(d2)) {
          case 1:
            c2 = fc;
            break;
          case 4:
            c2 = gc;
            break;
          case 16:
            c2 = hc;
            break;
          case 536870912:
            c2 = jc;
            break;
          default:
            c2 = hc;
        }
        c2 = Fk(c2, Gk.bind(null, a3));
      }
      a3.callbackPriority = b2;
      a3.callbackNode = c2;
    }
  }
  function Gk(a3, b2) {
    Ak = -1;
    Bk = 0;
    if (0 !== (K2 & 6)) throw Error(p2(327));
    var c2 = a3.callbackNode;
    if (Hk() && a3.callbackNode !== c2) return null;
    var d2 = uc(a3, a3 === Q2 ? Z2 : 0);
    if (0 === d2) return null;
    if (0 !== (d2 & 30) || 0 !== (d2 & a3.expiredLanes) || b2) b2 = Ik(a3, d2);
    else {
      b2 = d2;
      var e2 = K2;
      K2 |= 2;
      var f2 = Jk();
      if (Q2 !== a3 || Z2 !== b2) uk = null, Gj = B() + 500, Kk(a3, b2);
      do
        try {
          Lk();
          break;
        } catch (h2) {
          Mk(a3, h2);
        }
      while (1);
      $g();
      mk.current = f2;
      K2 = e2;
      null !== Y2 ? b2 = 0 : (Q2 = null, Z2 = 0, b2 = T3);
    }
    if (0 !== b2) {
      2 === b2 && (e2 = xc(a3), 0 !== e2 && (d2 = e2, b2 = Nk(a3, e2)));
      if (1 === b2) throw c2 = pk, Kk(a3, 0), Ck(a3, d2), Dk(a3, B()), c2;
      if (6 === b2) Ck(a3, d2);
      else {
        e2 = a3.current.alternate;
        if (0 === (d2 & 30) && !Ok(e2) && (b2 = Ik(a3, d2), 2 === b2 && (f2 = xc(a3), 0 !== f2 && (d2 = f2, b2 = Nk(a3, f2))), 1 === b2)) throw c2 = pk, Kk(a3, 0), Ck(a3, d2), Dk(a3, B()), c2;
        a3.finishedWork = e2;
        a3.finishedLanes = d2;
        switch (b2) {
          case 0:
          case 1:
            throw Error(p2(345));
          case 2:
            Pk(a3, tk, uk);
            break;
          case 3:
            Ck(a3, d2);
            if ((d2 & 130023424) === d2 && (b2 = fk + 500 - B(), 10 < b2)) {
              if (0 !== uc(a3, 0)) break;
              e2 = a3.suspendedLanes;
              if ((e2 & d2) !== d2) {
                R2();
                a3.pingedLanes |= a3.suspendedLanes & e2;
                break;
              }
              a3.timeoutHandle = Ff(Pk.bind(null, a3, tk, uk), b2);
              break;
            }
            Pk(a3, tk, uk);
            break;
          case 4:
            Ck(a3, d2);
            if ((d2 & 4194240) === d2) break;
            b2 = a3.eventTimes;
            for (e2 = -1; 0 < d2; ) {
              var g2 = 31 - oc(d2);
              f2 = 1 << g2;
              g2 = b2[g2];
              g2 > e2 && (e2 = g2);
              d2 &= ~f2;
            }
            d2 = e2;
            d2 = B() - d2;
            d2 = (120 > d2 ? 120 : 480 > d2 ? 480 : 1080 > d2 ? 1080 : 1920 > d2 ? 1920 : 3e3 > d2 ? 3e3 : 4320 > d2 ? 4320 : 1960 * lk(d2 / 1960)) - d2;
            if (10 < d2) {
              a3.timeoutHandle = Ff(Pk.bind(null, a3, tk, uk), d2);
              break;
            }
            Pk(a3, tk, uk);
            break;
          case 5:
            Pk(a3, tk, uk);
            break;
          default:
            throw Error(p2(329));
        }
      }
    }
    Dk(a3, B());
    return a3.callbackNode === c2 ? Gk.bind(null, a3) : null;
  }
  function Nk(a3, b2) {
    var c2 = sk;
    a3.current.memoizedState.isDehydrated && (Kk(a3, b2).flags |= 256);
    a3 = Ik(a3, b2);
    2 !== a3 && (b2 = tk, tk = c2, null !== b2 && Fj(b2));
    return a3;
  }
  function Fj(a3) {
    null === tk ? tk = a3 : tk.push.apply(tk, a3);
  }
  function Ok(a3) {
    for (var b2 = a3; ; ) {
      if (b2.flags & 16384) {
        var c2 = b2.updateQueue;
        if (null !== c2 && (c2 = c2.stores, null !== c2)) for (var d2 = 0; d2 < c2.length; d2++) {
          var e2 = c2[d2], f2 = e2.getSnapshot;
          e2 = e2.value;
          try {
            if (!He2(f2(), e2)) return false;
          } catch (g2) {
            return false;
          }
        }
      }
      c2 = b2.child;
      if (b2.subtreeFlags & 16384 && null !== c2) c2.return = b2, b2 = c2;
      else {
        if (b2 === a3) break;
        for (; null === b2.sibling; ) {
          if (null === b2.return || b2.return === a3) return true;
          b2 = b2.return;
        }
        b2.sibling.return = b2.return;
        b2 = b2.sibling;
      }
    }
    return true;
  }
  function Ck(a3, b2) {
    b2 &= ~rk;
    b2 &= ~qk;
    a3.suspendedLanes |= b2;
    a3.pingedLanes &= ~b2;
    for (a3 = a3.expirationTimes; 0 < b2; ) {
      var c2 = 31 - oc(b2), d2 = 1 << c2;
      a3[c2] = -1;
      b2 &= ~d2;
    }
  }
  function Ek(a3) {
    if (0 !== (K2 & 6)) throw Error(p2(327));
    Hk();
    var b2 = uc(a3, 0);
    if (0 === (b2 & 1)) return Dk(a3, B()), null;
    var c2 = Ik(a3, b2);
    if (0 !== a3.tag && 2 === c2) {
      var d2 = xc(a3);
      0 !== d2 && (b2 = d2, c2 = Nk(a3, d2));
    }
    if (1 === c2) throw c2 = pk, Kk(a3, 0), Ck(a3, b2), Dk(a3, B()), c2;
    if (6 === c2) throw Error(p2(345));
    a3.finishedWork = a3.current.alternate;
    a3.finishedLanes = b2;
    Pk(a3, tk, uk);
    Dk(a3, B());
    return null;
  }
  function Qk(a3, b2) {
    var c2 = K2;
    K2 |= 1;
    try {
      return a3(b2);
    } finally {
      K2 = c2, 0 === K2 && (Gj = B() + 500, fg && jg());
    }
  }
  function Rk(a3) {
    null !== wk && 0 === wk.tag && 0 === (K2 & 6) && Hk();
    var b2 = K2;
    K2 |= 1;
    var c2 = ok.transition, d2 = C2;
    try {
      if (ok.transition = null, C2 = 1, a3) return a3();
    } finally {
      C2 = d2, ok.transition = c2, K2 = b2, 0 === (K2 & 6) && jg();
    }
  }
  function Hj() {
    fj = ej.current;
    E2(ej);
  }
  function Kk(a3, b2) {
    a3.finishedWork = null;
    a3.finishedLanes = 0;
    var c2 = a3.timeoutHandle;
    -1 !== c2 && (a3.timeoutHandle = -1, Gf(c2));
    if (null !== Y2) for (c2 = Y2.return; null !== c2; ) {
      var d2 = c2;
      wg(d2);
      switch (d2.tag) {
        case 1:
          d2 = d2.type.childContextTypes;
          null !== d2 && void 0 !== d2 && $f();
          break;
        case 3:
          zh();
          E2(Wf);
          E2(H2);
          Eh();
          break;
        case 5:
          Bh(d2);
          break;
        case 4:
          zh();
          break;
        case 13:
          E2(L2);
          break;
        case 19:
          E2(L2);
          break;
        case 10:
          ah(d2.type._context);
          break;
        case 22:
        case 23:
          Hj();
      }
      c2 = c2.return;
    }
    Q2 = a3;
    Y2 = a3 = Pg(a3.current, null);
    Z2 = fj = b2;
    T3 = 0;
    pk = null;
    rk = qk = rh = 0;
    tk = sk = null;
    if (null !== fh) {
      for (b2 = 0; b2 < fh.length; b2++) if (c2 = fh[b2], d2 = c2.interleaved, null !== d2) {
        c2.interleaved = null;
        var e2 = d2.next, f2 = c2.pending;
        if (null !== f2) {
          var g2 = f2.next;
          f2.next = e2;
          d2.next = g2;
        }
        c2.pending = d2;
      }
      fh = null;
    }
    return a3;
  }
  function Mk(a3, b2) {
    do {
      var c2 = Y2;
      try {
        $g();
        Fh.current = Rh;
        if (Ih) {
          for (var d2 = M2.memoizedState; null !== d2; ) {
            var e2 = d2.queue;
            null !== e2 && (e2.pending = null);
            d2 = d2.next;
          }
          Ih = false;
        }
        Hh = 0;
        O2 = N2 = M2 = null;
        Jh = false;
        Kh = 0;
        nk.current = null;
        if (null === c2 || null === c2.return) {
          T3 = 1;
          pk = b2;
          Y2 = null;
          break;
        }
        a: {
          var f2 = a3, g2 = c2.return, h2 = c2, k2 = b2;
          b2 = Z2;
          h2.flags |= 32768;
          if (null !== k2 && "object" === typeof k2 && "function" === typeof k2.then) {
            var l2 = k2, m2 = h2, q3 = m2.tag;
            if (0 === (m2.mode & 1) && (0 === q3 || 11 === q3 || 15 === q3)) {
              var r2 = m2.alternate;
              r2 ? (m2.updateQueue = r2.updateQueue, m2.memoizedState = r2.memoizedState, m2.lanes = r2.lanes) : (m2.updateQueue = null, m2.memoizedState = null);
            }
            var y2 = Ui(g2);
            if (null !== y2) {
              y2.flags &= -257;
              Vi(y2, g2, h2, f2, b2);
              y2.mode & 1 && Si(f2, l2, b2);
              b2 = y2;
              k2 = l2;
              var n2 = b2.updateQueue;
              if (null === n2) {
                var t2 = /* @__PURE__ */ new Set();
                t2.add(k2);
                b2.updateQueue = t2;
              } else n2.add(k2);
              break a;
            } else {
              if (0 === (b2 & 1)) {
                Si(f2, l2, b2);
                tj();
                break a;
              }
              k2 = Error(p2(426));
            }
          } else if (I2 && h2.mode & 1) {
            var J2 = Ui(g2);
            if (null !== J2) {
              0 === (J2.flags & 65536) && (J2.flags |= 256);
              Vi(J2, g2, h2, f2, b2);
              Jg(Ji(k2, h2));
              break a;
            }
          }
          f2 = k2 = Ji(k2, h2);
          4 !== T3 && (T3 = 2);
          null === sk ? sk = [f2] : sk.push(f2);
          f2 = g2;
          do {
            switch (f2.tag) {
              case 3:
                f2.flags |= 65536;
                b2 &= -b2;
                f2.lanes |= b2;
                var x = Ni(f2, k2, b2);
                ph(f2, x);
                break a;
              case 1:
                h2 = k2;
                var w2 = f2.type, u2 = f2.stateNode;
                if (0 === (f2.flags & 128) && ("function" === typeof w2.getDerivedStateFromError || null !== u2 && "function" === typeof u2.componentDidCatch && (null === Ri || !Ri.has(u2)))) {
                  f2.flags |= 65536;
                  b2 &= -b2;
                  f2.lanes |= b2;
                  var F2 = Qi(f2, h2, b2);
                  ph(f2, F2);
                  break a;
                }
            }
            f2 = f2.return;
          } while (null !== f2);
        }
        Sk(c2);
      } catch (na) {
        b2 = na;
        Y2 === c2 && null !== c2 && (Y2 = c2 = c2.return);
        continue;
      }
      break;
    } while (1);
  }
  function Jk() {
    var a3 = mk.current;
    mk.current = Rh;
    return null === a3 ? Rh : a3;
  }
  function tj() {
    if (0 === T3 || 3 === T3 || 2 === T3) T3 = 4;
    null === Q2 || 0 === (rh & 268435455) && 0 === (qk & 268435455) || Ck(Q2, Z2);
  }
  function Ik(a3, b2) {
    var c2 = K2;
    K2 |= 2;
    var d2 = Jk();
    if (Q2 !== a3 || Z2 !== b2) uk = null, Kk(a3, b2);
    do
      try {
        Tk();
        break;
      } catch (e2) {
        Mk(a3, e2);
      }
    while (1);
    $g();
    K2 = c2;
    mk.current = d2;
    if (null !== Y2) throw Error(p2(261));
    Q2 = null;
    Z2 = 0;
    return T3;
  }
  function Tk() {
    for (; null !== Y2; ) Uk(Y2);
  }
  function Lk() {
    for (; null !== Y2 && !cc(); ) Uk(Y2);
  }
  function Uk(a3) {
    var b2 = Vk(a3.alternate, a3, fj);
    a3.memoizedProps = a3.pendingProps;
    null === b2 ? Sk(a3) : Y2 = b2;
    nk.current = null;
  }
  function Sk(a3) {
    var b2 = a3;
    do {
      var c2 = b2.alternate;
      a3 = b2.return;
      if (0 === (b2.flags & 32768)) {
        if (c2 = Ej(c2, b2, fj), null !== c2) {
          Y2 = c2;
          return;
        }
      } else {
        c2 = Ij(c2, b2);
        if (null !== c2) {
          c2.flags &= 32767;
          Y2 = c2;
          return;
        }
        if (null !== a3) a3.flags |= 32768, a3.subtreeFlags = 0, a3.deletions = null;
        else {
          T3 = 6;
          Y2 = null;
          return;
        }
      }
      b2 = b2.sibling;
      if (null !== b2) {
        Y2 = b2;
        return;
      }
      Y2 = b2 = a3;
    } while (null !== b2);
    0 === T3 && (T3 = 5);
  }
  function Pk(a3, b2, c2) {
    var d2 = C2, e2 = ok.transition;
    try {
      ok.transition = null, C2 = 1, Wk(a3, b2, c2, d2);
    } finally {
      ok.transition = e2, C2 = d2;
    }
    return null;
  }
  function Wk(a3, b2, c2, d2) {
    do
      Hk();
    while (null !== wk);
    if (0 !== (K2 & 6)) throw Error(p2(327));
    c2 = a3.finishedWork;
    var e2 = a3.finishedLanes;
    if (null === c2) return null;
    a3.finishedWork = null;
    a3.finishedLanes = 0;
    if (c2 === a3.current) throw Error(p2(177));
    a3.callbackNode = null;
    a3.callbackPriority = 0;
    var f2 = c2.lanes | c2.childLanes;
    Bc(a3, f2);
    a3 === Q2 && (Y2 = Q2 = null, Z2 = 0);
    0 === (c2.subtreeFlags & 2064) && 0 === (c2.flags & 2064) || vk || (vk = true, Fk(hc, function() {
      Hk();
      return null;
    }));
    f2 = 0 !== (c2.flags & 15990);
    if (0 !== (c2.subtreeFlags & 15990) || f2) {
      f2 = ok.transition;
      ok.transition = null;
      var g2 = C2;
      C2 = 1;
      var h2 = K2;
      K2 |= 4;
      nk.current = null;
      Oj(a3, c2);
      dk(c2, a3);
      Oe2(Df);
      dd = !!Cf;
      Df = Cf = null;
      a3.current = c2;
      hk(c2);
      dc();
      K2 = h2;
      C2 = g2;
      ok.transition = f2;
    } else a3.current = c2;
    vk && (vk = false, wk = a3, xk = e2);
    f2 = a3.pendingLanes;
    0 === f2 && (Ri = null);
    mc(c2.stateNode);
    Dk(a3, B());
    if (null !== b2) for (d2 = a3.onRecoverableError, c2 = 0; c2 < b2.length; c2++) e2 = b2[c2], d2(e2.value, { componentStack: e2.stack, digest: e2.digest });
    if (Oi) throw Oi = false, a3 = Pi, Pi = null, a3;
    0 !== (xk & 1) && 0 !== a3.tag && Hk();
    f2 = a3.pendingLanes;
    0 !== (f2 & 1) ? a3 === zk ? yk++ : (yk = 0, zk = a3) : yk = 0;
    jg();
    return null;
  }
  function Hk() {
    if (null !== wk) {
      var a3 = Dc(xk), b2 = ok.transition, c2 = C2;
      try {
        ok.transition = null;
        C2 = 16 > a3 ? 16 : a3;
        if (null === wk) var d2 = false;
        else {
          a3 = wk;
          wk = null;
          xk = 0;
          if (0 !== (K2 & 6)) throw Error(p2(331));
          var e2 = K2;
          K2 |= 4;
          for (V2 = a3.current; null !== V2; ) {
            var f2 = V2, g2 = f2.child;
            if (0 !== (V2.flags & 16)) {
              var h2 = f2.deletions;
              if (null !== h2) {
                for (var k2 = 0; k2 < h2.length; k2++) {
                  var l2 = h2[k2];
                  for (V2 = l2; null !== V2; ) {
                    var m2 = V2;
                    switch (m2.tag) {
                      case 0:
                      case 11:
                      case 15:
                        Pj(8, m2, f2);
                    }
                    var q3 = m2.child;
                    if (null !== q3) q3.return = m2, V2 = q3;
                    else for (; null !== V2; ) {
                      m2 = V2;
                      var r2 = m2.sibling, y2 = m2.return;
                      Sj(m2);
                      if (m2 === l2) {
                        V2 = null;
                        break;
                      }
                      if (null !== r2) {
                        r2.return = y2;
                        V2 = r2;
                        break;
                      }
                      V2 = y2;
                    }
                  }
                }
                var n2 = f2.alternate;
                if (null !== n2) {
                  var t2 = n2.child;
                  if (null !== t2) {
                    n2.child = null;
                    do {
                      var J2 = t2.sibling;
                      t2.sibling = null;
                      t2 = J2;
                    } while (null !== t2);
                  }
                }
                V2 = f2;
              }
            }
            if (0 !== (f2.subtreeFlags & 2064) && null !== g2) g2.return = f2, V2 = g2;
            else b: for (; null !== V2; ) {
              f2 = V2;
              if (0 !== (f2.flags & 2048)) switch (f2.tag) {
                case 0:
                case 11:
                case 15:
                  Pj(9, f2, f2.return);
              }
              var x = f2.sibling;
              if (null !== x) {
                x.return = f2.return;
                V2 = x;
                break b;
              }
              V2 = f2.return;
            }
          }
          var w2 = a3.current;
          for (V2 = w2; null !== V2; ) {
            g2 = V2;
            var u2 = g2.child;
            if (0 !== (g2.subtreeFlags & 2064) && null !== u2) u2.return = g2, V2 = u2;
            else b: for (g2 = w2; null !== V2; ) {
              h2 = V2;
              if (0 !== (h2.flags & 2048)) try {
                switch (h2.tag) {
                  case 0:
                  case 11:
                  case 15:
                    Qj(9, h2);
                }
              } catch (na) {
                W2(h2, h2.return, na);
              }
              if (h2 === g2) {
                V2 = null;
                break b;
              }
              var F2 = h2.sibling;
              if (null !== F2) {
                F2.return = h2.return;
                V2 = F2;
                break b;
              }
              V2 = h2.return;
            }
          }
          K2 = e2;
          jg();
          if (lc && "function" === typeof lc.onPostCommitFiberRoot) try {
            lc.onPostCommitFiberRoot(kc, a3);
          } catch (na) {
          }
          d2 = true;
        }
        return d2;
      } finally {
        C2 = c2, ok.transition = b2;
      }
    }
    return false;
  }
  function Xk(a3, b2, c2) {
    b2 = Ji(c2, b2);
    b2 = Ni(a3, b2, 1);
    a3 = nh(a3, b2, 1);
    b2 = R2();
    null !== a3 && (Ac(a3, 1, b2), Dk(a3, b2));
  }
  function W2(a3, b2, c2) {
    if (3 === a3.tag) Xk(a3, a3, c2);
    else for (; null !== b2; ) {
      if (3 === b2.tag) {
        Xk(b2, a3, c2);
        break;
      } else if (1 === b2.tag) {
        var d2 = b2.stateNode;
        if ("function" === typeof b2.type.getDerivedStateFromError || "function" === typeof d2.componentDidCatch && (null === Ri || !Ri.has(d2))) {
          a3 = Ji(c2, a3);
          a3 = Qi(b2, a3, 1);
          b2 = nh(b2, a3, 1);
          a3 = R2();
          null !== b2 && (Ac(b2, 1, a3), Dk(b2, a3));
          break;
        }
      }
      b2 = b2.return;
    }
  }
  function Ti(a3, b2, c2) {
    var d2 = a3.pingCache;
    null !== d2 && d2.delete(b2);
    b2 = R2();
    a3.pingedLanes |= a3.suspendedLanes & c2;
    Q2 === a3 && (Z2 & c2) === c2 && (4 === T3 || 3 === T3 && (Z2 & 130023424) === Z2 && 500 > B() - fk ? Kk(a3, 0) : rk |= c2);
    Dk(a3, b2);
  }
  function Yk(a3, b2) {
    0 === b2 && (0 === (a3.mode & 1) ? b2 = 1 : (b2 = sc, sc <<= 1, 0 === (sc & 130023424) && (sc = 4194304)));
    var c2 = R2();
    a3 = ih(a3, b2);
    null !== a3 && (Ac(a3, b2, c2), Dk(a3, c2));
  }
  function uj(a3) {
    var b2 = a3.memoizedState, c2 = 0;
    null !== b2 && (c2 = b2.retryLane);
    Yk(a3, c2);
  }
  function bk(a3, b2) {
    var c2 = 0;
    switch (a3.tag) {
      case 13:
        var d2 = a3.stateNode;
        var e2 = a3.memoizedState;
        null !== e2 && (c2 = e2.retryLane);
        break;
      case 19:
        d2 = a3.stateNode;
        break;
      default:
        throw Error(p2(314));
    }
    null !== d2 && d2.delete(b2);
    Yk(a3, c2);
  }
  var Vk;
  Vk = function(a3, b2, c2) {
    if (null !== a3) if (a3.memoizedProps !== b2.pendingProps || Wf.current) dh = true;
    else {
      if (0 === (a3.lanes & c2) && 0 === (b2.flags & 128)) return dh = false, yj(a3, b2, c2);
      dh = 0 !== (a3.flags & 131072) ? true : false;
    }
    else dh = false, I2 && 0 !== (b2.flags & 1048576) && ug(b2, ng, b2.index);
    b2.lanes = 0;
    switch (b2.tag) {
      case 2:
        var d2 = b2.type;
        ij(a3, b2);
        a3 = b2.pendingProps;
        var e2 = Yf(b2, H2.current);
        ch(b2, c2);
        e2 = Nh(null, b2, d2, a3, e2, c2);
        var f2 = Sh();
        b2.flags |= 1;
        "object" === typeof e2 && null !== e2 && "function" === typeof e2.render && void 0 === e2.$$typeof ? (b2.tag = 1, b2.memoizedState = null, b2.updateQueue = null, Zf(d2) ? (f2 = true, cg(b2)) : f2 = false, b2.memoizedState = null !== e2.state && void 0 !== e2.state ? e2.state : null, kh(b2), e2.updater = Ei, b2.stateNode = e2, e2._reactInternals = b2, Ii(b2, d2, a3, c2), b2 = jj(null, b2, d2, true, f2, c2)) : (b2.tag = 0, I2 && f2 && vg(b2), Xi(null, b2, e2, c2), b2 = b2.child);
        return b2;
      case 16:
        d2 = b2.elementType;
        a: {
          ij(a3, b2);
          a3 = b2.pendingProps;
          e2 = d2._init;
          d2 = e2(d2._payload);
          b2.type = d2;
          e2 = b2.tag = Zk(d2);
          a3 = Ci(d2, a3);
          switch (e2) {
            case 0:
              b2 = cj(null, b2, d2, a3, c2);
              break a;
            case 1:
              b2 = hj(null, b2, d2, a3, c2);
              break a;
            case 11:
              b2 = Yi(null, b2, d2, a3, c2);
              break a;
            case 14:
              b2 = $i(null, b2, d2, Ci(d2.type, a3), c2);
              break a;
          }
          throw Error(p2(
            306,
            d2,
            ""
          ));
        }
        return b2;
      case 0:
        return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : Ci(d2, e2), cj(a3, b2, d2, e2, c2);
      case 1:
        return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : Ci(d2, e2), hj(a3, b2, d2, e2, c2);
      case 3:
        a: {
          kj(b2);
          if (null === a3) throw Error(p2(387));
          d2 = b2.pendingProps;
          f2 = b2.memoizedState;
          e2 = f2.element;
          lh(a3, b2);
          qh(b2, d2, null, c2);
          var g2 = b2.memoizedState;
          d2 = g2.element;
          if (f2.isDehydrated) if (f2 = { element: d2, isDehydrated: false, cache: g2.cache, pendingSuspenseBoundaries: g2.pendingSuspenseBoundaries, transitions: g2.transitions }, b2.updateQueue.baseState = f2, b2.memoizedState = f2, b2.flags & 256) {
            e2 = Ji(Error(p2(423)), b2);
            b2 = lj(a3, b2, d2, c2, e2);
            break a;
          } else if (d2 !== e2) {
            e2 = Ji(Error(p2(424)), b2);
            b2 = lj(a3, b2, d2, c2, e2);
            break a;
          } else for (yg = Lf(b2.stateNode.containerInfo.firstChild), xg = b2, I2 = true, zg = null, c2 = Vg(b2, null, d2, c2), b2.child = c2; c2; ) c2.flags = c2.flags & -3 | 4096, c2 = c2.sibling;
          else {
            Ig();
            if (d2 === e2) {
              b2 = Zi(a3, b2, c2);
              break a;
            }
            Xi(a3, b2, d2, c2);
          }
          b2 = b2.child;
        }
        return b2;
      case 5:
        return Ah(b2), null === a3 && Eg(b2), d2 = b2.type, e2 = b2.pendingProps, f2 = null !== a3 ? a3.memoizedProps : null, g2 = e2.children, Ef(d2, e2) ? g2 = null : null !== f2 && Ef(d2, f2) && (b2.flags |= 32), gj(a3, b2), Xi(a3, b2, g2, c2), b2.child;
      case 6:
        return null === a3 && Eg(b2), null;
      case 13:
        return oj(a3, b2, c2);
      case 4:
        return yh(b2, b2.stateNode.containerInfo), d2 = b2.pendingProps, null === a3 ? b2.child = Ug(b2, null, d2, c2) : Xi(a3, b2, d2, c2), b2.child;
      case 11:
        return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : Ci(d2, e2), Yi(a3, b2, d2, e2, c2);
      case 7:
        return Xi(a3, b2, b2.pendingProps, c2), b2.child;
      case 8:
        return Xi(a3, b2, b2.pendingProps.children, c2), b2.child;
      case 12:
        return Xi(a3, b2, b2.pendingProps.children, c2), b2.child;
      case 10:
        a: {
          d2 = b2.type._context;
          e2 = b2.pendingProps;
          f2 = b2.memoizedProps;
          g2 = e2.value;
          G2(Wg, d2._currentValue);
          d2._currentValue = g2;
          if (null !== f2) if (He2(f2.value, g2)) {
            if (f2.children === e2.children && !Wf.current) {
              b2 = Zi(a3, b2, c2);
              break a;
            }
          } else for (f2 = b2.child, null !== f2 && (f2.return = b2); null !== f2; ) {
            var h2 = f2.dependencies;
            if (null !== h2) {
              g2 = f2.child;
              for (var k2 = h2.firstContext; null !== k2; ) {
                if (k2.context === d2) {
                  if (1 === f2.tag) {
                    k2 = mh(-1, c2 & -c2);
                    k2.tag = 2;
                    var l2 = f2.updateQueue;
                    if (null !== l2) {
                      l2 = l2.shared;
                      var m2 = l2.pending;
                      null === m2 ? k2.next = k2 : (k2.next = m2.next, m2.next = k2);
                      l2.pending = k2;
                    }
                  }
                  f2.lanes |= c2;
                  k2 = f2.alternate;
                  null !== k2 && (k2.lanes |= c2);
                  bh(
                    f2.return,
                    c2,
                    b2
                  );
                  h2.lanes |= c2;
                  break;
                }
                k2 = k2.next;
              }
            } else if (10 === f2.tag) g2 = f2.type === b2.type ? null : f2.child;
            else if (18 === f2.tag) {
              g2 = f2.return;
              if (null === g2) throw Error(p2(341));
              g2.lanes |= c2;
              h2 = g2.alternate;
              null !== h2 && (h2.lanes |= c2);
              bh(g2, c2, b2);
              g2 = f2.sibling;
            } else g2 = f2.child;
            if (null !== g2) g2.return = f2;
            else for (g2 = f2; null !== g2; ) {
              if (g2 === b2) {
                g2 = null;
                break;
              }
              f2 = g2.sibling;
              if (null !== f2) {
                f2.return = g2.return;
                g2 = f2;
                break;
              }
              g2 = g2.return;
            }
            f2 = g2;
          }
          Xi(a3, b2, e2.children, c2);
          b2 = b2.child;
        }
        return b2;
      case 9:
        return e2 = b2.type, d2 = b2.pendingProps.children, ch(b2, c2), e2 = eh(e2), d2 = d2(e2), b2.flags |= 1, Xi(a3, b2, d2, c2), b2.child;
      case 14:
        return d2 = b2.type, e2 = Ci(d2, b2.pendingProps), e2 = Ci(d2.type, e2), $i(a3, b2, d2, e2, c2);
      case 15:
        return bj(a3, b2, b2.type, b2.pendingProps, c2);
      case 17:
        return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : Ci(d2, e2), ij(a3, b2), b2.tag = 1, Zf(d2) ? (a3 = true, cg(b2)) : a3 = false, ch(b2, c2), Gi(b2, d2, e2), Ii(b2, d2, e2, c2), jj(null, b2, d2, true, a3, c2);
      case 19:
        return xj(a3, b2, c2);
      case 22:
        return dj(a3, b2, c2);
    }
    throw Error(p2(156, b2.tag));
  };
  function Fk(a3, b2) {
    return ac(a3, b2);
  }
  function $k(a3, b2, c2, d2) {
    this.tag = a3;
    this.key = c2;
    this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
    this.index = 0;
    this.ref = null;
    this.pendingProps = b2;
    this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
    this.mode = d2;
    this.subtreeFlags = this.flags = 0;
    this.deletions = null;
    this.childLanes = this.lanes = 0;
    this.alternate = null;
  }
  function Bg(a3, b2, c2, d2) {
    return new $k(a3, b2, c2, d2);
  }
  function aj(a3) {
    a3 = a3.prototype;
    return !(!a3 || !a3.isReactComponent);
  }
  function Zk(a3) {
    if ("function" === typeof a3) return aj(a3) ? 1 : 0;
    if (void 0 !== a3 && null !== a3) {
      a3 = a3.$$typeof;
      if (a3 === Da) return 11;
      if (a3 === Ga) return 14;
    }
    return 2;
  }
  function Pg(a3, b2) {
    var c2 = a3.alternate;
    null === c2 ? (c2 = Bg(a3.tag, b2, a3.key, a3.mode), c2.elementType = a3.elementType, c2.type = a3.type, c2.stateNode = a3.stateNode, c2.alternate = a3, a3.alternate = c2) : (c2.pendingProps = b2, c2.type = a3.type, c2.flags = 0, c2.subtreeFlags = 0, c2.deletions = null);
    c2.flags = a3.flags & 14680064;
    c2.childLanes = a3.childLanes;
    c2.lanes = a3.lanes;
    c2.child = a3.child;
    c2.memoizedProps = a3.memoizedProps;
    c2.memoizedState = a3.memoizedState;
    c2.updateQueue = a3.updateQueue;
    b2 = a3.dependencies;
    c2.dependencies = null === b2 ? null : { lanes: b2.lanes, firstContext: b2.firstContext };
    c2.sibling = a3.sibling;
    c2.index = a3.index;
    c2.ref = a3.ref;
    return c2;
  }
  function Rg(a3, b2, c2, d2, e2, f2) {
    var g2 = 2;
    d2 = a3;
    if ("function" === typeof a3) aj(a3) && (g2 = 1);
    else if ("string" === typeof a3) g2 = 5;
    else a: switch (a3) {
      case ya:
        return Tg(c2.children, e2, f2, b2);
      case za:
        g2 = 8;
        e2 |= 8;
        break;
      case Aa:
        return a3 = Bg(12, c2, b2, e2 | 2), a3.elementType = Aa, a3.lanes = f2, a3;
      case Ea:
        return a3 = Bg(13, c2, b2, e2), a3.elementType = Ea, a3.lanes = f2, a3;
      case Fa:
        return a3 = Bg(19, c2, b2, e2), a3.elementType = Fa, a3.lanes = f2, a3;
      case Ia:
        return pj(c2, e2, f2, b2);
      default:
        if ("object" === typeof a3 && null !== a3) switch (a3.$$typeof) {
          case Ba:
            g2 = 10;
            break a;
          case Ca:
            g2 = 9;
            break a;
          case Da:
            g2 = 11;
            break a;
          case Ga:
            g2 = 14;
            break a;
          case Ha:
            g2 = 16;
            d2 = null;
            break a;
        }
        throw Error(p2(130, null == a3 ? a3 : typeof a3, ""));
    }
    b2 = Bg(g2, c2, b2, e2);
    b2.elementType = a3;
    b2.type = d2;
    b2.lanes = f2;
    return b2;
  }
  function Tg(a3, b2, c2, d2) {
    a3 = Bg(7, a3, d2, b2);
    a3.lanes = c2;
    return a3;
  }
  function pj(a3, b2, c2, d2) {
    a3 = Bg(22, a3, d2, b2);
    a3.elementType = Ia;
    a3.lanes = c2;
    a3.stateNode = { isHidden: false };
    return a3;
  }
  function Qg(a3, b2, c2) {
    a3 = Bg(6, a3, null, b2);
    a3.lanes = c2;
    return a3;
  }
  function Sg(a3, b2, c2) {
    b2 = Bg(4, null !== a3.children ? a3.children : [], a3.key, b2);
    b2.lanes = c2;
    b2.stateNode = { containerInfo: a3.containerInfo, pendingChildren: null, implementation: a3.implementation };
    return b2;
  }
  function al(a3, b2, c2, d2, e2) {
    this.tag = b2;
    this.containerInfo = a3;
    this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
    this.timeoutHandle = -1;
    this.callbackNode = this.pendingContext = this.context = null;
    this.callbackPriority = 0;
    this.eventTimes = zc(0);
    this.expirationTimes = zc(-1);
    this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
    this.entanglements = zc(0);
    this.identifierPrefix = d2;
    this.onRecoverableError = e2;
    this.mutableSourceEagerHydrationData = null;
  }
  function bl(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
    a3 = new al(a3, b2, c2, h2, k2);
    1 === b2 ? (b2 = 1, true === f2 && (b2 |= 8)) : b2 = 0;
    f2 = Bg(3, null, null, b2);
    a3.current = f2;
    f2.stateNode = a3;
    f2.memoizedState = { element: d2, isDehydrated: c2, cache: null, transitions: null, pendingSuspenseBoundaries: null };
    kh(f2);
    return a3;
  }
  function cl(a3, b2, c2) {
    var d2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
    return { $$typeof: wa, key: null == d2 ? null : "" + d2, children: a3, containerInfo: b2, implementation: c2 };
  }
  function dl(a3) {
    if (!a3) return Vf;
    a3 = a3._reactInternals;
    a: {
      if (Vb(a3) !== a3 || 1 !== a3.tag) throw Error(p2(170));
      var b2 = a3;
      do {
        switch (b2.tag) {
          case 3:
            b2 = b2.stateNode.context;
            break a;
          case 1:
            if (Zf(b2.type)) {
              b2 = b2.stateNode.__reactInternalMemoizedMergedChildContext;
              break a;
            }
        }
        b2 = b2.return;
      } while (null !== b2);
      throw Error(p2(171));
    }
    if (1 === a3.tag) {
      var c2 = a3.type;
      if (Zf(c2)) return bg(a3, c2, b2);
    }
    return b2;
  }
  function el(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
    a3 = bl(c2, d2, true, a3, e2, f2, g2, h2, k2);
    a3.context = dl(null);
    c2 = a3.current;
    d2 = R2();
    e2 = yi(c2);
    f2 = mh(d2, e2);
    f2.callback = void 0 !== b2 && null !== b2 ? b2 : null;
    nh(c2, f2, e2);
    a3.current.lanes = e2;
    Ac(a3, e2, d2);
    Dk(a3, d2);
    return a3;
  }
  function fl2(a3, b2, c2, d2) {
    var e2 = b2.current, f2 = R2(), g2 = yi(e2);
    c2 = dl(c2);
    null === b2.context ? b2.context = c2 : b2.pendingContext = c2;
    b2 = mh(f2, g2);
    b2.payload = { element: a3 };
    d2 = void 0 === d2 ? null : d2;
    null !== d2 && (b2.callback = d2);
    a3 = nh(e2, b2, g2);
    null !== a3 && (gi(a3, e2, g2, f2), oh(a3, e2, g2));
    return g2;
  }
  function gl(a3) {
    a3 = a3.current;
    if (!a3.child) return null;
    switch (a3.child.tag) {
      case 5:
        return a3.child.stateNode;
      default:
        return a3.child.stateNode;
    }
  }
  function hl(a3, b2) {
    a3 = a3.memoizedState;
    if (null !== a3 && null !== a3.dehydrated) {
      var c2 = a3.retryLane;
      a3.retryLane = 0 !== c2 && c2 < b2 ? c2 : b2;
    }
  }
  function il(a3, b2) {
    hl(a3, b2);
    (a3 = a3.alternate) && hl(a3, b2);
  }
  function jl() {
    return null;
  }
  var kl = "function" === typeof reportError ? reportError : function(a3) {
    console.error(a3);
  };
  function ll(a3) {
    this._internalRoot = a3;
  }
  ml.prototype.render = ll.prototype.render = function(a3) {
    var b2 = this._internalRoot;
    if (null === b2) throw Error(p2(409));
    fl2(a3, b2, null, null);
  };
  ml.prototype.unmount = ll.prototype.unmount = function() {
    var a3 = this._internalRoot;
    if (null !== a3) {
      this._internalRoot = null;
      var b2 = a3.containerInfo;
      Rk(function() {
        fl2(null, a3, null, null);
      });
      b2[uf] = null;
    }
  };
  function ml(a3) {
    this._internalRoot = a3;
  }
  ml.prototype.unstable_scheduleHydration = function(a3) {
    if (a3) {
      var b2 = Hc();
      a3 = { blockedOn: null, target: a3, priority: b2 };
      for (var c2 = 0; c2 < Qc.length && 0 !== b2 && b2 < Qc[c2].priority; c2++) ;
      Qc.splice(c2, 0, a3);
      0 === c2 && Vc(a3);
    }
  };
  function nl(a3) {
    return !(!a3 || 1 !== a3.nodeType && 9 !== a3.nodeType && 11 !== a3.nodeType);
  }
  function ol(a3) {
    return !(!a3 || 1 !== a3.nodeType && 9 !== a3.nodeType && 11 !== a3.nodeType && (8 !== a3.nodeType || " react-mount-point-unstable " !== a3.nodeValue));
  }
  function pl() {
  }
  function ql(a3, b2, c2, d2, e2) {
    if (e2) {
      if ("function" === typeof d2) {
        var f2 = d2;
        d2 = function() {
          var a4 = gl(g2);
          f2.call(a4);
        };
      }
      var g2 = el(b2, d2, a3, 0, null, false, false, "", pl);
      a3._reactRootContainer = g2;
      a3[uf] = g2.current;
      sf(8 === a3.nodeType ? a3.parentNode : a3);
      Rk();
      return g2;
    }
    for (; e2 = a3.lastChild; ) a3.removeChild(e2);
    if ("function" === typeof d2) {
      var h2 = d2;
      d2 = function() {
        var a4 = gl(k2);
        h2.call(a4);
      };
    }
    var k2 = bl(a3, 0, false, null, null, false, false, "", pl);
    a3._reactRootContainer = k2;
    a3[uf] = k2.current;
    sf(8 === a3.nodeType ? a3.parentNode : a3);
    Rk(function() {
      fl2(b2, k2, c2, d2);
    });
    return k2;
  }
  function rl(a3, b2, c2, d2, e2) {
    var f2 = c2._reactRootContainer;
    if (f2) {
      var g2 = f2;
      if ("function" === typeof e2) {
        var h2 = e2;
        e2 = function() {
          var a4 = gl(g2);
          h2.call(a4);
        };
      }
      fl2(b2, g2, a3, e2);
    } else g2 = ql(c2, b2, a3, e2, d2);
    return gl(g2);
  }
  Ec = function(a3) {
    switch (a3.tag) {
      case 3:
        var b2 = a3.stateNode;
        if (b2.current.memoizedState.isDehydrated) {
          var c2 = tc(b2.pendingLanes);
          0 !== c2 && (Cc(b2, c2 | 1), Dk(b2, B()), 0 === (K2 & 6) && (Gj = B() + 500, jg()));
        }
        break;
      case 13:
        Rk(function() {
          var b3 = ih(a3, 1);
          if (null !== b3) {
            var c3 = R2();
            gi(b3, a3, 1, c3);
          }
        }), il(a3, 1);
    }
  };
  Fc = function(a3) {
    if (13 === a3.tag) {
      var b2 = ih(a3, 134217728);
      if (null !== b2) {
        var c2 = R2();
        gi(b2, a3, 134217728, c2);
      }
      il(a3, 134217728);
    }
  };
  Gc = function(a3) {
    if (13 === a3.tag) {
      var b2 = yi(a3), c2 = ih(a3, b2);
      if (null !== c2) {
        var d2 = R2();
        gi(c2, a3, b2, d2);
      }
      il(a3, b2);
    }
  };
  Hc = function() {
    return C2;
  };
  Ic = function(a3, b2) {
    var c2 = C2;
    try {
      return C2 = a3, b2();
    } finally {
      C2 = c2;
    }
  };
  yb = function(a3, b2, c2) {
    switch (b2) {
      case "input":
        bb(a3, c2);
        b2 = c2.name;
        if ("radio" === c2.type && null != b2) {
          for (c2 = a3; c2.parentNode; ) c2 = c2.parentNode;
          c2 = c2.querySelectorAll("input[name=" + JSON.stringify("" + b2) + '][type="radio"]');
          for (b2 = 0; b2 < c2.length; b2++) {
            var d2 = c2[b2];
            if (d2 !== a3 && d2.form === a3.form) {
              var e2 = Db(d2);
              if (!e2) throw Error(p2(90));
              Wa(d2);
              bb(d2, e2);
            }
          }
        }
        break;
      case "textarea":
        ib(a3, c2);
        break;
      case "select":
        b2 = c2.value, null != b2 && fb(a3, !!c2.multiple, b2, false);
    }
  };
  Gb = Qk;
  Hb = Rk;
  var sl = { usingClientEntryPoint: false, Events: [Cb, ue3, Db, Eb, Fb, Qk] }, tl = { findFiberByHostInstance: Wc, bundleType: 0, version: "18.3.1", rendererPackageName: "react-dom" };
  var ul = { bundleType: tl.bundleType, version: tl.version, rendererPackageName: tl.rendererPackageName, rendererConfig: tl.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setErrorHandler: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ua2.ReactCurrentDispatcher, findHostInstanceByFiber: function(a3) {
    a3 = Zb(a3);
    return null === a3 ? null : a3.stateNode;
  }, findFiberByHostInstance: tl.findFiberByHostInstance || jl, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, reconcilerVersion: "18.3.1-next-f1338f8080-20240426" };
  if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
    var vl = __REACT_DEVTOOLS_GLOBAL_HOOK__;
    if (!vl.isDisabled && vl.supportsFiber) try {
      kc = vl.inject(ul), lc = vl;
    } catch (a3) {
    }
  }
  reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = sl;
  reactDom_production_min.createPortal = function(a3, b2) {
    var c2 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
    if (!nl(b2)) throw Error(p2(200));
    return cl(a3, b2, null, c2);
  };
  reactDom_production_min.createRoot = function(a3, b2) {
    if (!nl(a3)) throw Error(p2(299));
    var c2 = false, d2 = "", e2 = kl;
    null !== b2 && void 0 !== b2 && (true === b2.unstable_strictMode && (c2 = true), void 0 !== b2.identifierPrefix && (d2 = b2.identifierPrefix), void 0 !== b2.onRecoverableError && (e2 = b2.onRecoverableError));
    b2 = bl(a3, 1, false, null, null, c2, false, d2, e2);
    a3[uf] = b2.current;
    sf(8 === a3.nodeType ? a3.parentNode : a3);
    return new ll(b2);
  };
  reactDom_production_min.findDOMNode = function(a3) {
    if (null == a3) return null;
    if (1 === a3.nodeType) return a3;
    var b2 = a3._reactInternals;
    if (void 0 === b2) {
      if ("function" === typeof a3.render) throw Error(p2(188));
      a3 = Object.keys(a3).join(",");
      throw Error(p2(268, a3));
    }
    a3 = Zb(b2);
    a3 = null === a3 ? null : a3.stateNode;
    return a3;
  };
  reactDom_production_min.flushSync = function(a3) {
    return Rk(a3);
  };
  reactDom_production_min.hydrate = function(a3, b2, c2) {
    if (!ol(b2)) throw Error(p2(200));
    return rl(null, a3, b2, true, c2);
  };
  reactDom_production_min.hydrateRoot = function(a3, b2, c2) {
    if (!nl(a3)) throw Error(p2(405));
    var d2 = null != c2 && c2.hydratedSources || null, e2 = false, f2 = "", g2 = kl;
    null !== c2 && void 0 !== c2 && (true === c2.unstable_strictMode && (e2 = true), void 0 !== c2.identifierPrefix && (f2 = c2.identifierPrefix), void 0 !== c2.onRecoverableError && (g2 = c2.onRecoverableError));
    b2 = el(b2, null, a3, 1, null != c2 ? c2 : null, e2, false, f2, g2);
    a3[uf] = b2.current;
    sf(a3);
    if (d2) for (a3 = 0; a3 < d2.length; a3++) c2 = d2[a3], e2 = c2._getVersion, e2 = e2(c2._source), null == b2.mutableSourceEagerHydrationData ? b2.mutableSourceEagerHydrationData = [c2, e2] : b2.mutableSourceEagerHydrationData.push(
      c2,
      e2
    );
    return new ml(b2);
  };
  reactDom_production_min.render = function(a3, b2, c2) {
    if (!ol(b2)) throw Error(p2(200));
    return rl(null, a3, b2, false, c2);
  };
  reactDom_production_min.unmountComponentAtNode = function(a3) {
    if (!ol(a3)) throw Error(p2(40));
    return a3._reactRootContainer ? (Rk(function() {
      rl(null, null, a3, false, function() {
        a3._reactRootContainer = null;
        a3[uf] = null;
      });
    }), true) : false;
  };
  reactDom_production_min.unstable_batchedUpdates = Qk;
  reactDom_production_min.unstable_renderSubtreeIntoContainer = function(a3, b2, c2, d2) {
    if (!ol(c2)) throw Error(p2(200));
    if (null == a3 || void 0 === a3._reactInternals) throw Error(p2(38));
    return rl(a3, b2, c2, false, d2);
  };
  reactDom_production_min.version = "18.3.1-next-f1338f8080-20240426";
  return reactDom_production_min;
}
var hasRequiredReactDom;
function requireReactDom() {
  if (hasRequiredReactDom) return reactDom.exports;
  hasRequiredReactDom = 1;
  function checkDCE() {
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
      return;
    }
    try {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
    } catch (err) {
      console.error(err);
    }
  }
  {
    checkDCE();
    reactDom.exports = requireReactDom_production_min();
  }
  return reactDom.exports;
}
var reactDomExports = requireReactDom();
/**
 * @remix-run/router v1.23.2
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function _extends$4() {
  _extends$4 = Object.assign ? Object.assign.bind() : function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$4.apply(this, arguments);
}
var Action;
(function(Action2) {
  Action2["Pop"] = "POP";
  Action2["Push"] = "PUSH";
  Action2["Replace"] = "REPLACE";
})(Action || (Action = {}));
function invariant$2(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}
function warning(cond, message) {
  if (!cond) {
    if (typeof console !== "undefined") console.warn(message);
    try {
      throw new Error(message);
    } catch (e2) {
    }
  }
}
function createLocation(current, to, state, key) {
  let location = _extends$4({
    pathname: current,
    search: "",
    hash: ""
  }, typeof to === "string" ? parsePath(to) : to, {
    state,
    // TODO: This could be cleaned up.  push/replace should probably just take
    // full Locations now and avoid the need to run through this flow at all
    // But that's a pretty big refactor to the current test suite so going to
    // keep as is for the time being and just let any incoming keys take precedence
    key: to && to.key || key
  });
  return location;
}
function createPath(_ref) {
  let {
    pathname = "/",
    search = "",
    hash = ""
  } = _ref;
  if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
  if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  return pathname;
}
function parsePath(path) {
  let parsedPath = {};
  if (path) {
    let hashIndex = path.indexOf("#");
    if (hashIndex >= 0) {
      parsedPath.hash = path.substr(hashIndex);
      path = path.substr(0, hashIndex);
    }
    let searchIndex = path.indexOf("?");
    if (searchIndex >= 0) {
      parsedPath.search = path.substr(searchIndex);
      path = path.substr(0, searchIndex);
    }
    if (path) {
      parsedPath.pathname = path;
    }
  }
  return parsedPath;
}
var ResultType;
(function(ResultType2) {
  ResultType2["data"] = "data";
  ResultType2["deferred"] = "deferred";
  ResultType2["redirect"] = "redirect";
  ResultType2["error"] = "error";
})(ResultType || (ResultType = {}));
const immutableRouteKeys = /* @__PURE__ */ new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
function isIndexRoute(route) {
  return route.index === true;
}
function convertRoutesToDataRoutes(routes2, mapRouteProperties2, parentPath, manifest) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  if (manifest === void 0) {
    manifest = {};
  }
  return routes2.map((route, index) => {
    let treePath = [...parentPath, String(index)];
    let id = typeof route.id === "string" ? route.id : treePath.join("-");
    invariant$2(route.index !== true || !route.children, "Cannot specify children on an index route");
    invariant$2(!manifest[id], 'Found a route id collision on id "' + id + `".  Route id's must be globally unique within Data Router usages`);
    if (isIndexRoute(route)) {
      let indexRoute = _extends$4({}, route, mapRouteProperties2(route), {
        id
      });
      manifest[id] = indexRoute;
      return indexRoute;
    } else {
      let pathOrLayoutRoute = _extends$4({}, route, mapRouteProperties2(route), {
        id,
        children: void 0
      });
      manifest[id] = pathOrLayoutRoute;
      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties2, treePath, manifest);
      }
      return pathOrLayoutRoute;
    }
  });
}
function matchRoutes(routes2, locationArg, basename2) {
  if (basename2 === void 0) {
    basename2 = "/";
  }
  return matchRoutesImpl(routes2, locationArg, basename2);
}
function matchRoutesImpl(routes2, locationArg, basename2, allowPartial) {
  let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  let pathname = stripBasename(location.pathname || "/", basename2);
  if (pathname == null) {
    return null;
  }
  let branches = flattenRoutes(routes2);
  rankRouteBranches(branches);
  let matches = null;
  for (let i2 = 0; matches == null && i2 < branches.length; ++i2) {
    let decoded = decodePath(pathname);
    matches = matchRouteBranch(branches[i2], decoded);
  }
  return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
  let {
    route,
    pathname,
    params
  } = match;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    handle: route.handle
  };
}
function flattenRoutes(routes2, branches, parentsMeta, parentPath) {
  if (branches === void 0) {
    branches = [];
  }
  if (parentsMeta === void 0) {
    parentsMeta = [];
  }
  if (parentPath === void 0) {
    parentPath = "";
  }
  let flattenRoute = (route, index, relativePath) => {
    let meta2 = {
      relativePath: relativePath === void 0 ? route.path || "" : relativePath,
      caseSensitive: route.caseSensitive === true,
      childrenIndex: index,
      route
    };
    if (meta2.relativePath.startsWith("/")) {
      invariant$2(meta2.relativePath.startsWith(parentPath), 'Absolute route path "' + meta2.relativePath + '" nested under path ' + ('"' + parentPath + '" is not valid. An absolute child route path ') + "must start with the combined path of all its parent routes.");
      meta2.relativePath = meta2.relativePath.slice(parentPath.length);
    }
    let path = joinPaths([parentPath, meta2.relativePath]);
    let routesMeta = parentsMeta.concat(meta2);
    if (route.children && route.children.length > 0) {
      invariant$2(
        // Our types know better, but runtime JS may not!
        // @ts-expect-error
        route.index !== true,
        "Index routes must not have child routes. Please remove " + ('all child routes from route path "' + path + '".')
      );
      flattenRoutes(route.children, branches, routesMeta, path);
    }
    if (route.path == null && !route.index) {
      return;
    }
    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta
    });
  };
  routes2.forEach((route, index) => {
    var _route$path;
    if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
      flattenRoute(route, index);
    } else {
      for (let exploded of explodeOptionalSegments(route.path)) {
        flattenRoute(route, index, exploded);
      }
    }
  });
  return branches;
}
function explodeOptionalSegments(path) {
  let segments = path.split("/");
  if (segments.length === 0) return [];
  let [first, ...rest] = segments;
  let isOptional = first.endsWith("?");
  let required = first.replace(/\?$/, "");
  if (rest.length === 0) {
    return isOptional ? [required, ""] : [required];
  }
  let restExploded = explodeOptionalSegments(rest.join("/"));
  let result = [];
  result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
  if (isOptional) {
    result.push(...restExploded);
  }
  return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
  branches.sort((a3, b2) => a3.score !== b2.score ? b2.score - a3.score : compareIndexes(a3.routesMeta.map((meta2) => meta2.childrenIndex), b2.routesMeta.map((meta2) => meta2.childrenIndex)));
}
const paramRe = /^:[\w-]+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = (s2) => s2 === "*";
function computeScore(path, index) {
  let segments = path.split("/");
  let initialScore = segments.length;
  if (segments.some(isSplat)) {
    initialScore += splatPenalty;
  }
  if (index) {
    initialScore += indexRouteValue;
  }
  return segments.filter((s2) => !isSplat(s2)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a3, b2) {
  let siblings = a3.length === b2.length && a3.slice(0, -1).every((n2, i2) => n2 === b2[i2]);
  return siblings ? (
    // If two routes are siblings, we should try to match the earlier sibling
    // first. This allows people to have fine-grained control over the matching
    // behavior by simply putting routes with identical paths in the order they
    // want them tried.
    a3[a3.length - 1] - b2[b2.length - 1]
  ) : (
    // Otherwise, it doesn't really make sense to rank non-siblings by index,
    // so they sort equally.
    0
  );
}
function matchRouteBranch(branch, pathname, allowPartial) {
  let {
    routesMeta
  } = branch;
  let matchedParams = {};
  let matchedPathname = "/";
  let matches = [];
  for (let i2 = 0; i2 < routesMeta.length; ++i2) {
    let meta2 = routesMeta[i2];
    let end = i2 === routesMeta.length - 1;
    let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
    let match = matchPath({
      path: meta2.relativePath,
      caseSensitive: meta2.caseSensitive,
      end
    }, remainingPathname);
    let route = meta2.route;
    if (!match) {
      return null;
    }
    Object.assign(matchedParams, match.params);
    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams,
      pathname: joinPaths([matchedPathname, match.pathname]),
      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
      route
    });
    if (match.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
    }
  }
  return matches;
}
function matchPath(pattern2, pathname) {
  if (typeof pattern2 === "string") {
    pattern2 = {
      path: pattern2,
      caseSensitive: false,
      end: true
    };
  }
  let [matcher, compiledParams] = compilePath(pattern2.path, pattern2.caseSensitive, pattern2.end);
  let match = pathname.match(matcher);
  if (!match) return null;
  let matchedPathname = match[0];
  let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  let captureGroups = match.slice(1);
  let params = compiledParams.reduce((memo, _ref, index) => {
    let {
      paramName,
      isOptional
    } = _ref;
    if (paramName === "*") {
      let splatValue = captureGroups[index] || "";
      pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
    }
    const value = captureGroups[index];
    if (isOptional && !value) {
      memo[paramName] = void 0;
    } else {
      memo[paramName] = (value || "").replace(/%2F/g, "/");
    }
    return memo;
  }, {});
  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern: pattern2
  };
}
function compilePath(path, caseSensitive, end) {
  if (caseSensitive === void 0) {
    caseSensitive = false;
  }
  if (end === void 0) {
    end = true;
  }
  warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".'));
  let params = [];
  let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (_2, paramName, isOptional) => {
    params.push({
      paramName,
      isOptional: isOptional != null
    });
    return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  });
  if (path.endsWith("*")) {
    params.push({
      paramName: "*"
    });
    regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  } else if (end) {
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    regexpSource += "(?:(?=\\/|$))";
  } else ;
  let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  return [matcher, params];
}
function decodePath(value) {
  try {
    return value.split("/").map((v5) => decodeURIComponent(v5).replace(/\//g, "%2F")).join("/");
  } catch (error2) {
    warning(false, 'The URL path "' + value + '" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent ' + ("encoding (" + error2 + ")."));
    return value;
  }
}
function stripBasename(pathname, basename2) {
  if (basename2 === "/") return pathname;
  if (!pathname.toLowerCase().startsWith(basename2.toLowerCase())) {
    return null;
  }
  let startIndex = basename2.endsWith("/") ? basename2.length - 1 : basename2.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    return null;
  }
  return pathname.slice(startIndex) || "/";
}
const ABSOLUTE_URL_REGEX$1$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX$1$1.test(url);
function resolvePath(to, fromPathname) {
  if (fromPathname === void 0) {
    fromPathname = "/";
  }
  let {
    pathname: toPathname,
    search = "",
    hash = ""
  } = typeof to === "string" ? parsePath(to) : to;
  let pathname;
  if (toPathname) {
    if (isAbsoluteUrl(toPathname)) {
      pathname = toPathname;
    } else {
      if (toPathname.includes("//")) {
        let oldPathname = toPathname;
        toPathname = toPathname.replace(/\/\/+/g, "/");
        warning(false, "Pathnames cannot have embedded double slashes - normalizing " + (oldPathname + " -> " + toPathname));
      }
      if (toPathname.startsWith("/")) {
        pathname = resolvePathname(toPathname.substring(1), "/");
      } else {
        pathname = resolvePathname(toPathname, fromPathname);
      }
    }
  } else {
    pathname = fromPathname;
  }
  return {
    pathname,
    search: normalizeSearch(search),
    hash: normalizeHash(hash)
  };
}
function resolvePathname(relativePath, fromPathname) {
  let segments = fromPathname.replace(/\/+$/, "").split("/");
  let relativeSegments = relativePath.split("/");
  relativeSegments.forEach((segment) => {
    if (segment === "..") {
      if (segments.length > 1) segments.pop();
    } else if (segment !== ".") {
      segments.push(segment);
    }
  });
  return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
  return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "].  Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + 'a string in <Link to="..."> and the router will parse it for you.';
}
function getPathContributingMatches(matches) {
  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}
function getResolveToMatches(matches, v7_relativeSplatPath) {
  let pathMatches = getPathContributingMatches(matches);
  if (v7_relativeSplatPath) {
    return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
  }
  return pathMatches.map((match) => match.pathnameBase);
}
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  if (isPathRelative === void 0) {
    isPathRelative = false;
  }
  let to;
  if (typeof toArg === "string") {
    to = parsePath(toArg);
  } else {
    to = _extends$4({}, toArg);
    invariant$2(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
    invariant$2(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
    invariant$2(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  }
  let isEmptyPath = toArg === "" || to.pathname === "";
  let toPathname = isEmptyPath ? "/" : to.pathname;
  let from;
  if (toPathname == null) {
    from = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;
    if (!isPathRelative && toPathname.startsWith("..")) {
      let toSegments = toPathname.split("/");
      while (toSegments[0] === "..") {
        toSegments.shift();
        routePathnameIndex -= 1;
      }
      to.pathname = toSegments.join("/");
    }
    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  }
  let path = resolvePath(to, from);
  let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
    path.pathname += "/";
  }
  return path;
}
const joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
const normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
const json$1 = function json(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  let headers = new Headers(responseInit.headers);
  if (!headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json; charset=utf-8");
  }
  return new Response(JSON.stringify(data), _extends$4({}, responseInit, {
    headers
  }));
};
class AbortedDeferredError extends Error {
}
class DeferredData {
  constructor(data, responseInit) {
    this.pendingKeysSet = /* @__PURE__ */ new Set();
    this.subscribers = /* @__PURE__ */ new Set();
    this.deferredKeys = [];
    invariant$2(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
    let reject;
    this.abortPromise = new Promise((_2, r2) => reject = r2);
    this.controller = new AbortController();
    let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
    this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
    this.controller.signal.addEventListener("abort", onAbort);
    this.data = Object.entries(data).reduce((acc, _ref2) => {
      let [key, value] = _ref2;
      return Object.assign(acc, {
        [key]: this.trackPromise(key, value)
      });
    }, {});
    if (this.done) {
      this.unlistenAbortSignal();
    }
    this.init = responseInit;
  }
  trackPromise(key, value) {
    if (!(value instanceof Promise)) {
      return value;
    }
    this.deferredKeys.push(key);
    this.pendingKeysSet.add(key);
    let promise = Promise.race([value, this.abortPromise]).then((data) => this.onSettle(promise, key, void 0, data), (error2) => this.onSettle(promise, key, error2));
    promise.catch(() => {
    });
    Object.defineProperty(promise, "_tracked", {
      get: () => true
    });
    return promise;
  }
  onSettle(promise, key, error2, data) {
    if (this.controller.signal.aborted && error2 instanceof AbortedDeferredError) {
      this.unlistenAbortSignal();
      Object.defineProperty(promise, "_error", {
        get: () => error2
      });
      return Promise.reject(error2);
    }
    this.pendingKeysSet.delete(key);
    if (this.done) {
      this.unlistenAbortSignal();
    }
    if (error2 === void 0 && data === void 0) {
      let undefinedError = new Error('Deferred data for key "' + key + '" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');
      Object.defineProperty(promise, "_error", {
        get: () => undefinedError
      });
      this.emit(false, key);
      return Promise.reject(undefinedError);
    }
    if (data === void 0) {
      Object.defineProperty(promise, "_error", {
        get: () => error2
      });
      this.emit(false, key);
      return Promise.reject(error2);
    }
    Object.defineProperty(promise, "_data", {
      get: () => data
    });
    this.emit(false, key);
    return data;
  }
  emit(aborted, settledKey) {
    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));
  }
  subscribe(fn2) {
    this.subscribers.add(fn2);
    return () => this.subscribers.delete(fn2);
  }
  cancel() {
    this.controller.abort();
    this.pendingKeysSet.forEach((v5, k2) => this.pendingKeysSet.delete(k2));
    this.emit(true);
  }
  async resolveData(signal) {
    let aborted = false;
    if (!this.done) {
      let onAbort = () => this.cancel();
      signal.addEventListener("abort", onAbort);
      aborted = await new Promise((resolve2) => {
        this.subscribe((aborted2) => {
          signal.removeEventListener("abort", onAbort);
          if (aborted2 || this.done) {
            resolve2(aborted2);
          }
        });
      });
    }
    return aborted;
  }
  get done() {
    return this.pendingKeysSet.size === 0;
  }
  get unwrappedData() {
    invariant$2(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
    return Object.entries(this.data).reduce((acc, _ref3) => {
      let [key, value] = _ref3;
      return Object.assign(acc, {
        [key]: unwrapTrackedPromise(value)
      });
    }, {});
  }
  get pendingKeys() {
    return Array.from(this.pendingKeysSet);
  }
}
function isTrackedPromise$1(value) {
  return value instanceof Promise && value._tracked === true;
}
function unwrapTrackedPromise(value) {
  if (!isTrackedPromise$1(value)) {
    return value;
  }
  if (value._error) {
    throw value._error;
  }
  return value._data;
}
const defer$1 = function defer(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  return new DeferredData(data, responseInit);
};
const redirect$1 = function redirect(url, init) {
  if (init === void 0) {
    init = 302;
  }
  let responseInit = init;
  if (typeof responseInit === "number") {
    responseInit = {
      status: responseInit
    };
  } else if (typeof responseInit.status === "undefined") {
    responseInit.status = 302;
  }
  let headers = new Headers(responseInit.headers);
  headers.set("Location", url);
  return new Response(null, _extends$4({}, responseInit, {
    headers
  }));
};
class ErrorResponseImpl {
  constructor(status, statusText, data, internal) {
    if (internal === void 0) {
      internal = false;
    }
    this.status = status;
    this.statusText = statusText || "";
    this.internal = internal;
    if (data instanceof Error) {
      this.data = data.toString();
      this.error = data;
    } else {
      this.data = data;
    }
  }
}
function isRouteErrorResponse(error2) {
  return error2 != null && typeof error2.status === "number" && typeof error2.statusText === "string" && typeof error2.internal === "boolean" && "data" in error2;
}
const validMutationMethodsArr = ["post", "put", "patch", "delete"];
const validMutationMethods = new Set(validMutationMethodsArr);
const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
const validRequestMethods = new Set(validRequestMethodsArr);
const redirectStatusCodes$1 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
const IDLE_NAVIGATION = {
  state: "idle",
  location: void 0,
  formMethod: void 0,
  formAction: void 0,
  formEncType: void 0,
  formData: void 0,
  json: void 0,
  text: void 0
};
const IDLE_FETCHER = {
  state: "idle",
  data: void 0,
  formMethod: void 0,
  formAction: void 0,
  formEncType: void 0,
  formData: void 0,
  json: void 0,
  text: void 0
};
const IDLE_BLOCKER = {
  state: "unblocked",
  proceed: void 0,
  reset: void 0,
  location: void 0
};
const ABSOLUTE_URL_REGEX$3 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const defaultMapRouteProperties = (route) => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
function createStaticHandler(routes2, opts) {
  invariant$2(routes2.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  let manifest = {};
  let basename2 = (opts ? opts.basename : null) || "/";
  let mapRouteProperties2;
  if (opts != null && opts.mapRouteProperties) {
    mapRouteProperties2 = opts.mapRouteProperties;
  } else if (opts != null && opts.detectErrorBoundary) {
    let detectErrorBoundary = opts.detectErrorBoundary;
    mapRouteProperties2 = (route) => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties2 = defaultMapRouteProperties;
  }
  let future2 = _extends$4({
    v7_relativeSplatPath: false,
    v7_throwAbortReason: false
  }, opts ? opts.future : null);
  let dataRoutes = convertRoutesToDataRoutes(routes2, mapRouteProperties2, void 0, manifest);
  async function query2(request, _temp3) {
    let {
      requestContext,
      skipLoaderErrorBubbling,
      dataStrategy
    } = _temp3 === void 0 ? {} : _temp3;
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename2);
    if (!isValidMethod(method) && method !== "HEAD") {
      let error2 = getInternalRouterError(405, {
        method
      });
      let {
        matches: methodNotAllowedMatches,
        route
      } = getShortCircuitMatches(dataRoutes);
      return {
        basename: basename2,
        location,
        matches: methodNotAllowedMatches,
        loaderData: {},
        actionData: null,
        errors: {
          [route.id]: error2
        },
        statusCode: error2.status,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    } else if (!matches) {
      let error2 = getInternalRouterError(404, {
        pathname: location.pathname
      });
      let {
        matches: notFoundMatches,
        route
      } = getShortCircuitMatches(dataRoutes);
      return {
        basename: basename2,
        location,
        matches: notFoundMatches,
        loaderData: {},
        actionData: null,
        errors: {
          [route.id]: error2
        },
        statusCode: error2.status,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    }
    let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);
    if (isResponse$1(result)) {
      return result;
    }
    return _extends$4({
      location,
      basename: basename2
    }, result);
  }
  async function queryRoute(request, _temp4) {
    let {
      routeId,
      requestContext,
      dataStrategy
    } = _temp4 === void 0 ? {} : _temp4;
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename2);
    if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
      throw getInternalRouterError(405, {
        method
      });
    } else if (!matches) {
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let match = routeId ? matches.find((m2) => m2.route.id === routeId) : getTargetMatch(matches, location);
    if (routeId && !match) {
      throw getInternalRouterError(403, {
        pathname: location.pathname,
        routeId
      });
    } else if (!match) {
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
    if (isResponse$1(result)) {
      return result;
    }
    let error2 = result.errors ? Object.values(result.errors)[0] : void 0;
    if (error2 !== void 0) {
      throw error2;
    }
    if (result.actionData) {
      return Object.values(result.actionData)[0];
    }
    if (result.loaderData) {
      var _result$activeDeferre;
      let data = Object.values(result.loaderData)[0];
      if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
      }
      return data;
    }
    return void 0;
  }
  async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
    invariant$2(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
    try {
      if (isMutationMethod(request.method.toLowerCase())) {
        let result2 = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
        return result2;
      }
      let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
      return isResponse$1(result) ? result : _extends$4({}, result, {
        actionData: null,
        actionHeaders: {}
      });
    } catch (e2) {
      if (isDataStrategyResult(e2) && isResponse$1(e2.result)) {
        if (e2.type === ResultType.error) {
          throw e2.result;
        }
        return e2.result;
      }
      if (isRedirectResponse$1(e2)) {
        return e2;
      }
      throw e2;
    }
  }
  async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
    let result;
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      let error2 = getInternalRouterError(405, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: actionMatch.route.id
      });
      if (isRouteRequest) {
        throw error2;
      }
      result = {
        type: ResultType.error,
        error: error2
      };
    } else {
      let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
      result = results[actionMatch.route.id];
      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future2);
      }
    }
    if (isRedirectResult(result)) {
      throw new Response(null, {
        status: result.response.status,
        headers: {
          Location: result.response.headers.get("Location")
        }
      });
    }
    if (isDeferredResult(result)) {
      let error2 = getInternalRouterError(400, {
        type: "defer-action"
      });
      if (isRouteRequest) {
        throw error2;
      }
      result = {
        type: ResultType.error,
        error: error2
      };
    }
    if (isRouteRequest) {
      if (isErrorResult(result)) {
        throw result.error;
      }
      return {
        matches: [actionMatch],
        loaderData: {},
        actionData: {
          [actionMatch.route.id]: result.data
        },
        errors: null,
        // Note: statusCode + headers are unused here since queryRoute will
        // return the raw Response or value
        statusCode: 200,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    }
    let loaderRequest = new Request(request.url, {
      headers: request.headers,
      redirect: request.redirect,
      signal: request.signal
    });
    if (isErrorResult(result)) {
      let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
      let context3 = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);
      return _extends$4({}, context3, {
        statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
        actionData: null,
        actionHeaders: _extends$4({}, result.headers ? {
          [actionMatch.route.id]: result.headers
        } : {})
      });
    }
    let context2 = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
    return _extends$4({}, context2, {
      actionData: {
        [actionMatch.route.id]: result.data
      }
    }, result.statusCode ? {
      statusCode: result.statusCode
    } : {}, {
      actionHeaders: result.headers ? {
        [actionMatch.route.id]: result.headers
      } : {}
    });
  }
  async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
    let isRouteRequest = routeMatch != null;
    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
      throw getInternalRouterError(400, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: routeMatch == null ? void 0 : routeMatch.route.id
      });
    }
    let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
    let matchesToLoad = requestMatches.filter((m2) => m2.route.loader || m2.route.lazy);
    if (matchesToLoad.length === 0) {
      return {
        matches,
        // Add a null for all matched routes for proper revalidation on the client
        loaderData: matches.reduce((acc, m2) => Object.assign(acc, {
          [m2.route.id]: null
        }), {}),
        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
          [pendingActionResult[0]]: pendingActionResult[1].error
        } : null,
        statusCode: 200,
        loaderHeaders: {},
        activeDeferreds: null
      };
    }
    let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
    if (request.signal.aborted) {
      throwStaticHandlerAbortedError(request, isRouteRequest, future2);
    }
    let activeDeferreds = /* @__PURE__ */ new Map();
    let context2 = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);
    let executedLoaders = new Set(matchesToLoad.map((match) => match.route.id));
    matches.forEach((match) => {
      if (!executedLoaders.has(match.route.id)) {
        context2.loaderData[match.route.id] = null;
      }
    });
    return _extends$4({}, context2, {
      matches,
      activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
    });
  }
  async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
    let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties2, requestContext);
    let dataResults = {};
    await Promise.all(matches.map(async (match) => {
      if (!(match.route.id in results)) {
        return;
      }
      let result = results[match.route.id];
      if (isRedirectDataStrategyResultResult(result)) {
        let response = result.result;
        throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename2, future2.v7_relativeSplatPath);
      }
      if (isResponse$1(result.result) && isRouteRequest) {
        throw result;
      }
      dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
    }));
    return dataResults;
  }
  return {
    dataRoutes,
    query: query2,
    queryRoute
  };
}
function getStaticContextFromError(routes2, context2, error2) {
  let newContext = _extends$4({}, context2, {
    statusCode: isRouteErrorResponse(error2) ? error2.status : 500,
    errors: {
      [context2._deepestRenderedBoundaryId || routes2[0].id]: error2
    }
  });
  return newContext;
}
function throwStaticHandlerAbortedError(request, isRouteRequest, future2) {
  if (future2.v7_throwAbortReason && request.signal.reason !== void 0) {
    throw request.signal.reason;
  }
  let method = isRouteRequest ? "queryRoute" : "query";
  throw new Error(method + "() call aborted: " + request.method + " " + request.url);
}
function normalizeTo(location, matches, basename2, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  let contextualMatches;
  let activeRouteMatch;
  {
    contextualMatches = matches;
    activeRouteMatch = matches[matches.length - 1];
  }
  let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename2) || location.pathname, relative === "path");
  if (to == null) {
    path.search = location.search;
    path.hash = location.hash;
  }
  if ((to == null || to === "" || to === ".") && activeRouteMatch) {
    let nakedIndex = hasNakedIndexQuery(path.search);
    if (activeRouteMatch.route.index && !nakedIndex) {
      path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
    } else if (!activeRouteMatch.route.index && nakedIndex) {
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      params.delete("index");
      indexValues.filter((v5) => v5).forEach((v5) => params.append("index", v5));
      let qs = params.toString();
      path.search = qs ? "?" + qs : "";
    }
  }
  if (basename2 !== "/") {
    path.pathname = path.pathname === "/" ? basename2 : joinPaths([basename2, path.pathname]);
  }
  return createPath(path);
}
function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
  if (includeBoundary === void 0) {
    includeBoundary = false;
  }
  let index = matches.findIndex((m2) => m2.route.id === boundaryId);
  if (index >= 0) {
    return matches.slice(0, includeBoundary ? index + 1 : index);
  }
  return matches;
}
async function loadLazyRouteModule(route, mapRouteProperties2, manifest) {
  if (!route.lazy) {
    return;
  }
  let lazyRoute = await route.lazy();
  if (!route.lazy) {
    return;
  }
  let routeToUpdate = manifest[route.id];
  invariant$2(routeToUpdate, "No route found in manifest");
  let routeUpdates = {};
  for (let lazyRouteProperty in lazyRoute) {
    let staticRouteValue = routeToUpdate[lazyRouteProperty];
    let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
    // on the route updates
    lazyRouteProperty !== "hasErrorBoundary";
    warning(!isPropertyStaticallyDefined, 'Route "' + routeToUpdate.id + '" has a static property "' + lazyRouteProperty + '" defined but its lazy function is also returning a value for this property. ' + ('The lazy route property "' + lazyRouteProperty + '" will be ignored.'));
    if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
      routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
    }
  }
  Object.assign(routeToUpdate, routeUpdates);
  Object.assign(routeToUpdate, _extends$4({}, mapRouteProperties2(routeToUpdate), {
    lazy: void 0
  }));
}
async function defaultDataStrategy(_ref4) {
  let {
    matches
  } = _ref4;
  let matchesToLoad = matches.filter((m2) => m2.shouldLoad);
  let results = await Promise.all(matchesToLoad.map((m2) => m2.resolve()));
  return results.reduce((acc, result, i2) => Object.assign(acc, {
    [matchesToLoad[i2].route.id]: result
  }), {});
}
async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2, requestContext) {
  let loadRouteDefinitionsPromises = matches.map((m2) => m2.route.lazy ? loadLazyRouteModule(m2.route, mapRouteProperties2, manifest) : void 0);
  let dsMatches = matches.map((match, i2) => {
    let loadRoutePromise = loadRouteDefinitionsPromises[i2];
    let shouldLoad = matchesToLoad.some((m2) => m2.route.id === match.route.id);
    let resolve2 = async (handlerOverride) => {
      if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
        shouldLoad = true;
      }
      return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
        type: ResultType.data,
        result: void 0
      });
    };
    return _extends$4({}, match, {
      shouldLoad,
      resolve: resolve2
    });
  });
  let results = await dataStrategyImpl({
    matches: dsMatches,
    request,
    params: matches[0].params,
    fetcherKey,
    context: requestContext
  });
  try {
    await Promise.all(loadRouteDefinitionsPromises);
  } catch (e2) {
  }
  return results;
}
async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
  let result;
  let onReject;
  let runHandler = (handler) => {
    let reject;
    let abortPromise = new Promise((_2, r2) => reject = r2);
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);
    let actualHandler = (ctx) => {
      if (typeof handler !== "function") {
        return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ('"' + type + '" [routeId: ' + match.route.id + "]")));
      }
      return handler({
        request,
        params: match.params,
        context: staticContext
      }, ...ctx !== void 0 ? [ctx] : []);
    };
    let handlerPromise = (async () => {
      try {
        let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
        return {
          type: "data",
          result: val
        };
      } catch (e2) {
        return {
          type: "error",
          result: e2
        };
      }
    })();
    return Promise.race([handlerPromise, abortPromise]);
  };
  try {
    let handler = match.route[type];
    if (loadRoutePromise) {
      if (handler) {
        let handlerError;
        let [value] = await Promise.all([
          // If the handler throws, don't let it immediately bubble out,
          // since we need to let the lazy() execution finish so we know if this
          // route has a boundary that can handle the error
          runHandler(handler).catch((e2) => {
            handlerError = e2;
          }),
          loadRoutePromise
        ]);
        if (handlerError !== void 0) {
          throw handlerError;
        }
        result = value;
      } else {
        await loadRoutePromise;
        handler = match.route[type];
        if (handler) {
          result = await runHandler(handler);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match.route.id
          });
        } else {
          return {
            type: ResultType.data,
            result: void 0
          };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname
      });
    } else {
      result = await runHandler(handler);
    }
    invariant$2(result.result !== void 0, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ('"' + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  } catch (e2) {
    return {
      type: ResultType.error,
      result: e2
    };
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }
  return result;
}
async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  let {
    result,
    type
  } = dataStrategyResult;
  if (isResponse$1(result)) {
    let data;
    try {
      let contentType = result.headers.get("Content-Type");
      if (contentType && /\bapplication\/json\b/.test(contentType)) {
        if (result.body == null) {
          data = null;
        } else {
          data = await result.json();
        }
      } else {
        data = await result.text();
      }
    } catch (e2) {
      return {
        type: ResultType.error,
        error: e2
      };
    }
    if (type === ResultType.error) {
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(result.status, result.statusText, data),
        statusCode: result.status,
        headers: result.headers
      };
    }
    return {
      type: ResultType.data,
      data,
      statusCode: result.status,
      headers: result.headers
    };
  }
  if (type === ResultType.error) {
    if (isDataWithResponseInit(result)) {
      var _result$init3, _result$init4;
      if (result.data instanceof Error) {
        var _result$init, _result$init2;
        return {
          type: ResultType.error,
          error: result.data,
          statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
          headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : void 0
        };
      }
      return {
        type: ResultType.error,
        error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, void 0, result.data),
        statusCode: isRouteErrorResponse(result) ? result.status : void 0,
        headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : void 0
      };
    }
    return {
      type: ResultType.error,
      error: result,
      statusCode: isRouteErrorResponse(result) ? result.status : void 0
    };
  }
  if (isDeferredData$1(result)) {
    var _result$init5, _result$init6;
    return {
      type: ResultType.deferred,
      deferredData: result,
      statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
      headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
    };
  }
  if (isDataWithResponseInit(result)) {
    var _result$init7, _result$init8;
    return {
      type: ResultType.data,
      data: result.data,
      statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
      headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : void 0
    };
  }
  return {
    type: ResultType.data,
    data: result
  };
}
function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename2, v7_relativeSplatPath) {
  let location = response.headers.get("Location");
  invariant$2(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  if (!ABSOLUTE_URL_REGEX$3.test(location)) {
    let trimmedMatches = matches.slice(0, matches.findIndex((m2) => m2.route.id === routeId) + 1);
    location = normalizeTo(new URL(request.url), trimmedMatches, basename2, true, location, v7_relativeSplatPath);
    response.headers.set("Location", location);
  }
  return response;
}
function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
  let loaderData = {};
  let errors = null;
  let statusCode;
  let foundError = false;
  let loaderHeaders = {};
  let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  matches.forEach((match) => {
    if (!(match.route.id in results)) {
      return;
    }
    let id = match.route.id;
    let result = results[id];
    invariant$2(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
    if (isErrorResult(result)) {
      let error2 = result.error;
      if (pendingError !== void 0) {
        error2 = pendingError;
        pendingError = void 0;
      }
      errors = errors || {};
      if (skipLoaderErrorBubbling) {
        errors[id] = error2;
      } else {
        let boundaryMatch = findNearestBoundary(matches, id);
        if (errors[boundaryMatch.route.id] == null) {
          errors[boundaryMatch.route.id] = error2;
        }
      }
      loaderData[id] = void 0;
      if (!foundError) {
        foundError = true;
        statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
      }
      if (result.headers) {
        loaderHeaders[id] = result.headers;
      }
    } else {
      if (isDeferredResult(result)) {
        activeDeferreds.set(id, result.deferredData);
        loaderData[id] = result.deferredData.data;
        if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      } else {
        loaderData[id] = result.data;
        if (result.statusCode && result.statusCode !== 200 && !foundError) {
          statusCode = result.statusCode;
        }
        if (result.headers) {
          loaderHeaders[id] = result.headers;
        }
      }
    }
  });
  if (pendingError !== void 0 && pendingActionResult) {
    errors = {
      [pendingActionResult[0]]: pendingError
    };
    loaderData[pendingActionResult[0]] = void 0;
  }
  return {
    loaderData,
    errors,
    statusCode: statusCode || 200,
    loaderHeaders
  };
}
function findNearestBoundary(matches, routeId) {
  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m2) => m2.route.id === routeId) + 1) : [...matches];
  return eligibleMatches.reverse().find((m2) => m2.route.hasErrorBoundary === true) || matches[0];
}
function getShortCircuitMatches(routes2) {
  let route = routes2.length === 1 ? routes2[0] : routes2.find((r2) => r2.index || !r2.path || r2.path === "/") || {
    id: "__shim-error-route__"
  };
  return {
    matches: [{
      params: {},
      pathname: "",
      pathnameBase: "",
      route
    }],
    route
  };
}
function getInternalRouterError(status, _temp5) {
  let {
    pathname,
    routeId,
    method,
    type,
    message
  } = _temp5 === void 0 ? {} : _temp5;
  let statusText = "Unknown Server Error";
  let errorMessage = "Unknown @remix-run/router error";
  if (status === 400) {
    statusText = "Bad Request";
    if (method && pathname && routeId) {
      errorMessage = "You made a " + method + ' request to "' + pathname + '" but ' + ('did not provide a `loader` for route "' + routeId + '", ') + "so there is no way to handle the request.";
    } else if (type === "defer-action") {
      errorMessage = "defer() is not supported in actions";
    } else if (type === "invalid-body") {
      errorMessage = "Unable to encode submission body";
    }
  } else if (status === 403) {
    statusText = "Forbidden";
    errorMessage = 'Route "' + routeId + '" does not match URL "' + pathname + '"';
  } else if (status === 404) {
    statusText = "Not Found";
    errorMessage = 'No route matches URL "' + pathname + '"';
  } else if (status === 405) {
    statusText = "Method Not Allowed";
    if (method && pathname && routeId) {
      errorMessage = "You made a " + method.toUpperCase() + ' request to "' + pathname + '" but ' + ('did not provide an `action` for route "' + routeId + '", ') + "so there is no way to handle the request.";
    } else if (method) {
      errorMessage = 'Invalid request method "' + method.toUpperCase() + '"';
    }
  }
  return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
}
function isDataStrategyResult(result) {
  return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
}
function isRedirectDataStrategyResultResult(result) {
  return isResponse$1(result.result) && redirectStatusCodes$1.has(result.result.status);
}
function isDeferredResult(result) {
  return result.type === ResultType.deferred;
}
function isErrorResult(result) {
  return result.type === ResultType.error;
}
function isRedirectResult(result) {
  return (result && result.type) === ResultType.redirect;
}
function isDataWithResponseInit(value) {
  return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
}
function isDeferredData$1(value) {
  let deferred = value;
  return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
}
function isResponse$1(value) {
  return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
}
function isRedirectResponse$1(result) {
  if (!isResponse$1(result)) {
    return false;
  }
  let status = result.status;
  let location = result.headers.get("Location");
  return status >= 300 && status <= 399 && location != null;
}
function isValidMethod(method) {
  return validRequestMethods.has(method.toLowerCase());
}
function isMutationMethod(method) {
  return validMutationMethods.has(method.toLowerCase());
}
function hasNakedIndexQuery(search) {
  return new URLSearchParams(search).getAll("index").some((v5) => v5 === "");
}
function getTargetMatch(matches, location) {
  let search = typeof location === "string" ? parsePath(location).search : location.search;
  if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
    return matches[matches.length - 1];
  }
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}
/**
 * React Router v6.30.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function _extends$3() {
  _extends$3 = Object.assign ? Object.assign.bind() : function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$3.apply(this, arguments);
}
const DataRouterContext = /* @__PURE__ */ reactExports.createContext(null);
const DataRouterStateContext = /* @__PURE__ */ reactExports.createContext(null);
const AwaitContext = /* @__PURE__ */ reactExports.createContext(null);
const NavigationContext = /* @__PURE__ */ reactExports.createContext(null);
const LocationContext = /* @__PURE__ */ reactExports.createContext(null);
const RouteContext = /* @__PURE__ */ reactExports.createContext({
  outlet: null,
  matches: [],
  isDataRoute: false
});
const RouteErrorContext = /* @__PURE__ */ reactExports.createContext(null);
function useHref(to, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  !useInRouterContext() ? invariant$2(false) : void 0;
  let {
    basename: basename2,
    navigator: navigator2
  } = reactExports.useContext(NavigationContext);
  let {
    hash,
    pathname,
    search
  } = useResolvedPath(to, {
    relative
  });
  let joinedPathname = pathname;
  if (basename2 !== "/") {
    joinedPathname = pathname === "/" ? basename2 : joinPaths([basename2, pathname]);
  }
  return navigator2.createHref({
    pathname: joinedPathname,
    search,
    hash
  });
}
function useInRouterContext() {
  return reactExports.useContext(LocationContext) != null;
}
function useLocation() {
  !useInRouterContext() ? invariant$2(false) : void 0;
  return reactExports.useContext(LocationContext).location;
}
function useIsomorphicLayoutEffect$2(cb) {
  let isStatic = reactExports.useContext(NavigationContext).static;
  if (!isStatic) {
    reactExports.useLayoutEffect(cb);
  }
}
function useNavigate() {
  let {
    isDataRoute
  } = reactExports.useContext(RouteContext);
  return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
  !useInRouterContext() ? invariant$2(false) : void 0;
  let dataRouterContext = reactExports.useContext(DataRouterContext);
  let {
    basename: basename2,
    future: future2,
    navigator: navigator2
  } = reactExports.useContext(NavigationContext);
  let {
    matches
  } = reactExports.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(getResolveToMatches(matches, future2.v7_relativeSplatPath));
  let activeRef = reactExports.useRef(false);
  useIsomorphicLayoutEffect$2(() => {
    activeRef.current = true;
  });
  let navigate = reactExports.useCallback(function(to, options) {
    if (options === void 0) {
      options = {};
    }
    if (!activeRef.current) return;
    if (typeof to === "number") {
      navigator2.go(to);
      return;
    }
    let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
    if (dataRouterContext == null && basename2 !== "/") {
      path.pathname = path.pathname === "/" ? basename2 : joinPaths([basename2, path.pathname]);
    }
    (!!options.replace ? navigator2.replace : navigator2.push)(path, options.state, options);
  }, [basename2, navigator2, routePathnamesJson, locationPathname, dataRouterContext]);
  return navigate;
}
const OutletContext = /* @__PURE__ */ reactExports.createContext(null);
function useOutletContext() {
  return reactExports.useContext(OutletContext);
}
function useOutlet(context2) {
  let outlet = reactExports.useContext(RouteContext).outlet;
  if (outlet) {
    return /* @__PURE__ */ reactExports.createElement(OutletContext.Provider, {
      value: context2
    }, outlet);
  }
  return outlet;
}
function useResolvedPath(to, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    future: future2
  } = reactExports.useContext(NavigationContext);
  let {
    matches
  } = reactExports.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(getResolveToMatches(matches, future2.v7_relativeSplatPath));
  return reactExports.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}
function useRoutesImpl(routes2, locationArg, dataRouterState, future2) {
  !useInRouterContext() ? invariant$2(false) : void 0;
  let {
    navigator: navigator2
  } = reactExports.useContext(NavigationContext);
  let {
    matches: parentMatches
  } = reactExports.useContext(RouteContext);
  let routeMatch = parentMatches[parentMatches.length - 1];
  let parentParams = routeMatch ? routeMatch.params : {};
  routeMatch ? routeMatch.pathname : "/";
  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  routeMatch && routeMatch.route;
  let locationFromContext = useLocation();
  let location;
  {
    location = locationFromContext;
  }
  let pathname = location.pathname || "/";
  let remainingPathname = pathname;
  if (parentPathnameBase !== "/") {
    let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
    let segments = pathname.replace(/^\//, "").split("/");
    remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  }
  let matches = matchRoutes(routes2, {
    pathname: remainingPathname
  });
  let renderedMatches = _renderMatches(matches && matches.map((match) => Object.assign({}, match, {
    params: Object.assign({}, parentParams, match.params),
    pathname: joinPaths([
      parentPathnameBase,
      // Re-encode pathnames that were decoded inside matchRoutes
      navigator2.encodeLocation ? navigator2.encodeLocation(match.pathname).pathname : match.pathname
    ]),
    pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
      parentPathnameBase,
      // Re-encode pathnames that were decoded inside matchRoutes
      navigator2.encodeLocation ? navigator2.encodeLocation(match.pathnameBase).pathname : match.pathnameBase
    ])
  })), parentMatches, dataRouterState, future2);
  return renderedMatches;
}
function DefaultErrorComponent() {
  let error2 = useRouteError();
  let message = isRouteErrorResponse(error2) ? error2.status + " " + error2.statusText : error2 instanceof Error ? error2.message : JSON.stringify(error2);
  let stack = error2 instanceof Error ? error2.stack : null;
  let lightgrey = "rgba(200,200,200, 0.5)";
  let preStyles = {
    padding: "0.5rem",
    backgroundColor: lightgrey
  };
  let devInfo = null;
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ reactExports.createElement("h3", {
    style: {
      fontStyle: "italic"
    }
  }, message), stack ? /* @__PURE__ */ reactExports.createElement("pre", {
    style: preStyles
  }, stack) : null, devInfo);
}
const defaultErrorElement = /* @__PURE__ */ reactExports.createElement(DefaultErrorComponent, null);
class RenderErrorBoundary extends reactExports.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: props.location,
      revalidation: props.revalidation,
      error: props.error
    };
  }
  static getDerivedStateFromError(error2) {
    return {
      error: error2
    };
  }
  static getDerivedStateFromProps(props, state) {
    if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
      return {
        error: props.error,
        location: props.location,
        revalidation: props.revalidation
      };
    }
    return {
      error: props.error !== void 0 ? props.error : state.error,
      location: state.location,
      revalidation: props.revalidation || state.revalidation
    };
  }
  componentDidCatch(error2, errorInfo) {
    console.error("React Router caught the following error during render", error2, errorInfo);
  }
  render() {
    return this.state.error !== void 0 ? /* @__PURE__ */ reactExports.createElement(RouteContext.Provider, {
      value: this.props.routeContext
    }, /* @__PURE__ */ reactExports.createElement(RouteErrorContext.Provider, {
      value: this.state.error,
      children: this.props.component
    })) : this.props.children;
  }
}
function RenderedRoute(_ref) {
  let {
    routeContext,
    match,
    children
  } = _ref;
  let dataRouterContext = reactExports.useContext(DataRouterContext);
  if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  }
  return /* @__PURE__ */ reactExports.createElement(RouteContext.Provider, {
    value: routeContext
  }, children);
}
function _renderMatches(matches, parentMatches, dataRouterState, future2) {
  var _dataRouterState;
  if (parentMatches === void 0) {
    parentMatches = [];
  }
  if (dataRouterState === void 0) {
    dataRouterState = null;
  }
  if (future2 === void 0) {
    future2 = null;
  }
  if (matches == null) {
    var _future;
    if (!dataRouterState) {
      return null;
    }
    if (dataRouterState.errors) {
      matches = dataRouterState.matches;
    } else if ((_future = future2) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
      matches = dataRouterState.matches;
    } else {
      return null;
    }
  }
  let renderedMatches = matches;
  let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;
  if (errors != null) {
    let errorIndex = renderedMatches.findIndex((m2) => m2.route.id && (errors == null ? void 0 : errors[m2.route.id]) !== void 0);
    !(errorIndex >= 0) ? invariant$2(false) : void 0;
    renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  }
  let renderFallback = false;
  let fallbackIndex = -1;
  if (dataRouterState && future2 && future2.v7_partialHydration) {
    for (let i2 = 0; i2 < renderedMatches.length; i2++) {
      let match = renderedMatches[i2];
      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
        fallbackIndex = i2;
      }
      if (match.route.id) {
        let {
          loaderData,
          errors: errors2
        } = dataRouterState;
        let needsToRunLoader = match.route.loader && loaderData[match.route.id] === void 0 && (!errors2 || errors2[match.route.id] === void 0);
        if (match.route.lazy || needsToRunLoader) {
          renderFallback = true;
          if (fallbackIndex >= 0) {
            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
          } else {
            renderedMatches = [renderedMatches[0]];
          }
          break;
        }
      }
    }
  }
  return renderedMatches.reduceRight((outlet, match, index) => {
    let error2;
    let shouldRenderHydrateFallback = false;
    let errorElement = null;
    let hydrateFallbackElement = null;
    if (dataRouterState) {
      error2 = errors && match.route.id ? errors[match.route.id] : void 0;
      errorElement = match.route.errorElement || defaultErrorElement;
      if (renderFallback) {
        if (fallbackIndex < 0 && index === 0) {
          warningOnce("route-fallback");
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = null;
        } else if (fallbackIndex === index) {
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = match.route.hydrateFallbackElement || null;
        }
      }
    }
    let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
    let getChildren = () => {
      let children;
      if (error2) {
        children = errorElement;
      } else if (shouldRenderHydrateFallback) {
        children = hydrateFallbackElement;
      } else if (match.route.Component) {
        children = /* @__PURE__ */ reactExports.createElement(match.route.Component, null);
      } else if (match.route.element) {
        children = match.route.element;
      } else {
        children = outlet;
      }
      return /* @__PURE__ */ reactExports.createElement(RenderedRoute, {
        match,
        routeContext: {
          outlet,
          matches: matches2,
          isDataRoute: dataRouterState != null
        },
        children
      });
    };
    return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ reactExports.createElement(RenderErrorBoundary, {
      location: dataRouterState.location,
      revalidation: dataRouterState.revalidation,
      component: errorElement,
      error: error2,
      children: getChildren(),
      routeContext: {
        outlet: null,
        matches: matches2,
        isDataRoute: true
      }
    }) : getChildren();
  }, null);
}
var DataRouterHook$1 = /* @__PURE__ */ (function(DataRouterHook2) {
  DataRouterHook2["UseBlocker"] = "useBlocker";
  DataRouterHook2["UseRevalidator"] = "useRevalidator";
  DataRouterHook2["UseNavigateStable"] = "useNavigate";
  return DataRouterHook2;
})(DataRouterHook$1 || {});
var DataRouterStateHook$1 = /* @__PURE__ */ (function(DataRouterStateHook2) {
  DataRouterStateHook2["UseBlocker"] = "useBlocker";
  DataRouterStateHook2["UseLoaderData"] = "useLoaderData";
  DataRouterStateHook2["UseActionData"] = "useActionData";
  DataRouterStateHook2["UseRouteError"] = "useRouteError";
  DataRouterStateHook2["UseNavigation"] = "useNavigation";
  DataRouterStateHook2["UseRouteLoaderData"] = "useRouteLoaderData";
  DataRouterStateHook2["UseMatches"] = "useMatches";
  DataRouterStateHook2["UseRevalidator"] = "useRevalidator";
  DataRouterStateHook2["UseNavigateStable"] = "useNavigate";
  DataRouterStateHook2["UseRouteId"] = "useRouteId";
  return DataRouterStateHook2;
})(DataRouterStateHook$1 || {});
function useDataRouterContext$2(hookName) {
  let ctx = reactExports.useContext(DataRouterContext);
  !ctx ? invariant$2(false) : void 0;
  return ctx;
}
function useDataRouterState$1(hookName) {
  let state = reactExports.useContext(DataRouterStateContext);
  !state ? invariant$2(false) : void 0;
  return state;
}
function useRouteContext(hookName) {
  let route = reactExports.useContext(RouteContext);
  !route ? invariant$2(false) : void 0;
  return route;
}
function useCurrentRouteId(hookName) {
  let route = useRouteContext();
  let thisRoute = route.matches[route.matches.length - 1];
  !thisRoute.route.id ? invariant$2(false) : void 0;
  return thisRoute.route.id;
}
function useRouteId() {
  return useCurrentRouteId();
}
function useNavigation() {
  let state = useDataRouterState$1(DataRouterStateHook$1.UseNavigation);
  return state.navigation;
}
function useMatches$1() {
  let {
    matches,
    loaderData
  } = useDataRouterState$1();
  return reactExports.useMemo(() => matches.map((m2) => convertRouteMatchToUiMatch(m2, loaderData)), [matches, loaderData]);
}
function useLoaderData$1() {
  let state = useDataRouterState$1();
  let routeId = useCurrentRouteId();
  if (state.errors && state.errors[routeId] != null) {
    console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
    return void 0;
  }
  return state.loaderData[routeId];
}
function useActionData$1() {
  let state = useDataRouterState$1();
  let routeId = useCurrentRouteId();
  return state.actionData ? state.actionData[routeId] : void 0;
}
function useRouteError() {
  var _state$errors;
  let error2 = reactExports.useContext(RouteErrorContext);
  let state = useDataRouterState$1();
  let routeId = useCurrentRouteId();
  if (error2 !== void 0) {
    return error2;
  }
  return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
}
function useAsyncValue() {
  let value = reactExports.useContext(AwaitContext);
  return value == null ? void 0 : value._data;
}
function useAsyncError() {
  let value = reactExports.useContext(AwaitContext);
  return value == null ? void 0 : value._error;
}
function useNavigateStable() {
  let {
    router
  } = useDataRouterContext$2(DataRouterHook$1.UseNavigateStable);
  let id = useCurrentRouteId();
  let activeRef = reactExports.useRef(false);
  useIsomorphicLayoutEffect$2(() => {
    activeRef.current = true;
  });
  let navigate = reactExports.useCallback(function(to, options) {
    if (options === void 0) {
      options = {};
    }
    if (!activeRef.current) return;
    if (typeof to === "number") {
      router.navigate(to);
    } else {
      router.navigate(to, _extends$3({
        fromRouteId: id
      }, options));
    }
  }, [router, id]);
  return navigate;
}
const alreadyWarned$1 = {};
function warningOnce(key, cond, message) {
  if (!alreadyWarned$1[key]) {
    alreadyWarned$1[key] = true;
  }
}
function Outlet(props) {
  return useOutlet(props.context);
}
function Router(_ref5) {
  let {
    basename: basenameProp = "/",
    children = null,
    location: locationProp,
    navigationType = Action.Pop,
    navigator: navigator2,
    static: staticProp = false,
    future: future2
  } = _ref5;
  !!useInRouterContext() ? invariant$2(false) : void 0;
  let basename2 = basenameProp.replace(/^\/*/, "/");
  let navigationContext = reactExports.useMemo(() => ({
    basename: basename2,
    navigator: navigator2,
    static: staticProp,
    future: _extends$3({
      v7_relativeSplatPath: false
    }, future2)
  }), [basename2, future2, navigator2, staticProp]);
  if (typeof locationProp === "string") {
    locationProp = parsePath(locationProp);
  }
  let {
    pathname = "/",
    search = "",
    hash = "",
    state = null,
    key = "default"
  } = locationProp;
  let locationContext = reactExports.useMemo(() => {
    let trailingPathname = stripBasename(pathname, basename2);
    if (trailingPathname == null) {
      return null;
    }
    return {
      location: {
        pathname: trailingPathname,
        search,
        hash,
        state,
        key
      },
      navigationType
    };
  }, [basename2, pathname, search, hash, state, key, navigationType]);
  if (locationContext == null) {
    return null;
  }
  return /* @__PURE__ */ reactExports.createElement(NavigationContext.Provider, {
    value: navigationContext
  }, /* @__PURE__ */ reactExports.createElement(LocationContext.Provider, {
    children,
    value: locationContext
  }));
}
function Await$1(_ref7) {
  let {
    children,
    errorElement,
    resolve: resolve2
  } = _ref7;
  return /* @__PURE__ */ reactExports.createElement(AwaitErrorBoundary, {
    resolve: resolve2,
    errorElement
  }, /* @__PURE__ */ reactExports.createElement(ResolveAwait, null, children));
}
var AwaitRenderStatus = /* @__PURE__ */ (function(AwaitRenderStatus2) {
  AwaitRenderStatus2[AwaitRenderStatus2["pending"] = 0] = "pending";
  AwaitRenderStatus2[AwaitRenderStatus2["success"] = 1] = "success";
  AwaitRenderStatus2[AwaitRenderStatus2["error"] = 2] = "error";
  return AwaitRenderStatus2;
})(AwaitRenderStatus || {});
const neverSettledPromise = new Promise(() => {
});
class AwaitErrorBoundary extends reactExports.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null
    };
  }
  static getDerivedStateFromError(error2) {
    return {
      error: error2
    };
  }
  componentDidCatch(error2, errorInfo) {
    console.error("<Await> caught the following error during render", error2, errorInfo);
  }
  render() {
    let {
      children,
      errorElement,
      resolve: resolve2
    } = this.props;
    let promise = null;
    let status = AwaitRenderStatus.pending;
    if (!(resolve2 instanceof Promise)) {
      status = AwaitRenderStatus.success;
      promise = Promise.resolve();
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_data", {
        get: () => resolve2
      });
    } else if (this.state.error) {
      status = AwaitRenderStatus.error;
      let renderError = this.state.error;
      promise = Promise.reject().catch(() => {
      });
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_error", {
        get: () => renderError
      });
    } else if (resolve2._tracked) {
      promise = resolve2;
      status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
    } else {
      status = AwaitRenderStatus.pending;
      Object.defineProperty(resolve2, "_tracked", {
        get: () => true
      });
      promise = resolve2.then((data) => Object.defineProperty(resolve2, "_data", {
        get: () => data
      }), (error2) => Object.defineProperty(resolve2, "_error", {
        get: () => error2
      }));
    }
    if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
      throw neverSettledPromise;
    }
    if (status === AwaitRenderStatus.error && !errorElement) {
      throw promise._error;
    }
    if (status === AwaitRenderStatus.error) {
      return /* @__PURE__ */ reactExports.createElement(AwaitContext.Provider, {
        value: promise,
        children: errorElement
      });
    }
    if (status === AwaitRenderStatus.success) {
      return /* @__PURE__ */ reactExports.createElement(AwaitContext.Provider, {
        value: promise,
        children
      });
    }
    throw promise;
  }
}
function ResolveAwait(_ref8) {
  let {
    children
  } = _ref8;
  let data = useAsyncValue();
  let toRender = typeof children === "function" ? children(data) : children;
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, toRender);
}
function mapRouteProperties(route) {
  let updates = {
    // Note: this check also occurs in createRoutesFromChildren so update
    // there if you change this -- please and thank you!
    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  };
  if (route.Component) {
    Object.assign(updates, {
      element: /* @__PURE__ */ reactExports.createElement(route.Component),
      Component: void 0
    });
  }
  if (route.HydrateFallback) {
    Object.assign(updates, {
      hydrateFallbackElement: /* @__PURE__ */ reactExports.createElement(route.HydrateFallback),
      HydrateFallback: void 0
    });
  }
  if (route.ErrorBoundary) {
    Object.assign(updates, {
      errorElement: /* @__PURE__ */ reactExports.createElement(route.ErrorBoundary),
      ErrorBoundary: void 0
    });
  }
  return updates;
}
/**
 * React Router DOM v6.30.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function _extends$2() {
  _extends$2 = Object.assign ? Object.assign.bind() : function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$2.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i2;
  for (i2 = 0; i2 < sourceKeys.length; i2++) {
    key = sourceKeys[i2];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
  return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
  return event.button === 0 && // Ignore everything but left clicks
  (!target || target === "_self") && // Let browser handle "target=_blank" etc.
  !isModifiedEvent(event);
}
function createSearchParams(init) {
  if (init === void 0) {
    init = "";
  }
  return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
    let value = init[key];
    return memo.concat(Array.isArray(value) ? value.map((v5) => [key, v5]) : [[key, value]]);
  }, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  let searchParams = createSearchParams(locationSearch);
  if (defaultSearchParams) {
    defaultSearchParams.forEach((_2, key) => {
      if (!searchParams.has(key)) {
        defaultSearchParams.getAll(key).forEach((value) => {
          searchParams.append(key, value);
        });
      }
    });
  }
  return searchParams;
}
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
  if (_formDataSupportsSubmitter === null) {
    try {
      new FormData(
        document.createElement("form"),
        // @ts-expect-error if FormData supports the submitter parameter, this will throw
        0
      );
      _formDataSupportsSubmitter = false;
    } catch (e2) {
      _formDataSupportsSubmitter = true;
    }
  }
  return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = /* @__PURE__ */ new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
  if (encType != null && !supportedFormEncTypes.has(encType)) {
    return null;
  }
  return encType;
}
function getFormSubmissionInfo(target, basename2) {
  let method;
  let action2;
  let encType;
  let formData;
  let body;
  if (isFormElement(target)) {
    let attr = target.getAttribute("action");
    action2 = attr ? stripBasename(attr, basename2) : null;
    method = target.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(target);
  } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
    let form = target.form;
    if (form == null) {
      throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');
    }
    let attr = target.getAttribute("formaction") || form.getAttribute("action");
    action2 = attr ? stripBasename(attr, basename2) : null;
    method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(form, target);
    if (!isFormDataSubmitterSupported()) {
      let {
        name,
        type,
        value
      } = target;
      if (type === "image") {
        let prefix = name ? name + "." : "";
        formData.append(prefix + "x", "0");
        formData.append(prefix + "y", "0");
      } else if (name) {
        formData.append(name, value);
      }
    }
  } else if (isHtmlElement(target)) {
    throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');
  } else {
    method = defaultMethod;
    action2 = null;
    encType = defaultEncType;
    body = target;
  }
  if (formData && encType === "text/plain") {
    body = formData;
    formData = void 0;
  }
  return {
    action: action2,
    method: method.toLowerCase(),
    encType,
    formData,
    body
  };
}
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"], _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"], _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
const REACT_ROUTER_VERSION = "6";
try {
  window.__reactRouterVersion = REACT_ROUTER_VERSION;
} catch (e2) {
}
const ViewTransitionContext = /* @__PURE__ */ reactExports.createContext({
  isTransitioning: false
});
const FetchersContext = /* @__PURE__ */ reactExports.createContext(/* @__PURE__ */ new Map());
const USE_ID = "useId";
const useIdImpl = t$6[USE_ID];
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX$2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const Link$1 = /* @__PURE__ */ reactExports.forwardRef(function LinkWithRef(_ref7, ref) {
  let {
    onClick,
    relative,
    reloadDocument,
    replace: replace2,
    state,
    target,
    to,
    preventScrollReset,
    viewTransition
  } = _ref7, rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
  let {
    basename: basename2
  } = reactExports.useContext(NavigationContext);
  let absoluteHref;
  let isExternal = false;
  if (typeof to === "string" && ABSOLUTE_URL_REGEX$2.test(to)) {
    absoluteHref = to;
    if (isBrowser) {
      try {
        let currentUrl = new URL(window.location.href);
        let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
        let path = stripBasename(targetUrl.pathname, basename2);
        if (targetUrl.origin === currentUrl.origin && path != null) {
          to = path + targetUrl.search + targetUrl.hash;
        } else {
          isExternal = true;
        }
      } catch (e2) {
      }
    }
  }
  let href = useHref(to, {
    relative
  });
  let internalOnClick = useLinkClickHandler(to, {
    replace: replace2,
    state,
    target,
    preventScrollReset,
    relative,
    viewTransition
  });
  function handleClick(event) {
    if (onClick) onClick(event);
    if (!event.defaultPrevented) {
      internalOnClick(event);
    }
  }
  return (
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    /* @__PURE__ */ reactExports.createElement("a", _extends$2({}, rest, {
      href: absoluteHref || href,
      onClick: isExternal || reloadDocument ? onClick : handleClick,
      ref,
      target
    }))
  );
});
const NavLink$1 = /* @__PURE__ */ reactExports.forwardRef(function NavLinkWithRef(_ref8, ref) {
  let {
    "aria-current": ariaCurrentProp = "page",
    caseSensitive = false,
    className: classNameProp = "",
    end = false,
    style: styleProp,
    to,
    viewTransition,
    children
  } = _ref8, rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
  let path = useResolvedPath(to, {
    relative: rest.relative
  });
  let location = useLocation();
  let routerState = reactExports.useContext(DataRouterStateContext);
  let {
    navigator: navigator2,
    basename: basename2
  } = reactExports.useContext(NavigationContext);
  let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useViewTransitionState(path) && viewTransition === true;
  let toPathname = navigator2.encodeLocation ? navigator2.encodeLocation(path).pathname : path.pathname;
  let locationPathname = location.pathname;
  let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  if (!caseSensitive) {
    locationPathname = locationPathname.toLowerCase();
    nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
    toPathname = toPathname.toLowerCase();
  }
  if (nextLocationPathname && basename2) {
    nextLocationPathname = stripBasename(nextLocationPathname, basename2) || nextLocationPathname;
  }
  const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  let renderProps = {
    isActive,
    isPending,
    isTransitioning
  };
  let ariaCurrent = isActive ? ariaCurrentProp : void 0;
  let className;
  if (typeof classNameProp === "function") {
    className = classNameProp(renderProps);
  } else {
    className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  }
  let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  return /* @__PURE__ */ reactExports.createElement(Link$1, _extends$2({}, rest, {
    "aria-current": ariaCurrent,
    className,
    ref,
    style,
    to,
    viewTransition
  }), typeof children === "function" ? children(renderProps) : children);
});
const Form$1 = /* @__PURE__ */ reactExports.forwardRef((_ref9, forwardedRef) => {
  let {
    fetcherKey,
    navigate,
    reloadDocument,
    replace: replace2,
    state,
    method = defaultMethod,
    action: action2,
    onSubmit,
    relative,
    preventScrollReset,
    viewTransition
  } = _ref9, props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
  let submit = useSubmit();
  let formAction = useFormAction(action2, {
    relative
  });
  let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  let submitHandler = (event) => {
    onSubmit && onSubmit(event);
    if (event.defaultPrevented) return;
    event.preventDefault();
    let submitter = event.nativeEvent.submitter;
    let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
    submit(submitter || event.currentTarget, {
      fetcherKey,
      method: submitMethod,
      navigate,
      replace: replace2,
      state,
      relative,
      preventScrollReset,
      viewTransition
    });
  };
  return /* @__PURE__ */ reactExports.createElement("form", _extends$2({
    ref: forwardedRef,
    method: formMethod,
    action: formAction,
    onSubmit: reloadDocument ? onSubmit : submitHandler
  }, props));
});
var DataRouterHook;
(function(DataRouterHook2) {
  DataRouterHook2["UseScrollRestoration"] = "useScrollRestoration";
  DataRouterHook2["UseSubmit"] = "useSubmit";
  DataRouterHook2["UseSubmitFetcher"] = "useSubmitFetcher";
  DataRouterHook2["UseFetcher"] = "useFetcher";
  DataRouterHook2["useViewTransitionState"] = "useViewTransitionState";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function(DataRouterStateHook2) {
  DataRouterStateHook2["UseFetcher"] = "useFetcher";
  DataRouterStateHook2["UseFetchers"] = "useFetchers";
  DataRouterStateHook2["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function useDataRouterContext$1(hookName) {
  let ctx = reactExports.useContext(DataRouterContext);
  !ctx ? invariant$2(false) : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = reactExports.useContext(DataRouterStateContext);
  !state ? invariant$2(false) : void 0;
  return state;
}
function useLinkClickHandler(to, _temp2) {
  let {
    target,
    replace: replaceProp,
    state,
    preventScrollReset,
    relative,
    viewTransition
  } = _temp2 === void 0 ? {} : _temp2;
  let navigate = useNavigate();
  let location = useLocation();
  let path = useResolvedPath(to, {
    relative
  });
  return reactExports.useCallback((event) => {
    if (shouldProcessLinkClick(event, target)) {
      event.preventDefault();
      let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
      navigate(to, {
        replace: replace2,
        state,
        preventScrollReset,
        relative,
        viewTransition
      });
    }
  }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
}
function useSearchParams(defaultInit) {
  let defaultSearchParamsRef = reactExports.useRef(createSearchParams(defaultInit));
  let hasSetSearchParamsRef = reactExports.useRef(false);
  let location = useLocation();
  let searchParams = reactExports.useMemo(() => (
    // Only merge in the defaults if we haven't yet called setSearchParams.
    // Once we call that we want those to take precedence, otherwise you can't
    // remove a param with setSearchParams({}) if it has an initial value
    getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current)
  ), [location.search]);
  let navigate = useNavigate();
  let setSearchParams = reactExports.useCallback((nextInit, navigateOptions) => {
    const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
    hasSetSearchParamsRef.current = true;
    navigate("?" + newSearchParams, navigateOptions);
  }, [navigate, searchParams]);
  return [searchParams, setSearchParams];
}
function validateClientSideSubmission() {
  if (typeof document === "undefined") {
    throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.");
  }
}
let fetcherId = 0;
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
function useSubmit() {
  let {
    router
  } = useDataRouterContext$1(DataRouterHook.UseSubmit);
  let {
    basename: basename2
  } = reactExports.useContext(NavigationContext);
  let currentRouteId = useRouteId();
  return reactExports.useCallback(function(target, options) {
    if (options === void 0) {
      options = {};
    }
    validateClientSideSubmission();
    let {
      action: action2,
      method,
      encType,
      formData,
      body
    } = getFormSubmissionInfo(target, basename2);
    if (options.navigate === false) {
      let key = options.fetcherKey || getUniqueFetcherId();
      router.fetch(key, currentRouteId, options.action || action2, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        flushSync: options.flushSync
      });
    } else {
      router.navigate(options.action || action2, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        replace: options.replace,
        state: options.state,
        fromRouteId: currentRouteId,
        flushSync: options.flushSync,
        viewTransition: options.viewTransition
      });
    }
  }, [router, basename2, currentRouteId]);
}
function useFormAction(action2, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    basename: basename2
  } = reactExports.useContext(NavigationContext);
  let routeContext = reactExports.useContext(RouteContext);
  !routeContext ? invariant$2(false) : void 0;
  let [match] = routeContext.matches.slice(-1);
  let path = _extends$2({}, useResolvedPath(action2 ? action2 : ".", {
    relative
  }));
  let location = useLocation();
  if (action2 == null) {
    path.search = location.search;
    let params = new URLSearchParams(path.search);
    let indexValues = params.getAll("index");
    let hasNakedIndexParam = indexValues.some((v5) => v5 === "");
    if (hasNakedIndexParam) {
      params.delete("index");
      indexValues.filter((v5) => v5).forEach((v5) => params.append("index", v5));
      let qs = params.toString();
      path.search = qs ? "?" + qs : "";
    }
  }
  if ((!action2 || action2 === ".") && match.route.index) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }
  if (basename2 !== "/") {
    path.pathname = path.pathname === "/" ? basename2 : joinPaths([basename2, path.pathname]);
  }
  return createPath(path);
}
function useFetcher$1(_temp3) {
  var _route$matches;
  let {
    key
  } = _temp3 === void 0 ? {} : _temp3;
  let {
    router
  } = useDataRouterContext$1(DataRouterHook.UseFetcher);
  let state = useDataRouterState(DataRouterStateHook.UseFetcher);
  let fetcherData = reactExports.useContext(FetchersContext);
  let route = reactExports.useContext(RouteContext);
  let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
  !fetcherData ? invariant$2(false) : void 0;
  !route ? invariant$2(false) : void 0;
  !(routeId != null) ? invariant$2(false) : void 0;
  let defaultKey = useIdImpl ? useIdImpl() : "";
  let [fetcherKey, setFetcherKey] = reactExports.useState(key || defaultKey);
  if (key && key !== fetcherKey) {
    setFetcherKey(key);
  } else if (!fetcherKey) {
    setFetcherKey(getUniqueFetcherId());
  }
  reactExports.useEffect(() => {
    router.getFetcher(fetcherKey);
    return () => {
      router.deleteFetcher(fetcherKey);
    };
  }, [router, fetcherKey]);
  let load = reactExports.useCallback((href, opts) => {
    !routeId ? invariant$2(false) : void 0;
    router.fetch(fetcherKey, routeId, href, opts);
  }, [fetcherKey, routeId, router]);
  let submitImpl = useSubmit();
  let submit = reactExports.useCallback((target, opts) => {
    submitImpl(target, _extends$2({}, opts, {
      navigate: false,
      fetcherKey
    }));
  }, [fetcherKey, submitImpl]);
  let FetcherForm = reactExports.useMemo(() => {
    let FetcherForm2 = /* @__PURE__ */ reactExports.forwardRef((props, ref) => {
      return /* @__PURE__ */ reactExports.createElement(Form$1, _extends$2({}, props, {
        navigate: false,
        fetcherKey,
        ref
      }));
    });
    return FetcherForm2;
  }, [fetcherKey]);
  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  let data = fetcherData.get(fetcherKey);
  let fetcherWithComponents = reactExports.useMemo(() => _extends$2({
    Form: FetcherForm,
    submit,
    load
  }, fetcher, {
    data
  }), [FetcherForm, submit, load, fetcher, data]);
  return fetcherWithComponents;
}
function useFetchers() {
  let state = useDataRouterState(DataRouterStateHook.UseFetchers);
  return Array.from(state.fetchers.entries()).map((_ref11) => {
    let [key, fetcher] = _ref11;
    return _extends$2({}, fetcher, {
      key
    });
  });
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
function useScrollRestoration(_temp4) {
  let {
    getKey,
    storageKey
  } = _temp4 === void 0 ? {} : _temp4;
  let {
    router
  } = useDataRouterContext$1(DataRouterHook.UseScrollRestoration);
  let {
    restoreScrollPosition,
    preventScrollReset
  } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
  let {
    basename: basename2
  } = reactExports.useContext(NavigationContext);
  let location = useLocation();
  let matches = useMatches$1();
  let navigation2 = useNavigation();
  reactExports.useEffect(() => {
    window.history.scrollRestoration = "manual";
    return () => {
      window.history.scrollRestoration = "auto";
    };
  }, []);
  usePageHide(reactExports.useCallback(() => {
    if (navigation2.state === "idle") {
      let key = (getKey ? getKey(location, matches) : null) || location.key;
      savedScrollPositions[key] = window.scrollY;
    }
    try {
      sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
    } catch (error2) {
    }
    window.history.scrollRestoration = "auto";
  }, [storageKey, getKey, navigation2.state, location, matches]));
  if (typeof document !== "undefined") {
    reactExports.useLayoutEffect(() => {
      try {
        let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
        if (sessionPositions) {
          savedScrollPositions = JSON.parse(sessionPositions);
        }
      } catch (e2) {
      }
    }, [storageKey]);
    reactExports.useLayoutEffect(() => {
      let getKeyWithoutBasename = getKey && basename2 !== "/" ? (location2, matches2) => getKey(
        // Strip the basename to match useLocation()
        _extends$2({}, location2, {
          pathname: stripBasename(location2.pathname, basename2) || location2.pathname
        }),
        matches2
      ) : getKey;
      let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
      return () => disableScrollRestoration && disableScrollRestoration();
    }, [router, basename2, getKey]);
    reactExports.useLayoutEffect(() => {
      if (restoreScrollPosition === false) {
        return;
      }
      if (typeof restoreScrollPosition === "number") {
        window.scrollTo(0, restoreScrollPosition);
        return;
      }
      if (location.hash) {
        let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
        if (el) {
          el.scrollIntoView();
          return;
        }
      }
      if (preventScrollReset === true) {
        return;
      }
      window.scrollTo(0, 0);
    }, [location, restoreScrollPosition, preventScrollReset]);
  }
}
function usePageHide(callback, options) {
  let {
    capture
  } = {};
  reactExports.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : void 0;
    window.addEventListener("pagehide", callback, opts);
    return () => {
      window.removeEventListener("pagehide", callback, opts);
    };
  }, [callback, capture]);
}
function useViewTransitionState(to, opts) {
  if (opts === void 0) {
    opts = {};
  }
  let vtContext = reactExports.useContext(ViewTransitionContext);
  !(vtContext != null) ? invariant$2(false) : void 0;
  let {
    basename: basename2
  } = useDataRouterContext$1(DataRouterHook.useViewTransitionState);
  let path = useResolvedPath(to, {
    relative: opts.relative
  });
  if (!vtContext.isTransitioning) {
    return false;
  }
  let currentPath = stripBasename(vtContext.currentLocation.pathname, basename2) || vtContext.currentLocation.pathname;
  let nextPath = stripBasename(vtContext.nextLocation.pathname, basename2) || vtContext.nextLocation.pathname;
  return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
}
var cookie = {};
/*!
 * cookie
 * Copyright(c) 2012-2014 Roman Shtylman
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */
var hasRequiredCookie;
function requireCookie() {
  if (hasRequiredCookie) return cookie;
  hasRequiredCookie = 1;
  cookie.parse = parse;
  cookie.serialize = serialize;
  var __toString = Object.prototype.toString;
  var __hasOwnProperty = Object.prototype.hasOwnProperty;
  var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
  var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
  var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
  function parse(str, opt) {
    if (typeof str !== "string") {
      throw new TypeError("argument str must be a string");
    }
    var obj = {};
    var len = str.length;
    if (len < 2) return obj;
    var dec = opt && opt.decode || decode;
    var index = 0;
    var eqIdx = 0;
    var endIdx = 0;
    do {
      eqIdx = str.indexOf("=", index);
      if (eqIdx === -1) break;
      endIdx = str.indexOf(";", index);
      if (endIdx === -1) {
        endIdx = len;
      } else if (eqIdx > endIdx) {
        index = str.lastIndexOf(";", eqIdx - 1) + 1;
        continue;
      }
      var keyStartIdx = startIndex(str, index, eqIdx);
      var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
      var key = str.slice(keyStartIdx, keyEndIdx);
      if (!__hasOwnProperty.call(obj, key)) {
        var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
        var valEndIdx = endIndex(str, endIdx, valStartIdx);
        if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) {
          valStartIdx++;
          valEndIdx--;
        }
        var val = str.slice(valStartIdx, valEndIdx);
        obj[key] = tryDecode(val, dec);
      }
      index = endIdx + 1;
    } while (index < len);
    return obj;
  }
  function startIndex(str, index, max2) {
    do {
      var code = str.charCodeAt(index);
      if (code !== 32 && code !== 9) return index;
    } while (++index < max2);
    return max2;
  }
  function endIndex(str, index, min) {
    while (index > min) {
      var code = str.charCodeAt(--index);
      if (code !== 32 && code !== 9) return index + 1;
    }
    return min;
  }
  function serialize(name, val, opt) {
    var enc = opt && opt.encode || encodeURIComponent;
    if (typeof enc !== "function") {
      throw new TypeError("option encode is invalid");
    }
    if (!cookieNameRegExp.test(name)) {
      throw new TypeError("argument name is invalid");
    }
    var value = enc(val);
    if (!cookieValueRegExp.test(value)) {
      throw new TypeError("argument val is invalid");
    }
    var str = name + "=" + value;
    if (!opt) return str;
    if (null != opt.maxAge) {
      var maxAge = Math.floor(opt.maxAge);
      if (!isFinite(maxAge)) {
        throw new TypeError("option maxAge is invalid");
      }
      str += "; Max-Age=" + maxAge;
    }
    if (opt.domain) {
      if (!domainValueRegExp.test(opt.domain)) {
        throw new TypeError("option domain is invalid");
      }
      str += "; Domain=" + opt.domain;
    }
    if (opt.path) {
      if (!pathValueRegExp.test(opt.path)) {
        throw new TypeError("option path is invalid");
      }
      str += "; Path=" + opt.path;
    }
    if (opt.expires) {
      var expires = opt.expires;
      if (!isDate(expires) || isNaN(expires.valueOf())) {
        throw new TypeError("option expires is invalid");
      }
      str += "; Expires=" + expires.toUTCString();
    }
    if (opt.httpOnly) {
      str += "; HttpOnly";
    }
    if (opt.secure) {
      str += "; Secure";
    }
    if (opt.partitioned) {
      str += "; Partitioned";
    }
    if (opt.priority) {
      var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
      switch (priority) {
        case "low":
          str += "; Priority=Low";
          break;
        case "medium":
          str += "; Priority=Medium";
          break;
        case "high":
          str += "; Priority=High";
          break;
        default:
          throw new TypeError("option priority is invalid");
      }
    }
    if (opt.sameSite) {
      var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
      switch (sameSite) {
        case true:
          str += "; SameSite=Strict";
          break;
        case "lax":
          str += "; SameSite=Lax";
          break;
        case "strict":
          str += "; SameSite=Strict";
          break;
        case "none":
          str += "; SameSite=None";
          break;
        default:
          throw new TypeError("option sameSite is invalid");
      }
    }
    return str;
  }
  function decode(str) {
    return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
  }
  function isDate(val) {
    return __toString.call(val) === "[object Date]";
  }
  function tryDecode(str, decode2) {
    try {
      return decode2(str);
    } catch (e2) {
      return str;
    }
  }
  return cookie;
}
var cookieExports = requireCookie();
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const alreadyWarned = {};
function warnOnce$2(condition, message) {
  if (!condition && !alreadyWarned[message]) {
    alreadyWarned[message] = true;
    console.warn(message);
  }
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const createCookieFactory = ({
  sign: sign2,
  unsign
}) => (name, cookieOptions = {}) => {
  let {
    secrets = [],
    ...options
  } = {
    path: "/",
    sameSite: "lax",
    ...cookieOptions
  };
  warnOnceAboutExpiresCookie(name, options.expires);
  return {
    get name() {
      return name;
    },
    get isSigned() {
      return secrets.length > 0;
    },
    get expires() {
      return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
    },
    async parse(cookieHeader, parseOptions) {
      if (!cookieHeader) return null;
      let cookies = cookieExports.parse(cookieHeader, {
        ...options,
        ...parseOptions
      });
      return name in cookies ? cookies[name] === "" ? "" : await decodeCookieValue(unsign, cookies[name], secrets) : null;
    },
    async serialize(value, serializeOptions) {
      return cookieExports.serialize(name, value === "" ? "" : await encodeCookieValue(sign2, value, secrets), {
        ...options,
        ...serializeOptions
      });
    }
  };
};
const isCookie = (object) => {
  return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
};
async function encodeCookieValue(sign2, value, secrets) {
  let encoded = encodeData(value);
  if (secrets.length > 0) {
    encoded = await sign2(encoded, secrets[0]);
  }
  return encoded;
}
async function decodeCookieValue(unsign, value, secrets) {
  if (secrets.length > 0) {
    for (let secret of secrets) {
      let unsignedValue = await unsign(value, secret);
      if (unsignedValue !== false) {
        return decodeData(unsignedValue);
      }
    }
    return null;
  }
  return decodeData(value);
}
function encodeData(value) {
  return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
}
function decodeData(value) {
  try {
    return JSON.parse(decodeURIComponent(myEscape(atob(value))));
  } catch (error2) {
    return {};
  }
}
function myEscape(value) {
  let str = value.toString();
  let result = "";
  let index = 0;
  let chr, code;
  while (index < str.length) {
    chr = str.charAt(index++);
    if (/[\w*+\-./@]/.exec(chr)) {
      result += chr;
    } else {
      code = chr.charCodeAt(0);
      if (code < 256) {
        result += "%" + hex(code, 2);
      } else {
        result += "%u" + hex(code, 4).toUpperCase();
      }
    }
  }
  return result;
}
function hex(code, length) {
  let result = code.toString(16);
  while (result.length < length) result = "0" + result;
  return result;
}
function myUnescape(value) {
  let str = value.toString();
  let result = "";
  let index = 0;
  let chr, part;
  while (index < str.length) {
    chr = str.charAt(index++);
    if (chr === "%") {
      if (str.charAt(index) === "u") {
        part = str.slice(index + 1, index + 5);
        if (/^[\da-f]{4}$/i.exec(part)) {
          result += String.fromCharCode(parseInt(part, 16));
          index += 5;
          continue;
        }
      } else {
        part = str.slice(index, index + 2);
        if (/^[\da-f]{2}$/i.exec(part)) {
          result += String.fromCharCode(parseInt(part, 16));
          index += 2;
          continue;
        }
      }
    }
    result += chr;
  }
  return result;
}
function warnOnceAboutExpiresCookie(name, expires) {
  warnOnce$2(!expires, `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`);
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
let ServerMode = /* @__PURE__ */ (function(ServerMode2) {
  ServerMode2["Development"] = "development";
  ServerMode2["Production"] = "production";
  ServerMode2["Test"] = "test";
  return ServerMode2;
})({});
function isServerMode(value) {
  return value === ServerMode.Development || value === ServerMode.Production || value === ServerMode.Test;
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function sanitizeError(error2, serverMode) {
  if (error2 instanceof Error && serverMode !== ServerMode.Development) {
    let sanitized = new Error("Unexpected Server Error");
    sanitized.stack = void 0;
    return sanitized;
  }
  return error2;
}
function sanitizeErrors(errors, serverMode) {
  return Object.entries(errors).reduce((acc, [routeId, error2]) => {
    return Object.assign(acc, {
      [routeId]: sanitizeError(error2, serverMode)
    });
  }, {});
}
function serializeError(error2, serverMode) {
  let sanitized = sanitizeError(error2, serverMode);
  return {
    message: sanitized.message,
    stack: sanitized.stack
  };
}
function serializeErrors$1(errors, serverMode) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    if (isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      let sanitized = sanitizeError(val, serverMode);
      serialized[key] = {
        message: sanitized.message,
        stack: sanitized.stack,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.  This will only apply
        // in dev mode since all production errors are sanitized to normal
        // Error instances
        ...sanitized.name !== "Error" ? {
          __subType: sanitized.name
        } : {}
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const json2 = (data, init = {}) => {
  return json$1(data, init);
};
const defer2 = (data, init = {}) => {
  return defer$1(data, init);
};
const redirect2 = (url, init = 302) => {
  return redirect$1(url, init);
};
function isDeferredData(value) {
  let deferred = value;
  return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
}
function isResponse(value) {
  return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
}
const redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
function isRedirectStatusCode(statusCode) {
  return redirectStatusCodes.has(statusCode);
}
function isRedirectResponse(response) {
  return isRedirectStatusCode(response.status);
}
function isTrackedPromise(value) {
  return value != null && typeof value.then === "function" && value._tracked === true;
}
const DEFERRED_VALUE_PLACEHOLDER_PREFIX = "__deferred_promise:";
function createDeferredReadableStream(deferredData, signal, serverMode) {
  let encoder = new TextEncoder();
  let stream = new ReadableStream({
    async start(controller) {
      let criticalData = {};
      let preresolvedKeys = [];
      for (let [key, value] of Object.entries(deferredData.data)) {
        if (isTrackedPromise(value)) {
          criticalData[key] = `${DEFERRED_VALUE_PLACEHOLDER_PREFIX}${key}`;
          if (typeof value._data !== "undefined" || typeof value._error !== "undefined") {
            preresolvedKeys.push(key);
          }
        } else {
          criticalData[key] = value;
        }
      }
      controller.enqueue(encoder.encode(JSON.stringify(criticalData) + "\n\n"));
      for (let preresolvedKey of preresolvedKeys) {
        enqueueTrackedPromise(controller, encoder, preresolvedKey, deferredData.data[preresolvedKey], serverMode);
      }
      let unsubscribe = deferredData.subscribe((aborted, settledKey) => {
        if (settledKey) {
          enqueueTrackedPromise(controller, encoder, settledKey, deferredData.data[settledKey], serverMode);
        }
      });
      await deferredData.resolveData(signal);
      unsubscribe();
      controller.close();
    }
  });
  return stream;
}
function enqueueTrackedPromise(controller, encoder, settledKey, promise, serverMode) {
  if ("_error" in promise) {
    controller.enqueue(encoder.encode("error:" + JSON.stringify({
      [settledKey]: promise._error instanceof Error ? serializeError(promise._error, serverMode) : promise._error
    }) + "\n\n"));
  } else {
    controller.enqueue(encoder.encode("data:" + JSON.stringify({
      [settledKey]: promise._data ?? null
    }) + "\n\n"));
  }
}
var HOLE = -1;
var NAN = -2;
var NEGATIVE_INFINITY = -3;
var NEGATIVE_ZERO = -4;
var NULL = -5;
var POSITIVE_INFINITY = -6;
var UNDEFINED = -7;
var TYPE_BIGINT = "B";
var TYPE_DATE = "D";
var TYPE_ERROR = "E";
var TYPE_MAP = "M";
var TYPE_NULL_OBJECT = "N";
var TYPE_PROMISE = "P";
var TYPE_REGEXP = "R";
var TYPE_SET = "S";
var TYPE_SYMBOL = "Y";
var TYPE_URL = "U";
var TYPE_PREVIOUS_RESOLVED = "Z";
function flatten$1(input) {
  const { indices } = this;
  const existing = indices.get(input);
  if (existing)
    return [existing];
  if (input === void 0)
    return UNDEFINED;
  if (input === null)
    return NULL;
  if (Number.isNaN(input))
    return NAN;
  if (input === Number.POSITIVE_INFINITY)
    return POSITIVE_INFINITY;
  if (input === Number.NEGATIVE_INFINITY)
    return NEGATIVE_INFINITY;
  if (input === 0 && 1 / input < 0)
    return NEGATIVE_ZERO;
  const index = this.index++;
  indices.set(input, index);
  stringify.call(this, input, index);
  return index;
}
function stringify(input, index) {
  const { deferred, plugins, postPlugins } = this;
  const str = this.stringified;
  const stack = [[input, index]];
  while (stack.length > 0) {
    const [input2, index2] = stack.pop();
    const partsForObj = (obj) => Object.keys(obj).map((k2) => `"_${flatten$1.call(this, k2)}":${flatten$1.call(this, obj[k2])}`).join(",");
    let error2 = null;
    switch (typeof input2) {
      case "boolean":
      case "number":
      case "string":
        str[index2] = JSON.stringify(input2);
        break;
      case "bigint":
        str[index2] = `["${TYPE_BIGINT}","${input2}"]`;
        break;
      case "symbol": {
        const keyFor = Symbol.keyFor(input2);
        if (!keyFor) {
          error2 = new Error(
            "Cannot encode symbol unless created with Symbol.for()"
          );
        } else {
          str[index2] = `["${TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`;
        }
        break;
      }
      case "object": {
        if (!input2) {
          str[index2] = `${NULL}`;
          break;
        }
        const isArray2 = Array.isArray(input2);
        let pluginHandled = false;
        if (!isArray2 && plugins) {
          for (const plugin of plugins) {
            const pluginResult = plugin(input2);
            if (Array.isArray(pluginResult)) {
              pluginHandled = true;
              const [pluginIdentifier, ...rest] = pluginResult;
              str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
              if (rest.length > 0) {
                str[index2] += `,${rest.map((v5) => flatten$1.call(this, v5)).join(",")}`;
              }
              str[index2] += "]";
              break;
            }
          }
        }
        if (!pluginHandled) {
          let result = isArray2 ? "[" : "{";
          if (isArray2) {
            for (let i2 = 0; i2 < input2.length; i2++)
              result += (i2 ? "," : "") + (i2 in input2 ? flatten$1.call(this, input2[i2]) : HOLE);
            str[index2] = `${result}]`;
          } else if (input2 instanceof Date) {
            str[index2] = `["${TYPE_DATE}",${input2.getTime()}]`;
          } else if (input2 instanceof URL) {
            str[index2] = `["${TYPE_URL}",${JSON.stringify(input2.href)}]`;
          } else if (input2 instanceof RegExp) {
            str[index2] = `["${TYPE_REGEXP}",${JSON.stringify(
              input2.source
            )},${JSON.stringify(input2.flags)}]`;
          } else if (input2 instanceof Set) {
            if (input2.size > 0) {
              str[index2] = `["${TYPE_SET}",${[...input2].map((val) => flatten$1.call(this, val)).join(",")}]`;
            } else {
              str[index2] = `["${TYPE_SET}"]`;
            }
          } else if (input2 instanceof Map) {
            if (input2.size > 0) {
              str[index2] = `["${TYPE_MAP}",${[...input2].flatMap(([k2, v5]) => [
                flatten$1.call(this, k2),
                flatten$1.call(this, v5)
              ]).join(",")}]`;
            } else {
              str[index2] = `["${TYPE_MAP}"]`;
            }
          } else if (input2 instanceof Promise) {
            str[index2] = `["${TYPE_PROMISE}",${index2}]`;
            deferred[index2] = input2;
          } else if (input2 instanceof Error) {
            str[index2] = `["${TYPE_ERROR}",${JSON.stringify(input2.message)}`;
            if (input2.name !== "Error") {
              str[index2] += `,${JSON.stringify(input2.name)}`;
            }
            str[index2] += "]";
          } else if (Object.getPrototypeOf(input2) === null) {
            str[index2] = `["${TYPE_NULL_OBJECT}",{${partsForObj(input2)}}]`;
          } else if (isPlainObject(input2)) {
            str[index2] = `{${partsForObj(input2)}}`;
          } else {
            error2 = new Error("Cannot encode object with prototype");
          }
        }
        break;
      }
      default: {
        const isArray2 = Array.isArray(input2);
        let pluginHandled = false;
        if (!isArray2 && plugins) {
          for (const plugin of plugins) {
            const pluginResult = plugin(input2);
            if (Array.isArray(pluginResult)) {
              pluginHandled = true;
              const [pluginIdentifier, ...rest] = pluginResult;
              str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
              if (rest.length > 0) {
                str[index2] += `,${rest.map((v5) => flatten$1.call(this, v5)).join(",")}`;
              }
              str[index2] += "]";
              break;
            }
          }
        }
        if (!pluginHandled) {
          error2 = new Error("Cannot encode function or unexpected type");
        }
      }
    }
    if (error2) {
      let pluginHandled = false;
      if (postPlugins) {
        for (const plugin of postPlugins) {
          const pluginResult = plugin(input2);
          if (Array.isArray(pluginResult)) {
            pluginHandled = true;
            const [pluginIdentifier, ...rest] = pluginResult;
            str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
            if (rest.length > 0) {
              str[index2] += `,${rest.map((v5) => flatten$1.call(this, v5)).join(",")}`;
            }
            str[index2] += "]";
            break;
          }
        }
      }
      if (!pluginHandled) {
        throw error2;
      }
    }
  }
}
var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function isPlainObject(thing) {
  const proto = Object.getPrototypeOf(thing);
  return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
}
function encode(input, options) {
  const { plugins, postPlugins, signal } = options ?? {};
  const encoder = {
    deferred: {},
    index: 0,
    indices: /* @__PURE__ */ new Map(),
    stringified: [],
    plugins,
    postPlugins,
    signal
  };
  const textEncoder = new TextEncoder();
  let lastSentIndex = 0;
  const readable = new ReadableStream({
    async start(controller) {
      const id = flatten$1.call(encoder, input);
      if (Array.isArray(id)) {
        throw new Error("This should never happen");
      }
      if (id < 0) {
        controller.enqueue(textEncoder.encode(`${id}
`));
      } else {
        controller.enqueue(
          textEncoder.encode(`[${encoder.stringified.join(",")}]
`)
        );
        lastSentIndex = encoder.stringified.length - 1;
      }
      const seenPromises = /* @__PURE__ */ new WeakSet();
      if (Object.keys(encoder.deferred).length) {
        let raceDone;
        const racePromise = new Promise((resolve2, reject) => {
          raceDone = resolve2;
          if (signal) {
            const rejectPromise = () => reject(signal.reason || new Error("Signal was aborted."));
            if (signal.aborted) {
              rejectPromise();
            } else {
              signal.addEventListener("abort", (event) => {
                rejectPromise();
              });
            }
          }
        });
        while (Object.keys(encoder.deferred).length > 0) {
          for (const [deferredId, deferred] of Object.entries(
            encoder.deferred
          )) {
            if (seenPromises.has(deferred))
              continue;
            seenPromises.add(
              // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
              encoder.deferred[Number(deferredId)] = Promise.race([
                racePromise,
                deferred
              ]).then(
                (resolved) => {
                  const id2 = flatten$1.call(encoder, resolved);
                  if (Array.isArray(id2)) {
                    controller.enqueue(
                      textEncoder.encode(
                        `${TYPE_PROMISE}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
`
                      )
                    );
                    encoder.index++;
                    lastSentIndex++;
                  } else if (id2 < 0) {
                    controller.enqueue(
                      textEncoder.encode(
                        `${TYPE_PROMISE}${deferredId}:${id2}
`
                      )
                    );
                  } else {
                    const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
                    controller.enqueue(
                      textEncoder.encode(
                        `${TYPE_PROMISE}${deferredId}:[${values}]
`
                      )
                    );
                    lastSentIndex = encoder.stringified.length - 1;
                  }
                },
                (reason) => {
                  if (!reason || typeof reason !== "object" || !(reason instanceof Error)) {
                    reason = new Error("An unknown error occurred");
                  }
                  const id2 = flatten$1.call(encoder, reason);
                  if (Array.isArray(id2)) {
                    controller.enqueue(
                      textEncoder.encode(
                        `${TYPE_ERROR}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
`
                      )
                    );
                    encoder.index++;
                    lastSentIndex++;
                  } else if (id2 < 0) {
                    controller.enqueue(
                      textEncoder.encode(`${TYPE_ERROR}${deferredId}:${id2}
`)
                    );
                  } else {
                    const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
                    controller.enqueue(
                      textEncoder.encode(
                        `${TYPE_ERROR}${deferredId}:[${values}]
`
                      )
                    );
                    lastSentIndex = encoder.stringified.length - 1;
                  }
                }
              ).finally(() => {
                delete encoder.deferred[Number(deferredId)];
              })
            );
          }
          await Promise.race(Object.values(encoder.deferred));
        }
        raceDone();
      }
      await Promise.all(Object.values(encoder.deferred));
      controller.close();
    }
  });
  return readable;
}
var setCookie = { exports: {} };
var hasRequiredSetCookie;
function requireSetCookie() {
  if (hasRequiredSetCookie) return setCookie.exports;
  hasRequiredSetCookie = 1;
  var defaultParseOptions = {
    decodeValues: true,
    map: false,
    silent: false
  };
  function isForbiddenKey(key) {
    return typeof key !== "string" || key in {};
  }
  function createNullObj() {
    return /* @__PURE__ */ Object.create(null);
  }
  function isNonEmptyString2(str) {
    return typeof str === "string" && !!str.trim();
  }
  function parseString(setCookieValue, options) {
    var parts = setCookieValue.split(";").filter(isNonEmptyString2);
    var nameValuePairStr = parts.shift();
    var parsed = parseNameValuePair(nameValuePairStr);
    var name = parsed.name;
    var value = parsed.value;
    options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
    if (isForbiddenKey(name)) {
      return null;
    }
    try {
      value = options.decodeValues ? decodeURIComponent(value) : value;
    } catch (e2) {
      console.error(
        "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
        e2
      );
    }
    var cookie2 = createNullObj();
    cookie2.name = name;
    cookie2.value = value;
    parts.forEach(function(part) {
      var sides = part.split("=");
      var key = sides.shift().trimLeft().toLowerCase();
      if (isForbiddenKey(key)) {
        return;
      }
      var value2 = sides.join("=");
      if (key === "expires") {
        cookie2.expires = new Date(value2);
      } else if (key === "max-age") {
        var n2 = parseInt(value2, 10);
        if (!Number.isNaN(n2)) cookie2.maxAge = n2;
      } else if (key === "secure") {
        cookie2.secure = true;
      } else if (key === "httponly") {
        cookie2.httpOnly = true;
      } else if (key === "samesite") {
        cookie2.sameSite = value2;
      } else if (key === "partitioned") {
        cookie2.partitioned = true;
      } else if (key) {
        cookie2[key] = value2;
      }
    });
    return cookie2;
  }
  function parseNameValuePair(nameValuePairStr) {
    var name = "";
    var value = "";
    var nameValueArr = nameValuePairStr.split("=");
    if (nameValueArr.length > 1) {
      name = nameValueArr.shift();
      value = nameValueArr.join("=");
    } else {
      value = nameValuePairStr;
    }
    return { name, value };
  }
  function parse(input, options) {
    options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
    if (!input) {
      if (!options.map) {
        return [];
      } else {
        return createNullObj();
      }
    }
    if (input.headers) {
      if (typeof input.headers.getSetCookie === "function") {
        input = input.headers.getSetCookie();
      } else if (input.headers["set-cookie"]) {
        input = input.headers["set-cookie"];
      } else {
        var sch = input.headers[Object.keys(input.headers).find(function(key) {
          return key.toLowerCase() === "set-cookie";
        })];
        if (!sch && input.headers.cookie && !options.silent) {
          console.warn(
            "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
          );
        }
        input = sch;
      }
    }
    if (!Array.isArray(input)) {
      input = [input];
    }
    if (!options.map) {
      return input.filter(isNonEmptyString2).map(function(str) {
        return parseString(str, options);
      }).filter(Boolean);
    } else {
      var cookies = createNullObj();
      return input.filter(isNonEmptyString2).reduce(function(cookies2, str) {
        var cookie2 = parseString(str, options);
        if (cookie2 && !isForbiddenKey(cookie2.name)) {
          cookies2[cookie2.name] = cookie2;
        }
        return cookies2;
      }, cookies);
    }
  }
  function splitCookiesString(cookiesString) {
    if (Array.isArray(cookiesString)) {
      return cookiesString;
    }
    if (typeof cookiesString !== "string") {
      return [];
    }
    var cookiesStrings = [];
    var pos = 0;
    var start;
    var ch;
    var lastComma;
    var nextStart;
    var cookiesSeparatorFound;
    function skipWhitespace() {
      while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
        pos += 1;
      }
      return pos < cookiesString.length;
    }
    function notSpecialChar() {
      ch = cookiesString.charAt(pos);
      return ch !== "=" && ch !== ";" && ch !== ",";
    }
    while (pos < cookiesString.length) {
      start = pos;
      cookiesSeparatorFound = false;
      while (skipWhitespace()) {
        ch = cookiesString.charAt(pos);
        if (ch === ",") {
          lastComma = pos;
          pos += 1;
          skipWhitespace();
          nextStart = pos;
          while (pos < cookiesString.length && notSpecialChar()) {
            pos += 1;
          }
          if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
            cookiesSeparatorFound = true;
            pos = nextStart;
            cookiesStrings.push(cookiesString.substring(start, lastComma));
            start = pos;
          } else {
            pos = lastComma + 1;
          }
        } else {
          pos += 1;
        }
      }
      if (!cookiesSeparatorFound || pos >= cookiesString.length) {
        cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
      }
    }
    return cookiesStrings;
  }
  setCookie.exports = parse;
  setCookie.exports.parse = parse;
  setCookie.exports.parseString = parseString;
  setCookie.exports.splitCookiesString = splitCookiesString;
  return setCookie.exports;
}
var setCookieExports = /* @__PURE__ */ requireSetCookie();
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function getDocumentHeaders(build, context2) {
  let boundaryIdx = context2.errors ? context2.matches.findIndex((m2) => context2.errors[m2.route.id]) : -1;
  let matches = boundaryIdx >= 0 ? context2.matches.slice(0, boundaryIdx + 1) : context2.matches;
  let errorHeaders;
  if (boundaryIdx >= 0) {
    let {
      actionHeaders,
      actionData,
      loaderHeaders,
      loaderData
    } = context2;
    context2.matches.slice(boundaryIdx).some((match) => {
      let id = match.route.id;
      if (actionHeaders[id] && (!actionData || actionData[id] === void 0)) {
        errorHeaders = actionHeaders[id];
      } else if (loaderHeaders[id] && loaderData[id] === void 0) {
        errorHeaders = loaderHeaders[id];
      }
      return errorHeaders != null;
    });
  }
  return matches.reduce((parentHeaders, match, idx) => {
    let {
      id
    } = match.route;
    let routeModule = build.routes[id].module;
    let loaderHeaders = context2.loaderHeaders[id] || new Headers();
    let actionHeaders = context2.actionHeaders[id] || new Headers();
    let includeErrorHeaders = errorHeaders != void 0 && idx === matches.length - 1;
    let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
    if (routeModule.headers == null) {
      let headers2 = new Headers(parentHeaders);
      if (includeErrorCookies) {
        prependCookies(errorHeaders, headers2);
      }
      prependCookies(actionHeaders, headers2);
      prependCookies(loaderHeaders, headers2);
      return headers2;
    }
    let headers = new Headers(routeModule.headers ? typeof routeModule.headers === "function" ? routeModule.headers({
      loaderHeaders,
      parentHeaders,
      actionHeaders,
      errorHeaders: includeErrorHeaders ? errorHeaders : void 0
    }) : routeModule.headers : void 0);
    if (includeErrorCookies) {
      prependCookies(errorHeaders, headers);
    }
    prependCookies(actionHeaders, headers);
    prependCookies(loaderHeaders, headers);
    prependCookies(parentHeaders, headers);
    return headers;
  }, new Headers());
}
function prependCookies(parentHeaders, childHeaders) {
  let parentSetCookieString = parentHeaders.get("Set-Cookie");
  if (parentSetCookieString) {
    var _childHeaders$getSetC;
    let cookies = setCookieExports.splitCookiesString(parentSetCookieString);
    let childCookies = new Set((_childHeaders$getSetC = childHeaders.getSetCookie) === null || _childHeaders$getSetC === void 0 ? void 0 : _childHeaders$getSetC.call(childHeaders));
    cookies.forEach((cookie2) => {
      if (!childCookies.has(cookie2)) {
        childHeaders.append("Set-Cookie", cookie2);
      }
    });
  }
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function throwIfPotentialCSRFAttack(headers) {
  let originHeader = headers.get("origin");
  let originDomain = typeof originHeader === "string" && originHeader !== "null" ? new URL(originHeader).host : originHeader;
  let host = parseHostHeader(headers);
  if (originDomain && (!host || originDomain !== host.value)) {
    if (host) {
      throw new Error(`${host.type} header does not match \`origin\` header from a forwarded action request. Aborting the action.`);
    } else {
      throw new Error("`x-forwarded-host` or `host` headers are not provided. One of these is needed to compare the `origin` header from a forwarded action request. Aborting the action.");
    }
  }
}
function parseHostHeader(headers) {
  var _forwardedHostHeader$;
  let forwardedHostHeader = headers.get("x-forwarded-host");
  let forwardedHostValue = forwardedHostHeader === null || forwardedHostHeader === void 0 ? void 0 : (_forwardedHostHeader$ = forwardedHostHeader.split(",")[0]) === null || _forwardedHostHeader$ === void 0 ? void 0 : _forwardedHostHeader$.trim();
  let hostHeader = headers.get("host");
  return forwardedHostValue ? {
    type: "x-forwarded-host",
    value: forwardedHostValue
  } : hostHeader ? {
    type: "host",
    value: hostHeader
  } : void 0;
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
const SINGLE_FETCH_REDIRECT_STATUS = 202;
function getSingleFetchDataStrategy({
  isActionDataRequest,
  loadRouteIds
} = {}) {
  return async ({
    request,
    matches
  }) => {
    if (isActionDataRequest && request.method === "GET") {
      return {};
    }
    let matchesToLoad = loadRouteIds ? matches.filter((m2) => loadRouteIds.includes(m2.route.id)) : matches;
    let results = await Promise.all(matchesToLoad.map((match) => match.resolve()));
    return results.reduce((acc, result, i2) => Object.assign(acc, {
      [matchesToLoad[i2].route.id]: result
    }), {});
  };
}
async function singleFetchAction(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) {
  try {
    throwIfPotentialCSRFAttack(request.headers);
    let handlerRequest = new Request(handlerUrl, {
      method: request.method,
      body: request.body,
      headers: request.headers,
      signal: request.signal,
      ...request.body ? {
        duplex: "half"
      } : void 0
    });
    let result = await staticHandler.query(handlerRequest, {
      requestContext: loadContext,
      skipLoaderErrorBubbling: true,
      dataStrategy: getSingleFetchDataStrategy({
        isActionDataRequest: true
      })
    });
    if (isResponse(result)) {
      return {
        result: getSingleFetchRedirect(result.status, result.headers, build.basename),
        headers: result.headers,
        status: SINGLE_FETCH_REDIRECT_STATUS
      };
    }
    let context2 = result;
    let headers = getDocumentHeaders(build, context2);
    if (isRedirectStatusCode(context2.statusCode) && headers.has("Location")) {
      return {
        result: getSingleFetchRedirect(context2.statusCode, headers, build.basename),
        headers,
        status: SINGLE_FETCH_REDIRECT_STATUS
      };
    }
    if (context2.errors) {
      Object.values(context2.errors).forEach((err) => {
        if (!isRouteErrorResponse(err) || err.error) {
          handleError(err);
        }
      });
      context2.errors = sanitizeErrors(context2.errors, serverMode);
    }
    let singleFetchResult;
    if (context2.errors) {
      singleFetchResult = {
        error: Object.values(context2.errors)[0]
      };
    } else {
      singleFetchResult = {
        data: Object.values(context2.actionData || {})[0]
      };
    }
    return {
      result: singleFetchResult,
      headers,
      status: context2.statusCode
    };
  } catch (error2) {
    handleError(error2);
    return {
      result: {
        error: error2
      },
      headers: new Headers(),
      status: 500
    };
  }
}
async function singleFetchLoaders(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) {
  try {
    var _URL$searchParams$get;
    let handlerRequest = new Request(handlerUrl, {
      headers: request.headers,
      signal: request.signal
    });
    let loadRouteIds = ((_URL$searchParams$get = new URL(request.url).searchParams.get("_routes")) === null || _URL$searchParams$get === void 0 ? void 0 : _URL$searchParams$get.split(",")) || void 0;
    let result = await staticHandler.query(handlerRequest, {
      requestContext: loadContext,
      skipLoaderErrorBubbling: true,
      dataStrategy: getSingleFetchDataStrategy({
        loadRouteIds
      })
    });
    if (isResponse(result)) {
      return {
        result: {
          [SingleFetchRedirectSymbol]: getSingleFetchRedirect(result.status, result.headers, build.basename)
        },
        headers: result.headers,
        status: SINGLE_FETCH_REDIRECT_STATUS
      };
    }
    let context2 = result;
    let headers = getDocumentHeaders(build, context2);
    if (isRedirectStatusCode(context2.statusCode) && headers.has("Location")) {
      return {
        result: {
          [SingleFetchRedirectSymbol]: getSingleFetchRedirect(context2.statusCode, headers, build.basename)
        },
        headers,
        status: SINGLE_FETCH_REDIRECT_STATUS
      };
    }
    if (context2.errors) {
      Object.values(context2.errors).forEach((err) => {
        if (!isRouteErrorResponse(err) || err.error) {
          handleError(err);
        }
      });
      context2.errors = sanitizeErrors(context2.errors, serverMode);
    }
    let results = {};
    let loadedMatches = loadRouteIds ? context2.matches.filter((m2) => m2.route.loader && loadRouteIds.includes(m2.route.id)) : context2.matches;
    loadedMatches.forEach((m2) => {
      var _context$loaderData, _context$errors;
      let data = (_context$loaderData = context2.loaderData) === null || _context$loaderData === void 0 ? void 0 : _context$loaderData[m2.route.id];
      let error2 = (_context$errors = context2.errors) === null || _context$errors === void 0 ? void 0 : _context$errors[m2.route.id];
      if (error2 !== void 0) {
        results[m2.route.id] = {
          error: error2
        };
      } else if (data !== void 0) {
        results[m2.route.id] = {
          data
        };
      }
    });
    return {
      result: results,
      headers,
      status: context2.statusCode
    };
  } catch (error2) {
    handleError(error2);
    return {
      result: {
        root: {
          error: error2
        }
      },
      headers: new Headers(),
      status: 500
    };
  }
}
function getSingleFetchRedirect(status, headers, basename2) {
  let redirect3 = headers.get("Location");
  if (basename2) {
    redirect3 = stripBasename(redirect3, basename2) || redirect3;
  }
  return {
    redirect: redirect3,
    status,
    revalidate: (
      // Technically X-Remix-Revalidate isn't needed here - that was an implementation
      // detail of ?_data requests as our way to tell the front end to revalidate when
      // we didn't have a response body to include that information in.
      // With single fetch, we tell the front end via this revalidate boolean field.
      // However, we're respecting it for now because it may be something folks have
      // used in their own responses
      // TODO(v3): Consider removing or making this official public API
      headers.has("X-Remix-Revalidate") || headers.has("Set-Cookie")
    ),
    reload: headers.has("X-Remix-Reload-Document"),
    replace: headers.has("X-Remix-Replace")
  };
}
function encodeViaTurboStream(data, requestSignal, streamTimeout, serverMode) {
  let controller = new AbortController();
  let timeoutId = setTimeout(() => controller.abort(new Error("Server Timeout")), typeof streamTimeout === "number" ? streamTimeout : 4950);
  requestSignal.addEventListener("abort", () => clearTimeout(timeoutId));
  return encode(data, {
    signal: controller.signal,
    plugins: [(value) => {
      if (value instanceof Error) {
        let {
          name,
          message,
          stack
        } = serverMode === ServerMode.Production ? sanitizeError(value, serverMode) : value;
        return ["SanitizedError", name, message, stack];
      }
      if (value instanceof ErrorResponseImpl) {
        let {
          data: data2,
          status,
          statusText
        } = value;
        return ["ErrorResponse", data2, status, statusText];
      }
      if (value && typeof value === "object" && SingleFetchRedirectSymbol in value) {
        return ["SingleFetchRedirect", value[SingleFetchRedirectSymbol]];
      }
    }],
    postPlugins: [(value) => {
      if (!value) return;
      if (typeof value !== "object") return;
      return ["SingleFetchClassInstance", Object.fromEntries(Object.entries(value))];
    }, () => ["SingleFetchFallback"]]
  });
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function createEntryRouteModules(manifest) {
  return Object.keys(manifest).reduce((memo, routeId) => {
    memo[routeId] = manifest[routeId].module;
    return memo;
  }, {});
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function invariant$1(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    console.error("The following error is a bug in Remix; please open an issue! https://github.com/remix-run/remix/issues/new");
    throw new Error(message);
  }
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function matchServerRoutes(routes2, pathname, basename2) {
  let matches = matchRoutes(routes2, pathname, basename2);
  if (!matches) return null;
  return matches.map((match) => ({
    params: match.params,
    pathname: match.pathname,
    route: match.route
  }));
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
async function callRouteAction({
  loadContext,
  action: action2,
  params,
  request,
  routeId,
  singleFetch
}) {
  let result = await action2({
    request: singleFetch ? stripRoutesParam(stripIndexParam(request)) : stripDataParam(stripIndexParam(request)),
    context: loadContext,
    params
  });
  if (result === void 0) {
    throw new Error(`You defined an action for route "${routeId}" but didn't return anything from your \`action\` function. Please return a value or \`null\`.`);
  }
  if (singleFetch) {
    return result;
  }
  return isResponse(result) ? result : json2(result);
}
async function callRouteLoader({
  loadContext,
  loader: loader2,
  params,
  request,
  routeId,
  singleFetch
}) {
  let result = await loader2({
    request: singleFetch ? stripRoutesParam(stripIndexParam(request)) : stripDataParam(stripIndexParam(request)),
    context: loadContext,
    params
  });
  if (result === void 0) {
    throw new Error(`You defined a loader for route "${routeId}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);
  }
  if (isDeferredData(result)) {
    if (result.init && isRedirectStatusCode(result.init.status || 200)) {
      return redirect2(new Headers(result.init.headers).get("Location"), result.init);
    }
    return result;
  }
  if (singleFetch) {
    return result;
  }
  return isResponse(result) ? result : json2(result);
}
function stripIndexParam(request) {
  let url = new URL(request.url);
  let indexValues = url.searchParams.getAll("index");
  url.searchParams.delete("index");
  let indexValuesToKeep = [];
  for (let indexValue of indexValues) {
    if (indexValue) {
      indexValuesToKeep.push(indexValue);
    }
  }
  for (let toKeep of indexValuesToKeep) {
    url.searchParams.append("index", toKeep);
  }
  let init = {
    method: request.method,
    body: request.body,
    headers: request.headers,
    signal: request.signal
  };
  if (init.body) {
    init.duplex = "half";
  }
  return new Request(url.href, init);
}
function stripDataParam(request) {
  let url = new URL(request.url);
  url.searchParams.delete("_data");
  let init = {
    method: request.method,
    body: request.body,
    headers: request.headers,
    signal: request.signal
  };
  if (init.body) {
    init.duplex = "half";
  }
  return new Request(url.href, init);
}
function stripRoutesParam(request) {
  let url = new URL(request.url);
  url.searchParams.delete("_routes");
  let init = {
    method: request.method,
    body: request.body,
    headers: request.headers,
    signal: request.signal
  };
  if (init.body) {
    init.duplex = "half";
  }
  return new Request(url.href, init);
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function groupRoutesByParentId$1(manifest) {
  let routes2 = {};
  Object.values(manifest).forEach((route) => {
    let parentId = route.parentId || "";
    if (!routes2[parentId]) {
      routes2[parentId] = [];
    }
    routes2[parentId].push(route);
  });
  return routes2;
}
function createRoutes(manifest, parentId = "", routesByParentId = groupRoutesByParentId$1(manifest)) {
  return (routesByParentId[parentId] || []).map((route) => ({
    ...route,
    children: createRoutes(manifest, route.id, routesByParentId)
  }));
}
function createStaticHandlerDataRoutes(manifest, future2, parentId = "", routesByParentId = groupRoutesByParentId$1(manifest)) {
  return (routesByParentId[parentId] || []).map((route) => {
    let commonRoute = {
      // Always include root due to default boundaries
      hasErrorBoundary: route.id === "root" || route.module.ErrorBoundary != null,
      id: route.id,
      path: route.path,
      loader: route.module.loader ? (
        // Need to use RR's version here to permit the optional context even
        // though we know it'll always be provided in remix
        (args, dataStrategyCtx) => callRouteLoader({
          request: args.request,
          params: args.params,
          loadContext: args.context,
          loader: route.module.loader,
          routeId: route.id,
          singleFetch: future2.v3_singleFetch === true
        })
      ) : void 0,
      action: route.module.action ? (args, dataStrategyCtx) => callRouteAction({
        request: args.request,
        params: args.params,
        loadContext: args.context,
        action: route.module.action,
        routeId: route.id,
        singleFetch: future2.v3_singleFetch === true
      }) : void 0,
      handle: route.module.handle
    };
    return route.index ? {
      index: true,
      ...commonRoute
    } : {
      caseSensitive: route.caseSensitive,
      children: createStaticHandlerDataRoutes(manifest, future2, route.id, routesByParentId),
      ...commonRoute
    };
  });
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const ESCAPE_LOOKUP$2 = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX$2 = /[&><\u2028\u2029]/g;
function escapeHtml$1(html) {
  return html.replace(ESCAPE_REGEX$2, (match) => ESCAPE_LOOKUP$2[match]);
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function createServerHandoffString(serverHandoff) {
  return escapeHtml$1(JSON.stringify(serverHandoff));
}
const globalDevServerHooksKey = "__remix_devServerHooks";
function getDevServerHooks() {
  return globalThis[globalDevServerHooksKey];
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function resourceRouteJsonWarning(type, routeId) {
  return `⚠️ REMIX FUTURE CHANGE: Externally-accessed resource routes will no longer be able to return raw JavaScript objects or \`null\` in React Router v7 when Single Fetch becomes the default. You can prepare for this change at your convenience by wrapping the data returned from your \`${type}\` function in the \`${routeId}\` route with \`json()\`.  For instructions on making this change, see https://remix.run/docs/en/v2.13.1/guides/single-fetch#resource-routes`;
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205, 304]);
function derive(build, mode2) {
  var _build$future, _build$future2;
  let routes2 = createRoutes(build.routes);
  let dataRoutes = createStaticHandlerDataRoutes(build.routes, build.future);
  let serverMode = isServerMode(mode2) ? mode2 : ServerMode.Production;
  let staticHandler = createStaticHandler(dataRoutes, {
    basename: build.basename,
    future: {
      v7_relativeSplatPath: ((_build$future = build.future) === null || _build$future === void 0 ? void 0 : _build$future.v3_relativeSplatPath) === true,
      v7_throwAbortReason: ((_build$future2 = build.future) === null || _build$future2 === void 0 ? void 0 : _build$future2.v3_throwAbortReason) === true
    }
  });
  let errorHandler = build.entry.module.handleError || ((error2, {
    request
  }) => {
    if (serverMode !== ServerMode.Test && !request.signal.aborted) {
      console.error(
        // @ts-expect-error This is "private" from users but intended for internal use
        isRouteErrorResponse(error2) && error2.error ? error2.error : error2
      );
    }
  });
  return {
    routes: routes2,
    dataRoutes,
    serverMode,
    staticHandler,
    errorHandler
  };
}
const createRequestHandler = (build, mode2) => {
  let _build;
  let routes2;
  let serverMode;
  let staticHandler;
  let errorHandler;
  return async function requestHandler(request, loadContext = {}) {
    _build = typeof build === "function" ? await build() : build;
    mode2 ?? (mode2 = _build.mode);
    if (typeof build === "function") {
      let derived = derive(_build, mode2);
      routes2 = derived.routes;
      serverMode = derived.serverMode;
      staticHandler = derived.staticHandler;
      errorHandler = derived.errorHandler;
    } else if (!routes2 || !serverMode || !staticHandler || !errorHandler) {
      let derived = derive(_build, mode2);
      routes2 = derived.routes;
      serverMode = derived.serverMode;
      staticHandler = derived.staticHandler;
      errorHandler = derived.errorHandler;
    }
    let url = new URL(request.url);
    let params = {};
    let handleError = (error2) => {
      if (mode2 === ServerMode.Development) {
        var _getDevServerHooks, _getDevServerHooks$pr;
        (_getDevServerHooks = getDevServerHooks()) === null || _getDevServerHooks === void 0 ? void 0 : (_getDevServerHooks$pr = _getDevServerHooks.processRequestError) === null || _getDevServerHooks$pr === void 0 ? void 0 : _getDevServerHooks$pr.call(_getDevServerHooks, error2);
      }
      errorHandler(error2, {
        context: loadContext,
        params,
        request
      });
    };
    let manifestUrl = `${_build.basename ?? "/"}/__manifest`.replace(/\/+/g, "/");
    if (url.pathname === manifestUrl) {
      try {
        let res = await handleManifestRequest(_build, routes2, url);
        return res;
      } catch (e2) {
        handleError(e2);
        return new Response("Unknown Server Error", {
          status: 500
        });
      }
    }
    let matches = matchServerRoutes(routes2, url.pathname, _build.basename);
    if (matches && matches.length > 0) {
      Object.assign(params, matches[0].params);
    }
    let response;
    if (url.searchParams.has("_data")) {
      if (_build.future.v3_singleFetch) {
        handleError(new Error("Warning: Single fetch-enabled apps should not be making ?_data requests, this is likely to break in the future"));
      }
      let routeId = url.searchParams.get("_data");
      response = await handleDataRequest(serverMode, _build, staticHandler, routeId, request, loadContext, handleError);
      if (_build.entry.module.handleDataRequest) {
        response = await _build.entry.module.handleDataRequest(response, {
          context: loadContext,
          params,
          request
        });
        if (isRedirectResponse(response)) {
          response = createRemixRedirectResponse(response, _build.basename);
        }
      }
    } else if (_build.future.v3_singleFetch && url.pathname.endsWith(".data")) {
      let handlerUrl = new URL(request.url);
      handlerUrl.pathname = handlerUrl.pathname.replace(/\.data$/, "").replace(/^\/_root$/, "/");
      let singleFetchMatches = matchServerRoutes(routes2, handlerUrl.pathname, _build.basename);
      response = await handleSingleFetchRequest(serverMode, _build, staticHandler, request, handlerUrl, loadContext, handleError);
      if (_build.entry.module.handleDataRequest) {
        response = await _build.entry.module.handleDataRequest(response, {
          context: loadContext,
          params: singleFetchMatches ? singleFetchMatches[0].params : {},
          request
        });
        if (isRedirectResponse(response)) {
          let result = getSingleFetchRedirect(response.status, response.headers, _build.basename);
          if (request.method === "GET") {
            result = {
              [SingleFetchRedirectSymbol]: result
            };
          }
          let headers = new Headers(response.headers);
          headers.set("Content-Type", "text/x-script");
          return new Response(encodeViaTurboStream(result, request.signal, _build.entry.module.streamTimeout, serverMode), {
            status: SINGLE_FETCH_REDIRECT_STATUS,
            headers
          });
        }
      }
    } else if (matches && matches[matches.length - 1].route.module.default == null && matches[matches.length - 1].route.module.ErrorBoundary == null) {
      response = await handleResourceRequest(serverMode, _build, staticHandler, matches.slice(-1)[0].route.id, request, loadContext, handleError);
    } else {
      var _getDevServerHooks2, _getDevServerHooks2$g;
      let criticalCss = mode2 === ServerMode.Development ? await ((_getDevServerHooks2 = getDevServerHooks()) === null || _getDevServerHooks2 === void 0 ? void 0 : (_getDevServerHooks2$g = _getDevServerHooks2.getCriticalCss) === null || _getDevServerHooks2$g === void 0 ? void 0 : _getDevServerHooks2$g.call(_getDevServerHooks2, _build, url.pathname)) : void 0;
      response = await handleDocumentRequest(serverMode, _build, staticHandler, request, loadContext, handleError, criticalCss);
    }
    if (request.method === "HEAD") {
      return new Response(null, {
        headers: response.headers,
        status: response.status,
        statusText: response.statusText
      });
    }
    return response;
  };
};
async function handleManifestRequest(build, routes2, url) {
  if (build.assets.version !== url.searchParams.get("version")) {
    return new Response(null, {
      status: 204,
      headers: {
        "X-Remix-Reload-Document": "true"
      }
    });
  }
  let patches = {};
  if (url.searchParams.has("p")) {
    let paths = /* @__PURE__ */ new Set();
    url.searchParams.getAll("p").forEach((path) => {
      if (!path.startsWith("/")) {
        path = `/${path}`;
      }
      let segments = path.split("/").slice(1);
      segments.forEach((_2, i2) => {
        let partialPath = segments.slice(0, i2 + 1).join("/");
        paths.add(`/${partialPath}`);
      });
    });
    for (let path of paths) {
      let matches = matchServerRoutes(routes2, path, build.basename);
      if (matches) {
        for (let match of matches) {
          let routeId = match.route.id;
          patches[routeId] = build.assets.routes[routeId];
        }
      }
    }
    return json2(patches, {
      headers: {
        "Cache-Control": "public, max-age=31536000, immutable"
      }
    });
  }
  return new Response("Invalid Request", {
    status: 400
  });
}
async function handleDataRequest(serverMode, build, staticHandler, routeId, request, loadContext, handleError) {
  try {
    let response = await staticHandler.queryRoute(request, {
      routeId,
      requestContext: loadContext
    });
    if (isRedirectResponse(response)) {
      return createRemixRedirectResponse(response, build.basename);
    }
    if (UNSAFE_DEFERRED_SYMBOL in response) {
      let deferredData = response[UNSAFE_DEFERRED_SYMBOL];
      let body = createDeferredReadableStream(deferredData, request.signal, serverMode);
      let init = deferredData.init || {};
      let headers = new Headers(init.headers);
      headers.set("Content-Type", "text/remix-deferred");
      headers.set("X-Remix-Response", "yes");
      init.headers = headers;
      return new Response(body, init);
    }
    response = safelySetHeader(response, "X-Remix-Response", "yes");
    return response;
  } catch (error2) {
    if (isResponse(error2)) {
      let response = safelySetHeader(error2, "X-Remix-Catch", "yes");
      return response;
    }
    if (isRouteErrorResponse(error2)) {
      handleError(error2);
      return errorResponseToJson(error2, serverMode);
    }
    let errorInstance = error2 instanceof Error || error2 instanceof DOMException ? error2 : new Error("Unexpected Server Error");
    handleError(errorInstance);
    return json$1(serializeError(errorInstance, serverMode), {
      status: 500,
      headers: {
        "X-Remix-Error": "yes"
      }
    });
  }
}
async function handleSingleFetchRequest(serverMode, build, staticHandler, request, handlerUrl, loadContext, handleError) {
  let {
    result,
    headers,
    status
  } = request.method !== "GET" ? await singleFetchAction(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) : await singleFetchLoaders(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError);
  let resultHeaders = new Headers(headers);
  resultHeaders.set("X-Remix-Response", "yes");
  if (NO_BODY_STATUS_CODES.has(status)) {
    return new Response(null, {
      status,
      headers: resultHeaders
    });
  }
  resultHeaders.set("Content-Type", "text/x-script");
  return new Response(encodeViaTurboStream(result, request.signal, build.entry.module.streamTimeout, serverMode), {
    status: status || 200,
    headers: resultHeaders
  });
}
async function handleDocumentRequest(serverMode, build, staticHandler, request, loadContext, handleError, criticalCss) {
  let context2;
  try {
    if (request.method === "POST") {
      throwIfPotentialCSRFAttack(request.headers);
    }
    context2 = await staticHandler.query(request, {
      requestContext: loadContext
    });
  } catch (error2) {
    handleError(error2);
    return new Response(null, {
      status: 500
    });
  }
  if (isResponse(context2)) {
    return context2;
  }
  let headers = getDocumentHeaders(build, context2);
  if (NO_BODY_STATUS_CODES.has(context2.statusCode)) {
    return new Response(null, {
      status: context2.statusCode,
      headers
    });
  }
  if (context2.errors) {
    Object.values(context2.errors).forEach((err) => {
      if (!isRouteErrorResponse(err) || err.error) {
        handleError(err);
      }
    });
    context2.errors = sanitizeErrors(context2.errors, serverMode);
  }
  let state = {
    loaderData: context2.loaderData,
    actionData: context2.actionData,
    errors: serializeErrors$1(context2.errors, serverMode)
  };
  let entryContext = {
    manifest: build.assets,
    routeModules: createEntryRouteModules(build.routes),
    staticHandlerContext: context2,
    criticalCss,
    serverHandoffString: createServerHandoffString({
      basename: build.basename,
      criticalCss,
      future: build.future,
      isSpaMode: build.isSpaMode,
      ...!build.future.v3_singleFetch ? {
        state
      } : null
    }),
    ...build.future.v3_singleFetch ? {
      serverHandoffStream: encodeViaTurboStream(state, request.signal, build.entry.module.streamTimeout, serverMode),
      renderMeta: {}
    } : null,
    future: build.future,
    isSpaMode: build.isSpaMode,
    serializeError: (err) => serializeError(err, serverMode)
  };
  let handleDocumentRequestFunction = build.entry.module.default;
  try {
    return await handleDocumentRequestFunction(request, context2.statusCode, headers, entryContext, loadContext);
  } catch (error2) {
    handleError(error2);
    let errorForSecondRender = error2;
    if (isResponse(error2)) {
      try {
        let data = await unwrapResponse(error2);
        errorForSecondRender = new ErrorResponseImpl(error2.status, error2.statusText, data);
      } catch (e2) {
      }
    }
    context2 = getStaticContextFromError(staticHandler.dataRoutes, context2, errorForSecondRender);
    if (context2.errors) {
      context2.errors = sanitizeErrors(context2.errors, serverMode);
    }
    let state2 = {
      loaderData: context2.loaderData,
      actionData: context2.actionData,
      errors: serializeErrors$1(context2.errors, serverMode)
    };
    entryContext = {
      ...entryContext,
      staticHandlerContext: context2,
      serverHandoffString: createServerHandoffString({
        basename: build.basename,
        future: build.future,
        isSpaMode: build.isSpaMode,
        ...!build.future.v3_singleFetch ? {
          state: state2
        } : null
      }),
      ...build.future.v3_singleFetch ? {
        serverHandoffStream: encodeViaTurboStream(state2, request.signal, build.entry.module.streamTimeout, serverMode),
        renderMeta: {}
      } : null
    };
    try {
      return await handleDocumentRequestFunction(request, context2.statusCode, headers, entryContext, loadContext);
    } catch (error3) {
      handleError(error3);
      return returnLastResortErrorResponse(error3, serverMode);
    }
  }
}
async function handleResourceRequest(serverMode, build, staticHandler, routeId, request, loadContext, handleError) {
  try {
    let response = await staticHandler.queryRoute(request, {
      routeId,
      requestContext: loadContext
    });
    if (typeof response === "object" && response !== null) {
      invariant$1(!(UNSAFE_DEFERRED_SYMBOL in response), `You cannot return a \`defer()\` response from a Resource Route.  Did you forget to export a default UI component from the "${routeId}" route?`);
    }
    if (build.future.v3_singleFetch && !isResponse(response)) {
      console.warn(resourceRouteJsonWarning(request.method === "GET" ? "loader" : "action", routeId));
      response = json2(response);
    }
    invariant$1(isResponse(response), "Expected a Response to be returned from queryRoute");
    return response;
  } catch (error2) {
    if (isResponse(error2)) {
      let response = safelySetHeader(error2, "X-Remix-Catch", "yes");
      return response;
    }
    if (isRouteErrorResponse(error2)) {
      if (error2) {
        handleError(error2);
      }
      return errorResponseToJson(error2, serverMode);
    }
    handleError(error2);
    return returnLastResortErrorResponse(error2, serverMode);
  }
}
function errorResponseToJson(errorResponse, serverMode) {
  return json$1(serializeError(
    // @ts-expect-error This is "private" from users but intended for internal use
    errorResponse.error || new Error("Unexpected Server Error"),
    serverMode
  ), {
    status: errorResponse.status,
    statusText: errorResponse.statusText,
    headers: {
      "X-Remix-Error": "yes"
    }
  });
}
function returnLastResortErrorResponse(error2, serverMode) {
  let message = "Unexpected Server Error";
  if (serverMode !== ServerMode.Production) {
    message += `

${String(error2)}`;
  }
  return new Response(message, {
    status: 500,
    headers: {
      "Content-Type": "text/plain"
    }
  });
}
function unwrapResponse(response) {
  let contentType = response.headers.get("Content-Type");
  return contentType && /\bapplication\/json\b/.test(contentType) ? response.body == null ? null : response.json() : response.text();
}
function createRemixRedirectResponse(response, basename2) {
  let headers = new Headers(response.headers);
  let redirectUrl = headers.get("Location");
  headers.set("X-Remix-Redirect", basename2 ? stripBasename(redirectUrl, basename2) || redirectUrl : redirectUrl);
  headers.set("X-Remix-Status", String(response.status));
  headers.delete("Location");
  if (response.headers.get("Set-Cookie") !== null) {
    headers.set("X-Remix-Revalidate", "yes");
  }
  return new Response(null, {
    status: 204,
    headers
  });
}
function safelySetHeader(response, name, value) {
  let headers = new Headers(response.headers);
  headers.set(name, value);
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
    duplex: response.body ? "half" : void 0
  });
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function flash(name) {
  return `__flash_${name}__`;
}
const createSession = (initialData = {}, id = "") => {
  let map = new Map(Object.entries(initialData));
  return {
    get id() {
      return id;
    },
    get data() {
      return Object.fromEntries(map);
    },
    has(name) {
      return map.has(name) || map.has(flash(name));
    },
    get(name) {
      if (map.has(name)) return map.get(name);
      let flashName = flash(name);
      if (map.has(flashName)) {
        let value = map.get(flashName);
        map.delete(flashName);
        return value;
      }
      return void 0;
    },
    set(name, value) {
      map.set(name, value);
    },
    flash(name, value) {
      map.set(flash(name), value);
    },
    unset(name) {
      map.delete(name);
    }
  };
};
function warnOnceAboutSigningSessionCookie(cookie2) {
  warnOnce$2(cookie2.isSigned, `The "${cookie2.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://remix.run/utils/cookies#signing-cookies for more information.`);
}
/**
 * @remix-run/server-runtime v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const createCookieSessionStorageFactory = (createCookie) => ({
  cookie: cookieArg
} = {}) => {
  let cookie2 = isCookie(cookieArg) ? cookieArg : createCookie((cookieArg === null || cookieArg === void 0 ? void 0 : cookieArg.name) || "__session", cookieArg);
  warnOnceAboutSigningSessionCookie(cookie2);
  return {
    async getSession(cookieHeader, options) {
      return createSession(cookieHeader && await cookie2.parse(cookieHeader, options) || {});
    },
    async commitSession(session, options) {
      let serializedCookie = await cookie2.serialize(session.data, options);
      if (serializedCookie.length > 4096) {
        throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length);
      }
      return serializedCookie;
    },
    async destroySession(_session2, options) {
      return cookie2.serialize("", {
        ...options,
        maxAge: void 0,
        expires: /* @__PURE__ */ new Date(0)
      });
    }
  };
};
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function _extends$1() {
  _extends$1 = Object.assign ? Object.assign.bind() : function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$1.apply(this, arguments);
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function invariant(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
async function loadRouteModule(route, routeModulesCache) {
  if (route.id in routeModulesCache) {
    return routeModulesCache[route.id];
  }
  try {
    let routeModule = await import(
      /* webpackIgnore: true */
      route.module
    );
    routeModulesCache[route.id] = routeModule;
    return routeModule;
  } catch (error2) {
    console.error(`Error loading route module \`${route.module}\`, reloading page...`);
    console.error(error2);
    if (window.__remixContext.isSpaMode && // @ts-expect-error
    false) ;
    window.location.reload();
    return new Promise(() => {
    });
  }
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function getKeyedLinksForMatches(matches, routeModules, manifest) {
  let descriptors = matches.map((match) => {
    var _module$links;
    let module = routeModules[match.route.id];
    let route = manifest.routes[match.route.id];
    return [route.css ? route.css.map((href) => ({
      rel: "stylesheet",
      href
    })) : [], (module === null || module === void 0 ? void 0 : (_module$links = module.links) === null || _module$links === void 0 ? void 0 : _module$links.call(module)) || []];
  }).flat(2);
  let preloads = getCurrentPageModulePreloadHrefs(matches, manifest);
  return dedupeLinkDescriptors(descriptors, preloads);
}
function isPageLinkDescriptor(object) {
  return object != null && typeof object.page === "string";
}
function isHtmlLinkDescriptor(object) {
  if (object == null) {
    return false;
  }
  if (object.href == null) {
    return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
  }
  return typeof object.rel === "string" && typeof object.href === "string";
}
async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
  let links2 = await Promise.all(matches.map(async (match) => {
    let mod = await loadRouteModule(manifest.routes[match.route.id], routeModules);
    return mod.links ? mod.links() : [];
  }));
  return dedupeLinkDescriptors(links2.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map((link) => link.rel === "stylesheet" ? {
    ...link,
    rel: "prefetch",
    as: "style"
  } : {
    ...link,
    rel: "prefetch"
  }));
}
function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, future2, mode2) {
  let path = parsePathPatch(page);
  let isNew = (match, index) => {
    if (!currentMatches[index]) return true;
    return match.route.id !== currentMatches[index].route.id;
  };
  let matchPathChanged = (match, index) => {
    var _currentMatches$index;
    return (
      // param change, /users/123 -> /users/456
      currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
      // e.g. /files/images/avatar.jpg -> files/finances.xls
      ((_currentMatches$index = currentMatches[index].route.path) === null || _currentMatches$index === void 0 ? void 0 : _currentMatches$index.endsWith("*")) && currentMatches[index].params["*"] !== match.params["*"]
    );
  };
  let newMatches = mode2 === "data" && (future2.v3_singleFetch || location.search !== path.search) ? (
    // this is really similar to stuff in transition.ts, maybe somebody smarter
    // than me (or in less of a hurry) can share some of it. You're the best.
    nextMatches.filter((match, index) => {
      let manifestRoute = manifest.routes[match.route.id];
      if (!manifestRoute.hasLoader) {
        return false;
      }
      if (isNew(match, index) || matchPathChanged(match, index)) {
        return true;
      }
      let defaultShouldRevalidate = future2.v3_singleFetch || location.search !== path.search;
      if (match.route.shouldRevalidate) {
        var _currentMatches$;
        let routeChoice = match.route.shouldRevalidate({
          currentUrl: new URL(location.pathname + location.search + location.hash, window.origin),
          currentParams: ((_currentMatches$ = currentMatches[0]) === null || _currentMatches$ === void 0 ? void 0 : _currentMatches$.params) || {},
          nextUrl: new URL(page, window.origin),
          nextParams: match.params,
          defaultShouldRevalidate
        });
        if (typeof routeChoice === "boolean") {
          return routeChoice;
        }
      }
      return defaultShouldRevalidate;
    })
  ) : nextMatches.filter((match, index) => {
    let manifestRoute = manifest.routes[match.route.id];
    return (mode2 === "assets" || manifestRoute.hasLoader) && (isNew(match, index) || matchPathChanged(match, index));
  });
  return newMatches;
}
function getDataLinkHrefs(page, matches, manifest) {
  let path = parsePathPatch(page);
  return dedupeHrefs(matches.filter((match) => manifest.routes[match.route.id].hasLoader && !manifest.routes[match.route.id].hasClientLoader).map((match) => {
    let {
      pathname,
      search
    } = path;
    let searchParams = new URLSearchParams(search);
    searchParams.set("_data", match.route.id);
    return `${pathname}?${searchParams}`;
  }));
}
function getModuleLinkHrefs(matches, manifestPatch) {
  return dedupeHrefs(matches.map((match) => {
    let route = manifestPatch.routes[match.route.id];
    let hrefs = [route.module];
    if (route.imports) {
      hrefs = hrefs.concat(route.imports);
    }
    return hrefs;
  }).flat(1));
}
function getCurrentPageModulePreloadHrefs(matches, manifest) {
  return dedupeHrefs(matches.map((match) => {
    let route = manifest.routes[match.route.id];
    let hrefs = [route.module];
    if (route.imports) {
      hrefs = hrefs.concat(route.imports);
    }
    return hrefs;
  }).flat(1));
}
function dedupeHrefs(hrefs) {
  return [...new Set(hrefs)];
}
function sortKeys(obj) {
  let sorted = {};
  let keys = Object.keys(obj).sort();
  for (let key of keys) {
    sorted[key] = obj[key];
  }
  return sorted;
}
function dedupeLinkDescriptors(descriptors, preloads) {
  let set = /* @__PURE__ */ new Set();
  let preloadsSet = new Set(preloads);
  return descriptors.reduce((deduped, descriptor) => {
    let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
    if (alreadyModulePreload) {
      return deduped;
    }
    let key = JSON.stringify(sortKeys(descriptor));
    if (!set.has(key)) {
      set.add(key);
      deduped.push({
        key,
        link: descriptor
      });
    }
    return deduped;
  }, []);
}
function parsePathPatch(href) {
  let path = parsePath(href);
  if (path.search === void 0) path.search = "";
  return path;
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
const ESCAPE_LOOKUP$1 = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX$1 = /[&><\u2028\u2029]/g;
function escapeHtml(html) {
  return html.replace(ESCAPE_REGEX$1, (match) => ESCAPE_LOOKUP$1[match]);
}
function createHtml(html) {
  return {
    __html: html
  };
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function StreamTransfer({
  context: context2,
  identifier,
  reader,
  textDecoder,
  nonce
}) {
  if (!context2.renderMeta || !context2.renderMeta.didRenderScripts) {
    return null;
  }
  if (!context2.renderMeta.streamCache) {
    context2.renderMeta.streamCache = {};
  }
  let {
    streamCache
  } = context2.renderMeta;
  let promise = streamCache[identifier];
  if (!promise) {
    promise = streamCache[identifier] = reader.read().then((result) => {
      streamCache[identifier].result = {
        done: result.done,
        value: textDecoder.decode(result.value, {
          stream: true
        })
      };
    }).catch((e2) => {
      streamCache[identifier].error = e2;
    });
  }
  if (promise.error) {
    throw promise.error;
  }
  if (promise.result === void 0) {
    throw promise;
  }
  let {
    done,
    value
  } = promise.result;
  let scriptTag = value ? /* @__PURE__ */ reactExports.createElement("script", {
    nonce,
    dangerouslySetInnerHTML: {
      __html: `window.__remixContext.streamController.enqueue(${escapeHtml(JSON.stringify(value))});`
    }
  }) : null;
  if (done) {
    return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, scriptTag, /* @__PURE__ */ reactExports.createElement("script", {
      nonce,
      dangerouslySetInnerHTML: {
        __html: `window.__remixContext.streamController.close();`
      }
    }));
  } else {
    return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, scriptTag, /* @__PURE__ */ reactExports.createElement(reactExports.Suspense, null, /* @__PURE__ */ reactExports.createElement(StreamTransfer, {
      context: context2,
      identifier: identifier + 1,
      reader,
      textDecoder,
      nonce
    })));
  }
}
function singleFetchUrl(reqUrl) {
  let url = typeof reqUrl === "string" ? new URL(
    reqUrl,
    // This can be called during the SSR flow via PrefetchPageLinksImpl so
    // don't assume window is available
    typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
  ) : reqUrl;
  if (url.pathname === "/") {
    url.pathname = "_root.data";
  } else {
    url.pathname = `${url.pathname.replace(/\/$/, "")}.data`;
  }
  return url;
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
class RemixErrorBoundary extends reactExports.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: props.error || null,
      location: props.location
    };
  }
  static getDerivedStateFromError(error2) {
    return {
      error: error2
    };
  }
  static getDerivedStateFromProps(props, state) {
    if (state.location !== props.location) {
      return {
        error: props.error || null,
        location: props.location
      };
    }
    return {
      error: props.error || state.error,
      location: state.location
    };
  }
  render() {
    if (this.state.error) {
      return /* @__PURE__ */ reactExports.createElement(RemixRootDefaultErrorBoundary, {
        error: this.state.error,
        isOutsideRemixApp: true
      });
    } else {
      return this.props.children;
    }
  }
}
function RemixRootDefaultErrorBoundary({
  error: error2,
  isOutsideRemixApp
}) {
  console.error(error2);
  let heyDeveloper = /* @__PURE__ */ reactExports.createElement("script", {
    dangerouslySetInnerHTML: {
      __html: `
        console.log(
          "💿 Hey developer 👋. You can provide a way better UX than this when your app throws errors. Check out https://remix.run/guides/errors for more information."
        );
      `
    }
  });
  if (isRouteErrorResponse(error2)) {
    return /* @__PURE__ */ reactExports.createElement(BoundaryShell, {
      title: "Unhandled Thrown Response!"
    }, /* @__PURE__ */ reactExports.createElement("h1", {
      style: {
        fontSize: "24px"
      }
    }, error2.status, " ", error2.statusText), heyDeveloper);
  }
  let errorInstance;
  if (error2 instanceof Error) {
    errorInstance = error2;
  } else {
    let errorString = error2 == null ? "Unknown Error" : typeof error2 === "object" && "toString" in error2 ? error2.toString() : JSON.stringify(error2);
    errorInstance = new Error(errorString);
  }
  return /* @__PURE__ */ reactExports.createElement(BoundaryShell, {
    title: "Application Error!",
    isOutsideRemixApp
  }, /* @__PURE__ */ reactExports.createElement("h1", {
    style: {
      fontSize: "24px"
    }
  }, "Application Error"), /* @__PURE__ */ reactExports.createElement("pre", {
    style: {
      padding: "2rem",
      background: "hsla(10, 50%, 50%, 0.1)",
      color: "red",
      overflow: "auto"
    }
  }, errorInstance.stack), heyDeveloper);
}
function BoundaryShell({
  title,
  renderScripts,
  isOutsideRemixApp,
  children
}) {
  var _routeModules$root;
  let {
    routeModules
  } = useRemixContext();
  if ((_routeModules$root = routeModules.root) !== null && _routeModules$root !== void 0 && _routeModules$root.Layout && !isOutsideRemixApp) {
    return children;
  }
  return /* @__PURE__ */ reactExports.createElement("html", {
    lang: "en"
  }, /* @__PURE__ */ reactExports.createElement("head", null, /* @__PURE__ */ reactExports.createElement("meta", {
    charSet: "utf-8"
  }), /* @__PURE__ */ reactExports.createElement("meta", {
    name: "viewport",
    content: "width=device-width,initial-scale=1,viewport-fit=cover"
  }), /* @__PURE__ */ reactExports.createElement("title", null, title)), /* @__PURE__ */ reactExports.createElement("body", null, /* @__PURE__ */ reactExports.createElement("main", {
    style: {
      fontFamily: "system-ui, sans-serif",
      padding: "2rem"
    }
  }, children, renderScripts ? /* @__PURE__ */ reactExports.createElement(Scripts, null) : null)));
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function RemixRootDefaultHydrateFallback() {
  return /* @__PURE__ */ reactExports.createElement(BoundaryShell, {
    title: "Loading...",
    renderScripts: true
  }, /* @__PURE__ */ reactExports.createElement("script", {
    dangerouslySetInnerHTML: {
      __html: `
              console.log(
                "💿 Hey developer 👋. You can provide a way better UX than this " +
                "when your app is loading JS modules and/or running \`clientLoader\` " +
                "functions. Check out https://remix.run/route/hydrate-fallback " +
                "for more information."
              );
            `
    }
  }));
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function groupRoutesByParentId(manifest) {
  let routes2 = {};
  Object.values(manifest).forEach((route) => {
    let parentId = route.parentId || "";
    if (!routes2[parentId]) {
      routes2[parentId] = [];
    }
    routes2[parentId].push(route);
  });
  return routes2;
}
function getRouteComponents(route, routeModule, isSpaMode2) {
  let Component2 = getRouteModuleComponent(routeModule);
  let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode2 || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
  let ErrorBoundary2 = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => /* @__PURE__ */ reactExports.createElement(RemixRootDefaultErrorBoundary, {
    error: useRouteError()
  }) : void 0;
  if (route.id === "root" && routeModule.Layout) {
    return {
      ...Component2 ? {
        element: /* @__PURE__ */ reactExports.createElement(routeModule.Layout, null, /* @__PURE__ */ reactExports.createElement(Component2, null))
      } : {
        Component: Component2
      },
      ...ErrorBoundary2 ? {
        errorElement: /* @__PURE__ */ reactExports.createElement(routeModule.Layout, null, /* @__PURE__ */ reactExports.createElement(ErrorBoundary2, null))
      } : {
        ErrorBoundary: ErrorBoundary2
      },
      ...HydrateFallback ? {
        hydrateFallbackElement: /* @__PURE__ */ reactExports.createElement(routeModule.Layout, null, /* @__PURE__ */ reactExports.createElement(HydrateFallback, null))
      } : {
        HydrateFallback
      }
    };
  }
  return {
    Component: Component2,
    ErrorBoundary: ErrorBoundary2,
    HydrateFallback
  };
}
function createServerRoutes(manifest, routeModules, future2, isSpaMode2, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({
  Component: () => null
})) {
  return (routesByParentId[parentId] || []).map((route) => {
    let routeModule = routeModules[route.id];
    invariant(routeModule, "No `routeModule` available to create server routes");
    let dataRoute = {
      ...getRouteComponents(route, routeModule, isSpaMode2),
      caseSensitive: route.caseSensitive,
      id: route.id,
      index: route.index,
      path: route.path,
      handle: routeModule.handle,
      // For SPA Mode, all routes are lazy except root.  However we tell the
      // router root is also lazy here too since we don't need a full
      // implementation - we just need a `lazy` prop to tell the RR rendering
      // where to stop which is always at the root route in SPA mode
      lazy: isSpaMode2 ? () => spaModeLazyPromise : void 0,
      // For partial hydration rendering, we need to indicate when the route
      // has a loader/clientLoader, but it won't ever be called during the static
      // render, so just give it a no-op function so we can render down to the
      // proper fallback
      loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
      // We don't need action/shouldRevalidate on these routes since they're
      // for a static render
    };
    let children = createServerRoutes(manifest, routeModules, future2, isSpaMode2, route.id, routesByParentId, spaModeLazyPromise);
    if (children.length > 0) dataRoute.children = children;
    return dataRoute;
  });
}
function getRouteModuleComponent(routeModule) {
  if (routeModule.default == null) return void 0;
  let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
  if (!isEmptyObject) {
    return routeModule.default;
  }
}
function shouldHydrateRouteLoader(route, routeModule, isSpaMode2) {
  return isSpaMode2 && route.id !== "root" || routeModule.clientLoader != null && (routeModule.clientLoader.hydrate === true || route.hasLoader !== true);
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function isFogOfWarEnabled(future2, isSpaMode2) {
  return future2.v3_lazyRouteDiscovery === true && !isSpaMode2;
}
function getPartialManifest(manifest, router) {
  let routeIds = new Set(router.state.matches.map((m2) => m2.route.id));
  let segments = router.state.location.pathname.split("/").filter(Boolean);
  let paths = ["/"];
  segments.pop();
  while (segments.length > 0) {
    paths.push(`/${segments.join("/")}`);
    segments.pop();
  }
  paths.forEach((path) => {
    let matches = matchRoutes(router.routes, path, router.basename);
    if (matches) {
      matches.forEach((m2) => routeIds.add(m2.route.id));
    }
  });
  let initialRoutes = [...routeIds].reduce((acc, id) => Object.assign(acc, {
    [id]: manifest.routes[id]
  }), {});
  return {
    ...manifest,
    routes: initialRoutes
  };
}
function useDataRouterContext() {
  let context2 = reactExports.useContext(DataRouterContext);
  invariant(context2, "You must render this element inside a <DataRouterContext.Provider> element");
  return context2;
}
function useDataRouterStateContext() {
  let context2 = reactExports.useContext(DataRouterStateContext);
  invariant(context2, "You must render this element inside a <DataRouterStateContext.Provider> element");
  return context2;
}
const RemixContext = /* @__PURE__ */ reactExports.createContext(void 0);
RemixContext.displayName = "Remix";
function useRemixContext() {
  let context2 = reactExports.useContext(RemixContext);
  invariant(context2, "You must render this element inside a <Remix> element");
  return context2;
}
function usePrefetchBehavior(prefetch, theirElementProps) {
  let [maybePrefetch, setMaybePrefetch] = reactExports.useState(false);
  let [shouldPrefetch, setShouldPrefetch] = reactExports.useState(false);
  let {
    onFocus,
    onBlur,
    onMouseEnter,
    onMouseLeave,
    onTouchStart
  } = theirElementProps;
  let ref = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (prefetch === "render") {
      setShouldPrefetch(true);
    }
    if (prefetch === "viewport") {
      let callback = (entries) => {
        entries.forEach((entry2) => {
          setShouldPrefetch(entry2.isIntersecting);
        });
      };
      let observer = new IntersectionObserver(callback, {
        threshold: 0.5
      });
      if (ref.current) observer.observe(ref.current);
      return () => {
        observer.disconnect();
      };
    }
  }, [prefetch]);
  let setIntent = () => {
    if (prefetch === "intent") {
      setMaybePrefetch(true);
    }
  };
  let cancelIntent = () => {
    if (prefetch === "intent") {
      setMaybePrefetch(false);
      setShouldPrefetch(false);
    }
  };
  reactExports.useEffect(() => {
    if (maybePrefetch) {
      let id = setTimeout(() => {
        setShouldPrefetch(true);
      }, 100);
      return () => {
        clearTimeout(id);
      };
    }
  }, [maybePrefetch]);
  return [shouldPrefetch, ref, {
    onFocus: composeEventHandlers(onFocus, setIntent),
    onBlur: composeEventHandlers(onBlur, cancelIntent),
    onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
    onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
    onTouchStart: composeEventHandlers(onTouchStart, setIntent)
  }];
}
const ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
function getDiscoverAttr(discover, isAbsolute, reloadDocument) {
  return discover === "render" && !isAbsolute && !reloadDocument ? "true" : void 0;
}
let NavLink = /* @__PURE__ */ reactExports.forwardRef(({
  to,
  prefetch = "none",
  discover = "render",
  ...props
}, forwardedRef) => {
  let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX$1.test(to);
  let href = useHref(to);
  let [shouldPrefetch, ref, prefetchHandlers] = usePrefetchBehavior(prefetch, props);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(NavLink$1, _extends$1({}, props, prefetchHandlers, {
    ref: mergeRefs(forwardedRef, ref),
    to,
    "data-discover": getDiscoverAttr(discover, isAbsolute, props.reloadDocument)
  })), shouldPrefetch && !isAbsolute ? /* @__PURE__ */ reactExports.createElement(PrefetchPageLinks, {
    page: href
  }) : null);
});
NavLink.displayName = "NavLink";
let Link = /* @__PURE__ */ reactExports.forwardRef(({
  to,
  prefetch = "none",
  discover = "render",
  ...props
}, forwardedRef) => {
  let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX$1.test(to);
  let href = useHref(to);
  let [shouldPrefetch, ref, prefetchHandlers] = usePrefetchBehavior(prefetch, props);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(Link$1, _extends$1({}, props, prefetchHandlers, {
    ref: mergeRefs(forwardedRef, ref),
    to,
    "data-discover": getDiscoverAttr(discover, isAbsolute, props.reloadDocument)
  })), shouldPrefetch && !isAbsolute ? /* @__PURE__ */ reactExports.createElement(PrefetchPageLinks, {
    page: href
  }) : null);
});
Link.displayName = "Link";
let Form = /* @__PURE__ */ reactExports.forwardRef(({
  discover = "render",
  ...props
}, forwardedRef) => {
  let isAbsolute = typeof props.action === "string" && ABSOLUTE_URL_REGEX$1.test(props.action);
  return /* @__PURE__ */ reactExports.createElement(Form$1, _extends$1({}, props, {
    ref: forwardedRef,
    "data-discover": getDiscoverAttr(discover, isAbsolute, props.reloadDocument)
  }));
});
Form.displayName = "Form";
function composeEventHandlers(theirHandler, ourHandler) {
  return (event) => {
    theirHandler && theirHandler(event);
    if (!event.defaultPrevented) {
      ourHandler(event);
    }
  };
}
function getActiveMatches(matches, errors, isSpaMode2) {
  if (isSpaMode2 && !isHydrated) {
    return [matches[0]];
  }
  if (errors) {
    let errorIdx = matches.findIndex((m2) => errors[m2.route.id] !== void 0);
    return matches.slice(0, errorIdx + 1);
  }
  return matches;
}
function Links() {
  let {
    isSpaMode: isSpaMode2,
    manifest,
    routeModules,
    criticalCss
  } = useRemixContext();
  let {
    errors,
    matches: routerMatches
  } = useDataRouterStateContext();
  let matches = getActiveMatches(routerMatches, errors, isSpaMode2);
  let keyedLinks = reactExports.useMemo(() => getKeyedLinksForMatches(matches, routeModules, manifest), [matches, routeModules, manifest]);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, criticalCss ? /* @__PURE__ */ reactExports.createElement("style", {
    dangerouslySetInnerHTML: {
      __html: criticalCss
    }
  }) : null, keyedLinks.map(({
    key,
    link
  }) => isPageLinkDescriptor(link) ? /* @__PURE__ */ reactExports.createElement(PrefetchPageLinks, _extends$1({
    key
  }, link)) : /* @__PURE__ */ reactExports.createElement("link", _extends$1({
    key
  }, link))));
}
function PrefetchPageLinks({
  page,
  ...dataLinkProps
}) {
  let {
    router
  } = useDataRouterContext();
  let matches = reactExports.useMemo(() => matchRoutes(router.routes, page, router.basename), [router.routes, page, router.basename]);
  if (!matches) {
    console.warn(`Tried to prefetch ${page} but no routes matched.`);
    return null;
  }
  return /* @__PURE__ */ reactExports.createElement(PrefetchPageLinksImpl, _extends$1({
    page,
    matches
  }, dataLinkProps));
}
function useKeyedPrefetchLinks(matches) {
  let {
    manifest,
    routeModules
  } = useRemixContext();
  let [keyedPrefetchLinks, setKeyedPrefetchLinks] = reactExports.useState([]);
  reactExports.useEffect(() => {
    let interrupted = false;
    void getKeyedPrefetchLinks(matches, manifest, routeModules).then((links2) => {
      if (!interrupted) {
        setKeyedPrefetchLinks(links2);
      }
    });
    return () => {
      interrupted = true;
    };
  }, [matches, manifest, routeModules]);
  return keyedPrefetchLinks;
}
function PrefetchPageLinksImpl({
  page,
  matches: nextMatches,
  ...linkProps
}) {
  let location = useLocation();
  let {
    future: future2,
    manifest,
    routeModules
  } = useRemixContext();
  let {
    loaderData,
    matches
  } = useDataRouterStateContext();
  let newMatchesForData = reactExports.useMemo(() => getNewMatchesForLinks(page, nextMatches, matches, manifest, location, future2, "data"), [page, nextMatches, matches, manifest, location, future2]);
  let dataHrefs = reactExports.useMemo(() => {
    if (!future2.v3_singleFetch) {
      return getDataLinkHrefs(page, newMatchesForData, manifest);
    }
    if (page === location.pathname + location.search + location.hash) {
      return [];
    }
    let routesParams = /* @__PURE__ */ new Set();
    let foundOptOutRoute = false;
    nextMatches.forEach((m2) => {
      var _routeModules$m$route;
      if (!manifest.routes[m2.route.id].hasLoader) {
        return;
      }
      if (!newMatchesForData.some((m22) => m22.route.id === m2.route.id) && m2.route.id in loaderData && (_routeModules$m$route = routeModules[m2.route.id]) !== null && _routeModules$m$route !== void 0 && _routeModules$m$route.shouldRevalidate) {
        foundOptOutRoute = true;
      } else if (manifest.routes[m2.route.id].hasClientLoader) {
        foundOptOutRoute = true;
      } else {
        routesParams.add(m2.route.id);
      }
    });
    if (routesParams.size === 0) {
      return [];
    }
    let url = singleFetchUrl(page);
    if (foundOptOutRoute && routesParams.size > 0) {
      url.searchParams.set("_routes", nextMatches.filter((m2) => routesParams.has(m2.route.id)).map((m2) => m2.route.id).join(","));
    }
    return [url.pathname + url.search];
  }, [future2.v3_singleFetch, loaderData, location, manifest, newMatchesForData, nextMatches, page, routeModules]);
  let newMatchesForAssets = reactExports.useMemo(() => getNewMatchesForLinks(page, nextMatches, matches, manifest, location, future2, "assets"), [page, nextMatches, matches, manifest, location, future2]);
  let moduleHrefs = reactExports.useMemo(() => getModuleLinkHrefs(newMatchesForAssets, manifest), [newMatchesForAssets, manifest]);
  let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ reactExports.createElement("link", _extends$1({
    key: href,
    rel: "prefetch",
    as: "fetch",
    href
  }, linkProps))), moduleHrefs.map((href) => /* @__PURE__ */ reactExports.createElement("link", _extends$1({
    key: href,
    rel: "modulepreload",
    href
  }, linkProps))), keyedPrefetchLinks.map(({
    key,
    link
  }) => (
    // these don't spread `linkProps` because they are full link descriptors
    // already with their own props
    /* @__PURE__ */ reactExports.createElement("link", _extends$1({
      key
    }, link))
  )));
}
function Meta() {
  let {
    isSpaMode: isSpaMode2,
    routeModules
  } = useRemixContext();
  let {
    errors,
    matches: routerMatches,
    loaderData
  } = useDataRouterStateContext();
  let location = useLocation();
  let _matches = getActiveMatches(routerMatches, errors, isSpaMode2);
  let error2 = null;
  if (errors) {
    error2 = errors[_matches[_matches.length - 1].route.id];
  }
  let meta2 = [];
  let leafMeta = null;
  let matches = [];
  for (let i2 = 0; i2 < _matches.length; i2++) {
    let _match = _matches[i2];
    let routeId = _match.route.id;
    let data = loaderData[routeId];
    let params = _match.params;
    let routeModule = routeModules[routeId];
    let routeMeta = [];
    let match = {
      id: routeId,
      data,
      meta: [],
      params: _match.params,
      pathname: _match.pathname,
      handle: _match.route.handle,
      error: error2
    };
    matches[i2] = match;
    if (routeModule !== null && routeModule !== void 0 && routeModule.meta) {
      routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
        data,
        params,
        location,
        matches,
        error: error2
      }) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
    } else if (leafMeta) {
      routeMeta = [...leafMeta];
    }
    routeMeta = routeMeta || [];
    if (!Array.isArray(routeMeta)) {
      throw new Error("The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://remix.run/route/meta");
    }
    match.meta = routeMeta;
    matches[i2] = match;
    meta2 = [...routeMeta];
    leafMeta = meta2;
  }
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, meta2.flat().map((metaProps) => {
    if (!metaProps) {
      return null;
    }
    if ("tagName" in metaProps) {
      let {
        tagName,
        ...rest
      } = metaProps;
      if (!isValidMetaTag(tagName)) {
        console.warn(`A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`);
        return null;
      }
      let Comp = tagName;
      return /* @__PURE__ */ reactExports.createElement(Comp, _extends$1({
        key: JSON.stringify(rest)
      }, rest));
    }
    if ("title" in metaProps) {
      return /* @__PURE__ */ reactExports.createElement("title", {
        key: "title"
      }, String(metaProps.title));
    }
    if ("charset" in metaProps) {
      metaProps.charSet ?? (metaProps.charSet = metaProps.charset);
      delete metaProps.charset;
    }
    if ("charSet" in metaProps && metaProps.charSet != null) {
      return typeof metaProps.charSet === "string" ? /* @__PURE__ */ reactExports.createElement("meta", {
        key: "charSet",
        charSet: metaProps.charSet
      }) : null;
    }
    if ("script:ld+json" in metaProps) {
      try {
        let json3 = JSON.stringify(metaProps["script:ld+json"]);
        return /* @__PURE__ */ reactExports.createElement("script", {
          key: `script:ld+json:${json3}`,
          type: "application/ld+json",
          dangerouslySetInnerHTML: {
            __html: escapeHtml(json3)
          }
        });
      } catch (err) {
        return null;
      }
    }
    return /* @__PURE__ */ reactExports.createElement("meta", _extends$1({
      key: JSON.stringify(metaProps)
    }, metaProps));
  }));
}
function isValidMetaTag(tagName) {
  return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
}
function Await(props) {
  return /* @__PURE__ */ reactExports.createElement(Await$1, props);
}
let isHydrated = false;
function Scripts(props) {
  let {
    manifest,
    serverHandoffString,
    abortDelay,
    serializeError: serializeError2,
    isSpaMode: isSpaMode2,
    future: future2,
    renderMeta
  } = useRemixContext();
  let {
    router,
    static: isStatic,
    staticContext
  } = useDataRouterContext();
  let {
    matches: routerMatches
  } = useDataRouterStateContext();
  let enableFogOfWar = isFogOfWarEnabled(future2, isSpaMode2);
  if (renderMeta) {
    renderMeta.didRenderScripts = true;
  }
  let matches = getActiveMatches(routerMatches, null, isSpaMode2);
  reactExports.useEffect(() => {
    isHydrated = true;
  }, []);
  let serializePreResolvedErrorImp = (key, error2) => {
    let toSerialize;
    if (serializeError2 && error2 instanceof Error) {
      toSerialize = serializeError2(error2);
    } else {
      toSerialize = error2;
    }
    return `${JSON.stringify(key)}:__remixContext.p(!1, ${escapeHtml(JSON.stringify(toSerialize))})`;
  };
  let serializePreresolvedDataImp = (routeId, key, data) => {
    let serializedData;
    try {
      serializedData = JSON.stringify(data);
    } catch (error2) {
      return serializePreResolvedErrorImp(key, error2);
    }
    return `${JSON.stringify(key)}:__remixContext.p(${escapeHtml(serializedData)})`;
  };
  let serializeErrorImp = (routeId, key, error2) => {
    let toSerialize;
    if (serializeError2 && error2 instanceof Error) {
      toSerialize = serializeError2(error2);
    } else {
      toSerialize = error2;
    }
    return `__remixContext.r(${JSON.stringify(routeId)}, ${JSON.stringify(key)}, !1, ${escapeHtml(JSON.stringify(toSerialize))})`;
  };
  let serializeDataImp = (routeId, key, data) => {
    let serializedData;
    try {
      serializedData = JSON.stringify(data);
    } catch (error2) {
      return serializeErrorImp(routeId, key, error2);
    }
    return `__remixContext.r(${JSON.stringify(routeId)}, ${JSON.stringify(key)}, ${escapeHtml(serializedData)})`;
  };
  let deferredScripts = [];
  let initialScripts = reactExports.useMemo(() => {
    var _manifest$hmr;
    let streamScript = future2.v3_singleFetch ? (
      // prettier-ignore
      "window.__remixContext.stream = new ReadableStream({start(controller){window.__remixContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());"
    ) : "";
    let contextScript = staticContext ? `window.__remixContext = ${serverHandoffString};${streamScript}` : " ";
    let activeDeferreds = future2.v3_singleFetch ? void 0 : staticContext === null || staticContext === void 0 ? void 0 : staticContext.activeDeferreds;
    contextScript += !activeDeferreds ? "" : ["__remixContext.p = function(v,e,p,x) {", "  if (typeof e !== 'undefined') {", '    x=new Error("Unexpected Server Error");\n    x.stack=undefined;', "    p=Promise.reject(x);", "  } else {", "    p=Promise.resolve(v);", "  }", "  return p;", "};", "__remixContext.n = function(i,k) {", "  __remixContext.t = __remixContext.t || {};", "  __remixContext.t[i] = __remixContext.t[i] || {};", "  let p = new Promise((r, e) => {__remixContext.t[i][k] = {r:(v)=>{r(v);},e:(v)=>{e(v);}};});", typeof abortDelay === "number" ? `setTimeout(() => {if(typeof p._error !== "undefined" || typeof p._data !== "undefined"){return;} __remixContext.t[i][k].e(new Error("Server timeout."))}, ${abortDelay});` : "", "  return p;", "};", "__remixContext.r = function(i,k,v,e,p,x) {", "  p = __remixContext.t[i][k];", "  if (typeof e !== 'undefined') {", '    x=new Error("Unexpected Server Error");\n    x.stack=undefined;', "    p.e(x);", "  } else {", "    p.r(v);", "  }", "};"].join("\n") + Object.entries(activeDeferreds).map(([routeId, deferredData]) => {
      let pendingKeys = new Set(deferredData.pendingKeys);
      let promiseKeyValues = deferredData.deferredKeys.map((key) => {
        if (pendingKeys.has(key)) {
          deferredScripts.push(/* @__PURE__ */ reactExports.createElement(DeferredHydrationScript, {
            key: `${routeId} | ${key}`,
            deferredData,
            routeId,
            dataKey: key,
            scriptProps: props,
            serializeData: serializeDataImp,
            serializeError: serializeErrorImp
          }));
          return `${JSON.stringify(key)}:__remixContext.n(${JSON.stringify(routeId)}, ${JSON.stringify(key)})`;
        } else {
          let trackedPromise = deferredData.data[key];
          if (typeof trackedPromise._error !== "undefined") {
            return serializePreResolvedErrorImp(key, trackedPromise._error);
          } else {
            return serializePreresolvedDataImp(routeId, key, trackedPromise._data);
          }
        }
      }).join(",\n");
      return `Object.assign(__remixContext.state.loaderData[${JSON.stringify(routeId)}], {${promiseKeyValues}});`;
    }).join("\n") + (deferredScripts.length > 0 ? `__remixContext.a=${deferredScripts.length};` : "");
    let routeModulesScript = !isStatic ? " " : `${(_manifest$hmr = manifest.hmr) !== null && _manifest$hmr !== void 0 && _manifest$hmr.runtime ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${enableFogOfWar ? "" : `import ${JSON.stringify(manifest.url)}`};
${matches.map((match, index) => `import * as route${index} from ${JSON.stringify(manifest.routes[match.route.id].module)};`).join("\n")}
${enableFogOfWar ? (
      // Inline a minimal manifest with the SSR matches
      `window.__remixManifest = ${JSON.stringify(getPartialManifest(manifest, router), null, 2)};`
    ) : ""}
window.__remixRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};

import(${JSON.stringify(manifest.entry.module)});`;
    return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, props, {
      suppressHydrationWarning: true,
      dangerouslySetInnerHTML: createHtml(contextScript),
      type: void 0
    })), /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, props, {
      suppressHydrationWarning: true,
      dangerouslySetInnerHTML: createHtml(routeModulesScript),
      type: "module",
      async: true
    })));
  }, []);
  if (!isStatic && typeof __remixContext === "object" && __remixContext.a) {
    for (let i2 = 0; i2 < __remixContext.a; i2++) {
      deferredScripts.push(/* @__PURE__ */ reactExports.createElement(DeferredHydrationScript, {
        key: i2,
        scriptProps: props,
        serializeData: serializeDataImp,
        serializeError: serializeErrorImp
      }));
    }
  }
  let routePreloads = matches.map((match) => {
    let route = manifest.routes[match.route.id];
    return (route.imports || []).concat([route.module]);
  }).flat(1);
  let preloads = isHydrated ? [] : manifest.entry.imports.concat(routePreloads);
  return isHydrated ? null : /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, !enableFogOfWar ? /* @__PURE__ */ reactExports.createElement("link", {
    rel: "modulepreload",
    href: manifest.url,
    crossOrigin: props.crossOrigin
  }) : null, /* @__PURE__ */ reactExports.createElement("link", {
    rel: "modulepreload",
    href: manifest.entry.module,
    crossOrigin: props.crossOrigin
  }), dedupe(preloads).map((path) => /* @__PURE__ */ reactExports.createElement("link", {
    key: path,
    rel: "modulepreload",
    href: path,
    crossOrigin: props.crossOrigin
  })), initialScripts, deferredScripts);
}
function DeferredHydrationScript({
  dataKey,
  deferredData,
  routeId,
  scriptProps,
  serializeData,
  serializeError: serializeError2
}) {
  if (typeof document === "undefined" && deferredData && dataKey && routeId) {
    invariant(deferredData.pendingKeys.includes(dataKey), `Deferred data for route ${routeId} with key ${dataKey} was not pending but tried to render a script for it.`);
  }
  return /* @__PURE__ */ reactExports.createElement(reactExports.Suspense, {
    fallback: (
      // This makes absolutely no sense. The server renders null as a fallback,
      // but when hydrating, we need to render a script tag to avoid a hydration issue.
      // To reproduce a hydration mismatch, just render null as a fallback.
      typeof document === "undefined" && deferredData && dataKey && routeId ? null : /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, scriptProps, {
        async: true,
        suppressHydrationWarning: true,
        dangerouslySetInnerHTML: {
          __html: " "
        }
      }))
    )
  }, typeof document === "undefined" && deferredData && dataKey && routeId ? /* @__PURE__ */ reactExports.createElement(Await, {
    resolve: deferredData.data[dataKey],
    errorElement: /* @__PURE__ */ reactExports.createElement(ErrorDeferredHydrationScript, {
      dataKey,
      routeId,
      scriptProps,
      serializeError: serializeError2
    }),
    children: (data) => {
      return /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, scriptProps, {
        async: true,
        suppressHydrationWarning: true,
        dangerouslySetInnerHTML: {
          __html: serializeData(routeId, dataKey, data)
        }
      }));
    }
  }) : /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, scriptProps, {
    async: true,
    suppressHydrationWarning: true,
    dangerouslySetInnerHTML: {
      __html: " "
    }
  })));
}
function ErrorDeferredHydrationScript({
  dataKey,
  routeId,
  scriptProps,
  serializeError: serializeError2
}) {
  let error2 = useAsyncError();
  return /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, scriptProps, {
    suppressHydrationWarning: true,
    dangerouslySetInnerHTML: {
      __html: serializeError2(routeId, dataKey, error2)
    }
  }));
}
function dedupe(array) {
  return [...new Set(array)];
}
function useMatches() {
  return useMatches$1();
}
function useLoaderData() {
  return useLoaderData$1();
}
function useActionData() {
  return useActionData$1();
}
function useFetcher(opts = {}) {
  return useFetcher$1(opts);
}
function mergeRefs(...refs) {
  return (value) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref != null) {
        ref.current = value;
      }
    });
  };
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
let STORAGE_KEY = "positions";
function ScrollRestoration({
  getKey,
  ...props
}) {
  let {
    isSpaMode: isSpaMode2
  } = useRemixContext();
  let location = useLocation();
  let matches = useMatches$1();
  useScrollRestoration({
    getKey,
    storageKey: STORAGE_KEY
  });
  let key = reactExports.useMemo(
    () => {
      if (!getKey) return null;
      let userKey = getKey(location, matches);
      return userKey !== location.key ? userKey : null;
    },
    // Nah, we only need this the first time for the SSR render
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );
  if (isSpaMode2) {
    return null;
  }
  let restoreScroll = ((STORAGE_KEY2, restoreKey) => {
    if (!window.history.state || !window.history.state.key) {
      let key2 = Math.random().toString(32).slice(2);
      window.history.replaceState({
        key: key2
      }, "");
    }
    try {
      let positions = JSON.parse(sessionStorage.getItem(STORAGE_KEY2) || "{}");
      let storedY = positions[restoreKey || window.history.state.key];
      if (typeof storedY === "number") {
        window.scrollTo(0, storedY);
      }
    } catch (error2) {
      console.error(error2);
      sessionStorage.removeItem(STORAGE_KEY2);
    }
  }).toString();
  return /* @__PURE__ */ reactExports.createElement("script", _extends$1({}, props, {
    suppressHydrationWarning: true,
    dangerouslySetInnerHTML: {
      __html: `(${restoreScroll})(${escapeHtml(JSON.stringify(STORAGE_KEY))}, ${escapeHtml(JSON.stringify(key))})`
    }
  }));
}
function StaticRouterProvider({
  context: context2,
  router,
  hydrate = true,
  nonce
}) {
  !(router && context2) ? invariant$2(false) : void 0;
  let dataRouterContext = {
    router,
    navigator: getStatelessNavigator(),
    static: true,
    staticContext: context2,
    basename: context2.basename || "/"
  };
  let fetchersContext = /* @__PURE__ */ new Map();
  let hydrateScript = "";
  if (hydrate !== false) {
    let data = {
      loaderData: context2.loaderData,
      actionData: context2.actionData,
      errors: serializeErrors(context2.errors)
    };
    let json3 = htmlEscape(JSON.stringify(JSON.stringify(data)));
    hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json3});`;
  }
  let {
    state
  } = dataRouterContext.router;
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(DataRouterContext.Provider, {
    value: dataRouterContext
  }, /* @__PURE__ */ reactExports.createElement(DataRouterStateContext.Provider, {
    value: state
  }, /* @__PURE__ */ reactExports.createElement(FetchersContext.Provider, {
    value: fetchersContext
  }, /* @__PURE__ */ reactExports.createElement(ViewTransitionContext.Provider, {
    value: {
      isTransitioning: false
    }
  }, /* @__PURE__ */ reactExports.createElement(Router, {
    basename: dataRouterContext.basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: dataRouterContext.navigator,
    static: dataRouterContext.static,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, /* @__PURE__ */ reactExports.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state
  })))))), hydrateScript ? /* @__PURE__ */ reactExports.createElement("script", {
    suppressHydrationWarning: true,
    nonce,
    dangerouslySetInnerHTML: {
      __html: hydrateScript
    }
  }) : null);
}
function DataRoutes({
  routes: routes2,
  future: future2,
  state
}) {
  return useRoutesImpl(routes2, void 0, state, future2);
}
function serializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    if (isRouteErrorResponse(val)) {
      serialized[key] = {
        ...val,
        __type: "RouteErrorResponse"
      };
    } else if (val instanceof Error) {
      serialized[key] = {
        message: val.message,
        __type: "Error",
        // If this is a subclass (i.e., ReferenceError), send up the type so we
        // can re-create the same type during hydration.
        ...val.name !== "Error" ? {
          __subType: val.name
        } : {}
      };
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
function getStatelessNavigator() {
  return {
    createHref,
    encodeLocation,
    push(to) {
      throw new Error(`You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
    },
    replace(to) {
      throw new Error(`You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere in your app.`);
    },
    go(delta) {
      throw new Error(`You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${delta})\` somewhere in your app.`);
    },
    back() {
      throw new Error(`You cannot use navigator.back() on the server because it is a stateless environment.`);
    },
    forward() {
      throw new Error(`You cannot use navigator.forward() on the server because it is a stateless environment.`);
    }
  };
}
function createStaticRouter(routes2, context2, opts = {}) {
  let manifest = {};
  let dataRoutes = convertRoutesToDataRoutes(routes2, mapRouteProperties, void 0, manifest);
  let matches = context2.matches.map((match) => {
    let route = manifest[match.route.id] || match.route;
    return {
      ...match,
      route
    };
  });
  let msg = (method) => `You cannot use router.${method}() on the server because it is a stateless environment`;
  return {
    get basename() {
      return context2.basename;
    },
    get future() {
      var _a2, _b2;
      return {
        v7_fetcherPersist: false,
        v7_normalizeFormMethod: false,
        v7_partialHydration: ((_a2 = opts.future) == null ? void 0 : _a2.v7_partialHydration) === true,
        v7_prependBasename: false,
        v7_relativeSplatPath: ((_b2 = opts.future) == null ? void 0 : _b2.v7_relativeSplatPath) === true,
        v7_skipActionErrorRevalidation: false
      };
    },
    get state() {
      return {
        historyAction: Action.Pop,
        location: context2.location,
        matches,
        loaderData: context2.loaderData,
        actionData: context2.actionData,
        errors: context2.errors,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        restoreScrollPosition: null,
        preventScrollReset: false,
        revalidation: "idle",
        fetchers: /* @__PURE__ */ new Map(),
        blockers: /* @__PURE__ */ new Map()
      };
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return void 0;
    },
    initialize() {
      throw msg("initialize");
    },
    subscribe() {
      throw msg("subscribe");
    },
    enableScrollRestoration() {
      throw msg("enableScrollRestoration");
    },
    navigate() {
      throw msg("navigate");
    },
    fetch() {
      throw msg("fetch");
    },
    revalidate() {
      throw msg("revalidate");
    },
    createHref,
    encodeLocation,
    getFetcher() {
      return IDLE_FETCHER;
    },
    deleteFetcher() {
      throw msg("deleteFetcher");
    },
    dispose() {
      throw msg("dispose");
    },
    getBlocker() {
      return IDLE_BLOCKER;
    },
    deleteBlocker() {
      throw msg("deleteBlocker");
    },
    patchRoutes() {
      throw msg("patchRoutes");
    },
    _internalFetchControllers: /* @__PURE__ */ new Map(),
    _internalActiveDeferreds: /* @__PURE__ */ new Map(),
    _internalSetRoutes() {
      throw msg("_internalSetRoutes");
    }
  };
}
function createHref(to) {
  return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
  let href = typeof to === "string" ? to : createPath(to);
  href = href.replace(/ $/, "%20");
  let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
  return {
    pathname: encoded.pathname,
    search: encoded.search,
    hash: encoded.hash
  };
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const ESCAPE_LOOKUP = {
  "&": "\\u0026",
  ">": "\\u003e",
  "<": "\\u003c",
  "\u2028": "\\u2028",
  "\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function htmlEscape(str) {
  return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
/**
 * @remix-run/react v2.17.4
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function RemixServer({
  context: context2,
  url,
  abortDelay,
  nonce
}) {
  if (typeof url === "string") {
    url = new URL(url);
  }
  let {
    manifest,
    routeModules,
    criticalCss,
    serverHandoffString
  } = context2;
  let routes2 = createServerRoutes(manifest.routes, routeModules, context2.future, context2.isSpaMode);
  context2.staticHandlerContext.loaderData = {
    ...context2.staticHandlerContext.loaderData
  };
  for (let match of context2.staticHandlerContext.matches) {
    let routeId = match.route.id;
    let route = routeModules[routeId];
    let manifestRoute = context2.manifest.routes[routeId];
    if (route && shouldHydrateRouteLoader(manifestRoute, route, context2.isSpaMode) && (route.HydrateFallback || !manifestRoute.hasLoader)) {
      context2.staticHandlerContext.loaderData[routeId] = void 0;
    }
  }
  let router = createStaticRouter(routes2, context2.staticHandlerContext, {
    future: {
      v7_partialHydration: true,
      v7_relativeSplatPath: context2.future.v3_relativeSplatPath
    }
  });
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(RemixContext.Provider, {
    value: {
      manifest,
      routeModules,
      criticalCss,
      serverHandoffString,
      future: context2.future,
      isSpaMode: context2.isSpaMode,
      serializeError: context2.serializeError,
      abortDelay,
      renderMeta: context2.renderMeta
    }
  }, /* @__PURE__ */ reactExports.createElement(RemixErrorBoundary, {
    location: router.state.location
  }, /* @__PURE__ */ reactExports.createElement(StaticRouterProvider, {
    router,
    context: context2.staticHandlerContext,
    hydrate: false
  }))), context2.future.v3_singleFetch && context2.serverHandoffStream ? /* @__PURE__ */ reactExports.createElement(reactExports.Suspense, null, /* @__PURE__ */ reactExports.createElement(StreamTransfer, {
    context: context2,
    identifier: 0,
    reader: context2.serverHandoffStream.getReader(),
    textDecoder: new TextDecoder(),
    nonce
  })) : null);
}
var fullPattern = " daum[ /]| deusu/|(?:^|[^g])news(?!sapphire)|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!(?:lib))http|(?<!cam)scan|24x7|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\b\\w+\\.ai|\\bmanus-user/|\\bort/|\\bperl\\b|\\bsecurityheaders\\b|\\btime/|\\||^[\\w \\.\\-\\(?:\\):%]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[^ ]{50,}$|^\\d+\\b|^\\W|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^\\w+/\\d\\.\\d\\s\\([\\w@]+\\)$|^active|^ad muncher|^amaya|^apache/|^avsdevicesdk/|^azure|^biglotron|^bot|^bw/|^clamav[ /]|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^email|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^igetter/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d\\s[\\w\\.-]+$|^mozilla/\\d\\.\\d\\s\\((?:compatible;)?(?:\\s?[\\w\\d-.]+\\/\\d+\\.\\d+)?\\)$|^navermailapp|^netsurf|^offline|^openai/|^owler|^php|^postman|^python|^rank|^read|^reed|^rest|^rss|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^track|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|advisor|agent\\b|analyzer|archive|ask jeeves/teoma|audit|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|convertify|crawl|cypress/|dareboost|datanyze|dejaclick|detect|dmbrowser|download|exaleadcloudview|feed|fetcher|firephp|functionize|grab|headless|httrack|hubspot marketing grader|ibisbrowser|infrawatch|insight|inspect|iplabel|java(?!;)|library|linkcheck|mail\\.ru/|manager|measure|monitor\\b|neustar wpm|node\\b|nutch|offbyone|onetrust|optimize|pageburst|pagespeed|parser|phantomjs|pingdom|powermarks|preview|proxy|ptst[ /]\\d|retriever|rexx;|rigor|rss\\b|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|tools|torrent|transcoder|url|validator|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|xtate/";
var naivePattern = /bot|crawl|http|lighthouse|scan|search|spider/i;
var pattern;
function getPattern() {
  if (pattern instanceof RegExp) {
    return pattern;
  }
  try {
    pattern = new RegExp(fullPattern, "i");
  } catch (error2) {
    pattern = naivePattern;
  }
  return pattern;
}
var isNonEmptyString = (value) => typeof value === "string" && value !== "";
function isbot(userAgent) {
  return isNonEmptyString(userAgent) && getPattern().test(userAgent);
}
var server_browser = {};
var reactDomServerLegacy_browser_production_min = {};
/**
 * @license React
 * react-dom-server-legacy.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactDomServerLegacy_browser_production_min;
function requireReactDomServerLegacy_browser_production_min() {
  if (hasRequiredReactDomServerLegacy_browser_production_min) return reactDomServerLegacy_browser_production_min;
  hasRequiredReactDomServerLegacy_browser_production_min = 1;
  var aa = requireReact();
  function l2(a3) {
    for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a3, c2 = 1; c2 < arguments.length; c2++) b2 += "&args[]=" + encodeURIComponent(arguments[c2]);
    return "Minified React error #" + a3 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  var p2 = Object.prototype.hasOwnProperty, fa = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, ha = {}, ia = {};
  function ja(a3) {
    if (p2.call(ia, a3)) return true;
    if (p2.call(ha, a3)) return false;
    if (fa.test(a3)) return ia[a3] = true;
    ha[a3] = true;
    return false;
  }
  function r2(a3, b2, c2, d2, f2, e2, g2) {
    this.acceptsBooleans = 2 === b2 || 3 === b2 || 4 === b2;
    this.attributeName = d2;
    this.attributeNamespace = f2;
    this.mustUseProperty = c2;
    this.propertyName = a3;
    this.type = b2;
    this.sanitizeURL = e2;
    this.removeEmptyString = g2;
  }
  var t2 = {};
  "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a3) {
    t2[a3] = new r2(a3, 0, false, a3, null, false, false);
  });
  [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a3) {
    var b2 = a3[0];
    t2[b2] = new r2(b2, 1, false, a3[1], null, false, false);
  });
  ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a3) {
    t2[a3] = new r2(a3, 2, false, a3.toLowerCase(), null, false, false);
  });
  ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a3) {
    t2[a3] = new r2(a3, 2, false, a3, null, false, false);
  });
  "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a3) {
    t2[a3] = new r2(a3, 3, false, a3.toLowerCase(), null, false, false);
  });
  ["checked", "multiple", "muted", "selected"].forEach(function(a3) {
    t2[a3] = new r2(a3, 3, true, a3, null, false, false);
  });
  ["capture", "download"].forEach(function(a3) {
    t2[a3] = new r2(a3, 4, false, a3, null, false, false);
  });
  ["cols", "rows", "size", "span"].forEach(function(a3) {
    t2[a3] = new r2(a3, 6, false, a3, null, false, false);
  });
  ["rowSpan", "start"].forEach(function(a3) {
    t2[a3] = new r2(a3, 5, false, a3.toLowerCase(), null, false, false);
  });
  var ka = /[\-:]([a-z])/g;
  function la2(a3) {
    return a3[1].toUpperCase();
  }
  "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a3) {
    var b2 = a3.replace(
      ka,
      la2
    );
    t2[b2] = new r2(b2, 1, false, a3, null, false, false);
  });
  "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a3) {
    var b2 = a3.replace(ka, la2);
    t2[b2] = new r2(b2, 1, false, a3, "http://www.w3.org/1999/xlink", false, false);
  });
  ["xml:base", "xml:lang", "xml:space"].forEach(function(a3) {
    var b2 = a3.replace(ka, la2);
    t2[b2] = new r2(b2, 1, false, a3, "http://www.w3.org/XML/1998/namespace", false, false);
  });
  ["tabIndex", "crossOrigin"].forEach(function(a3) {
    t2[a3] = new r2(a3, 1, false, a3.toLowerCase(), null, false, false);
  });
  t2.xlinkHref = new r2("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
  ["src", "href", "action", "formAction"].forEach(function(a3) {
    t2[a3] = new r2(a3, 1, false, a3.toLowerCase(), null, true, true);
  });
  var u2 = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  }, ma = ["Webkit", "ms", "Moz", "O"];
  Object.keys(u2).forEach(function(a3) {
    ma.forEach(function(b2) {
      b2 = b2 + a3.charAt(0).toUpperCase() + a3.substring(1);
      u2[b2] = u2[a3];
    });
  });
  var na = /["'&<>]/;
  function v5(a3) {
    if ("boolean" === typeof a3 || "number" === typeof a3) return "" + a3;
    a3 = "" + a3;
    var b2 = na.exec(a3);
    if (b2) {
      var c2 = "", d2, f2 = 0;
      for (d2 = b2.index; d2 < a3.length; d2++) {
        switch (a3.charCodeAt(d2)) {
          case 34:
            b2 = "&quot;";
            break;
          case 38:
            b2 = "&amp;";
            break;
          case 39:
            b2 = "&#x27;";
            break;
          case 60:
            b2 = "&lt;";
            break;
          case 62:
            b2 = "&gt;";
            break;
          default:
            continue;
        }
        f2 !== d2 && (c2 += a3.substring(f2, d2));
        f2 = d2 + 1;
        c2 += b2;
      }
      a3 = f2 !== d2 ? c2 + a3.substring(f2, d2) : c2;
    }
    return a3;
  }
  var oa = /([A-Z])/g, pa2 = /^ms-/, qa = Array.isArray;
  function w2(a3, b2) {
    return { insertionMode: a3, selectedValue: b2 };
  }
  function ra(a3, b2, c2) {
    switch (b2) {
      case "select":
        return w2(1, null != c2.value ? c2.value : c2.defaultValue);
      case "svg":
        return w2(2, null);
      case "math":
        return w2(3, null);
      case "foreignObject":
        return w2(1, null);
      case "table":
        return w2(4, null);
      case "thead":
      case "tbody":
      case "tfoot":
        return w2(5, null);
      case "colgroup":
        return w2(7, null);
      case "tr":
        return w2(6, null);
    }
    return 4 <= a3.insertionMode || 0 === a3.insertionMode ? w2(1, null) : a3;
  }
  var sa = /* @__PURE__ */ new Map();
  function ta(a3, b2, c2) {
    if ("object" !== typeof c2) throw Error(l2(62));
    b2 = true;
    for (var d2 in c2) if (p2.call(c2, d2)) {
      var f2 = c2[d2];
      if (null != f2 && "boolean" !== typeof f2 && "" !== f2) {
        if (0 === d2.indexOf("--")) {
          var e2 = v5(d2);
          f2 = v5(("" + f2).trim());
        } else {
          e2 = d2;
          var g2 = sa.get(e2);
          void 0 !== g2 ? e2 = g2 : (g2 = v5(e2.replace(oa, "-$1").toLowerCase().replace(pa2, "-ms-")), sa.set(e2, g2), e2 = g2);
          f2 = "number" === typeof f2 ? 0 === f2 || p2.call(u2, d2) ? "" + f2 : f2 + "px" : v5(("" + f2).trim());
        }
        b2 ? (b2 = false, a3.push(' style="', e2, ":", f2)) : a3.push(";", e2, ":", f2);
      }
    }
    b2 || a3.push('"');
  }
  function x(a3, b2, c2, d2) {
    switch (c2) {
      case "style":
        ta(a3, b2, d2);
        return;
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
        return;
    }
    if (!(2 < c2.length) || "o" !== c2[0] && "O" !== c2[0] || "n" !== c2[1] && "N" !== c2[1]) {
      if (b2 = t2.hasOwnProperty(c2) ? t2[c2] : null, null !== b2) {
        switch (typeof d2) {
          case "function":
          case "symbol":
            return;
          case "boolean":
            if (!b2.acceptsBooleans) return;
        }
        c2 = b2.attributeName;
        switch (b2.type) {
          case 3:
            d2 && a3.push(" ", c2, '=""');
            break;
          case 4:
            true === d2 ? a3.push(" ", c2, '=""') : false !== d2 && a3.push(" ", c2, '="', v5(d2), '"');
            break;
          case 5:
            isNaN(d2) || a3.push(" ", c2, '="', v5(d2), '"');
            break;
          case 6:
            !isNaN(d2) && 1 <= d2 && a3.push(" ", c2, '="', v5(d2), '"');
            break;
          default:
            b2.sanitizeURL && (d2 = "" + d2), a3.push(" ", c2, '="', v5(d2), '"');
        }
      } else if (ja(c2)) {
        switch (typeof d2) {
          case "function":
          case "symbol":
            return;
          case "boolean":
            if (b2 = c2.toLowerCase().slice(0, 5), "data-" !== b2 && "aria-" !== b2) return;
        }
        a3.push(" ", c2, '="', v5(d2), '"');
      }
    }
  }
  function y2(a3, b2, c2) {
    if (null != b2) {
      if (null != c2) throw Error(l2(60));
      if ("object" !== typeof b2 || !("__html" in b2)) throw Error(l2(61));
      b2 = b2.__html;
      null !== b2 && void 0 !== b2 && a3.push("" + b2);
    }
  }
  function ua2(a3) {
    var b2 = "";
    aa.Children.forEach(a3, function(a4) {
      null != a4 && (b2 += a4);
    });
    return b2;
  }
  function va(a3, b2, c2, d2) {
    a3.push(A2(c2));
    var f2 = c2 = null, e2;
    for (e2 in b2) if (p2.call(b2, e2)) {
      var g2 = b2[e2];
      if (null != g2) switch (e2) {
        case "children":
          c2 = g2;
          break;
        case "dangerouslySetInnerHTML":
          f2 = g2;
          break;
        default:
          x(a3, d2, e2, g2);
      }
    }
    a3.push(">");
    y2(a3, f2, c2);
    return "string" === typeof c2 ? (a3.push(v5(c2)), null) : c2;
  }
  var wa = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, xa = /* @__PURE__ */ new Map();
  function A2(a3) {
    var b2 = xa.get(a3);
    if (void 0 === b2) {
      if (!wa.test(a3)) throw Error(l2(65, a3));
      b2 = "<" + a3;
      xa.set(a3, b2);
    }
    return b2;
  }
  function ya(a3, b2, c2, d2, f2) {
    switch (b2) {
      case "select":
        a3.push(A2("select"));
        var e2 = null, g2 = null;
        for (n2 in c2) if (p2.call(c2, n2)) {
          var h2 = c2[n2];
          if (null != h2) switch (n2) {
            case "children":
              e2 = h2;
              break;
            case "dangerouslySetInnerHTML":
              g2 = h2;
              break;
            case "defaultValue":
            case "value":
              break;
            default:
              x(a3, d2, n2, h2);
          }
        }
        a3.push(">");
        y2(a3, g2, e2);
        return e2;
      case "option":
        g2 = f2.selectedValue;
        a3.push(A2("option"));
        var k2 = h2 = null, m2 = null;
        var n2 = null;
        for (e2 in c2) if (p2.call(c2, e2)) {
          var q3 = c2[e2];
          if (null != q3) switch (e2) {
            case "children":
              h2 = q3;
              break;
            case "selected":
              m2 = q3;
              break;
            case "dangerouslySetInnerHTML":
              n2 = q3;
              break;
            case "value":
              k2 = q3;
            default:
              x(a3, d2, e2, q3);
          }
        }
        if (null != g2) if (c2 = null !== k2 ? "" + k2 : ua2(h2), qa(g2)) for (d2 = 0; d2 < g2.length; d2++) {
          if ("" + g2[d2] === c2) {
            a3.push(' selected=""');
            break;
          }
        }
        else "" + g2 === c2 && a3.push(' selected=""');
        else m2 && a3.push(' selected=""');
        a3.push(">");
        y2(a3, n2, h2);
        return h2;
      case "textarea":
        a3.push(A2("textarea"));
        n2 = g2 = e2 = null;
        for (h2 in c2) if (p2.call(c2, h2) && (k2 = c2[h2], null != k2)) switch (h2) {
          case "children":
            n2 = k2;
            break;
          case "value":
            e2 = k2;
            break;
          case "defaultValue":
            g2 = k2;
            break;
          case "dangerouslySetInnerHTML":
            throw Error(l2(91));
          default:
            x(
              a3,
              d2,
              h2,
              k2
            );
        }
        null === e2 && null !== g2 && (e2 = g2);
        a3.push(">");
        if (null != n2) {
          if (null != e2) throw Error(l2(92));
          if (qa(n2) && 1 < n2.length) throw Error(l2(93));
          e2 = "" + n2;
        }
        "string" === typeof e2 && "\n" === e2[0] && a3.push("\n");
        null !== e2 && a3.push(v5("" + e2));
        return null;
      case "input":
        a3.push(A2("input"));
        k2 = n2 = h2 = e2 = null;
        for (g2 in c2) if (p2.call(c2, g2) && (m2 = c2[g2], null != m2)) switch (g2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(l2(399, "input"));
          case "defaultChecked":
            k2 = m2;
            break;
          case "defaultValue":
            h2 = m2;
            break;
          case "checked":
            n2 = m2;
            break;
          case "value":
            e2 = m2;
            break;
          default:
            x(a3, d2, g2, m2);
        }
        null !== n2 ? x(a3, d2, "checked", n2) : null !== k2 && x(a3, d2, "checked", k2);
        null !== e2 ? x(a3, d2, "value", e2) : null !== h2 && x(a3, d2, "value", h2);
        a3.push("/>");
        return null;
      case "menuitem":
        a3.push(A2("menuitem"));
        for (var C2 in c2) if (p2.call(c2, C2) && (e2 = c2[C2], null != e2)) switch (C2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(l2(400));
          default:
            x(a3, d2, C2, e2);
        }
        a3.push(">");
        return null;
      case "title":
        a3.push(A2("title"));
        e2 = null;
        for (q3 in c2) if (p2.call(c2, q3) && (g2 = c2[q3], null != g2)) switch (q3) {
          case "children":
            e2 = g2;
            break;
          case "dangerouslySetInnerHTML":
            throw Error(l2(434));
          default:
            x(a3, d2, q3, g2);
        }
        a3.push(">");
        return e2;
      case "listing":
      case "pre":
        a3.push(A2(b2));
        g2 = e2 = null;
        for (k2 in c2) if (p2.call(c2, k2) && (h2 = c2[k2], null != h2)) switch (k2) {
          case "children":
            e2 = h2;
            break;
          case "dangerouslySetInnerHTML":
            g2 = h2;
            break;
          default:
            x(a3, d2, k2, h2);
        }
        a3.push(">");
        if (null != g2) {
          if (null != e2) throw Error(l2(60));
          if ("object" !== typeof g2 || !("__html" in g2)) throw Error(l2(61));
          c2 = g2.__html;
          null !== c2 && void 0 !== c2 && ("string" === typeof c2 && 0 < c2.length && "\n" === c2[0] ? a3.push("\n", c2) : a3.push("" + c2));
        }
        "string" === typeof e2 && "\n" === e2[0] && a3.push("\n");
        return e2;
      case "area":
      case "base":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "img":
      case "keygen":
      case "link":
      case "meta":
      case "param":
      case "source":
      case "track":
      case "wbr":
        a3.push(A2(b2));
        for (var D2 in c2) if (p2.call(c2, D2) && (e2 = c2[D2], null != e2)) switch (D2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(l2(399, b2));
          default:
            x(a3, d2, D2, e2);
        }
        a3.push("/>");
        return null;
      case "annotation-xml":
      case "color-profile":
      case "font-face":
      case "font-face-src":
      case "font-face-uri":
      case "font-face-format":
      case "font-face-name":
      case "missing-glyph":
        return va(
          a3,
          c2,
          b2,
          d2
        );
      case "html":
        return 0 === f2.insertionMode && a3.push("<!DOCTYPE html>"), va(a3, c2, b2, d2);
      default:
        if (-1 === b2.indexOf("-") && "string" !== typeof c2.is) return va(a3, c2, b2, d2);
        a3.push(A2(b2));
        g2 = e2 = null;
        for (m2 in c2) if (p2.call(c2, m2) && (h2 = c2[m2], null != h2)) switch (m2) {
          case "children":
            e2 = h2;
            break;
          case "dangerouslySetInnerHTML":
            g2 = h2;
            break;
          case "style":
            ta(a3, d2, h2);
            break;
          case "suppressContentEditableWarning":
          case "suppressHydrationWarning":
            break;
          default:
            ja(m2) && "function" !== typeof h2 && "symbol" !== typeof h2 && a3.push(" ", m2, '="', v5(h2), '"');
        }
        a3.push(">");
        y2(a3, g2, e2);
        return e2;
    }
  }
  function za(a3, b2, c2) {
    a3.push('<!--$?--><template id="');
    if (null === c2) throw Error(l2(395));
    a3.push(c2);
    return a3.push('"></template>');
  }
  function Aa(a3, b2, c2, d2) {
    switch (c2.insertionMode) {
      case 0:
      case 1:
        return a3.push('<div hidden id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 2:
        return a3.push('<svg aria-hidden="true" style="display:none" id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 3:
        return a3.push('<math aria-hidden="true" style="display:none" id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 4:
        return a3.push('<table hidden id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 5:
        return a3.push('<table hidden><tbody id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 6:
        return a3.push('<table hidden><tr id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      case 7:
        return a3.push('<table hidden><colgroup id="'), a3.push(b2.segmentPrefix), b2 = d2.toString(16), a3.push(b2), a3.push('">');
      default:
        throw Error(l2(397));
    }
  }
  function Ba(a3, b2) {
    switch (b2.insertionMode) {
      case 0:
      case 1:
        return a3.push("</div>");
      case 2:
        return a3.push("</svg>");
      case 3:
        return a3.push("</math>");
      case 4:
        return a3.push("</table>");
      case 5:
        return a3.push("</tbody></table>");
      case 6:
        return a3.push("</tr></table>");
      case 7:
        return a3.push("</colgroup></table>");
      default:
        throw Error(l2(397));
    }
  }
  var Ca = /[<\u2028\u2029]/g;
  function Da(a3) {
    return JSON.stringify(a3).replace(Ca, function(a4) {
      switch (a4) {
        case "<":
          return "\\u003c";
        case "\u2028":
          return "\\u2028";
        case "\u2029":
          return "\\u2029";
        default:
          throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");
      }
    });
  }
  function Ea(a3, b2) {
    b2 = void 0 === b2 ? "" : b2;
    return { bootstrapChunks: [], startInlineScript: "<script>", placeholderPrefix: b2 + "P:", segmentPrefix: b2 + "S:", boundaryPrefix: b2 + "B:", idPrefix: b2, nextSuspenseID: 0, sentCompleteSegmentFunction: false, sentCompleteBoundaryFunction: false, sentClientRenderFunction: false, generateStaticMarkup: a3 };
  }
  function Fa(a3, b2, c2, d2) {
    if (c2.generateStaticMarkup) return a3.push(v5(b2)), false;
    "" === b2 ? a3 = d2 : (d2 && a3.push("<!-- -->"), a3.push(v5(b2)), a3 = true);
    return a3;
  }
  var B = Object.assign, Ga = Symbol.for("react.element"), Ha = Symbol.for("react.portal"), Ia = Symbol.for("react.fragment"), Ja = Symbol.for("react.strict_mode"), Ka = Symbol.for("react.profiler"), La = Symbol.for("react.provider"), Ma = Symbol.for("react.context"), Na = Symbol.for("react.forward_ref"), Oa = Symbol.for("react.suspense"), Pa = Symbol.for("react.suspense_list"), Qa = Symbol.for("react.memo"), Ra = Symbol.for("react.lazy"), Sa = Symbol.for("react.scope"), Ta = Symbol.for("react.debug_trace_mode"), Ua = Symbol.for("react.legacy_hidden"), Va = Symbol.for("react.default_value"), Wa = Symbol.iterator;
  function Xa(a3) {
    if (null == a3) return null;
    if ("function" === typeof a3) return a3.displayName || a3.name || null;
    if ("string" === typeof a3) return a3;
    switch (a3) {
      case Ia:
        return "Fragment";
      case Ha:
        return "Portal";
      case Ka:
        return "Profiler";
      case Ja:
        return "StrictMode";
      case Oa:
        return "Suspense";
      case Pa:
        return "SuspenseList";
    }
    if ("object" === typeof a3) switch (a3.$$typeof) {
      case Ma:
        return (a3.displayName || "Context") + ".Consumer";
      case La:
        return (a3._context.displayName || "Context") + ".Provider";
      case Na:
        var b2 = a3.render;
        a3 = a3.displayName;
        a3 || (a3 = b2.displayName || b2.name || "", a3 = "" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
        return a3;
      case Qa:
        return b2 = a3.displayName || null, null !== b2 ? b2 : Xa(a3.type) || "Memo";
      case Ra:
        b2 = a3._payload;
        a3 = a3._init;
        try {
          return Xa(a3(b2));
        } catch (c2) {
        }
    }
    return null;
  }
  var Ya = {};
  function Za(a3, b2) {
    a3 = a3.contextTypes;
    if (!a3) return Ya;
    var c2 = {}, d2;
    for (d2 in a3) c2[d2] = b2[d2];
    return c2;
  }
  var E2 = null;
  function F2(a3, b2) {
    if (a3 !== b2) {
      a3.context._currentValue2 = a3.parentValue;
      a3 = a3.parent;
      var c2 = b2.parent;
      if (null === a3) {
        if (null !== c2) throw Error(l2(401));
      } else {
        if (null === c2) throw Error(l2(401));
        F2(a3, c2);
      }
      b2.context._currentValue2 = b2.value;
    }
  }
  function $a(a3) {
    a3.context._currentValue2 = a3.parentValue;
    a3 = a3.parent;
    null !== a3 && $a(a3);
  }
  function ab(a3) {
    var b2 = a3.parent;
    null !== b2 && ab(b2);
    a3.context._currentValue2 = a3.value;
  }
  function bb(a3, b2) {
    a3.context._currentValue2 = a3.parentValue;
    a3 = a3.parent;
    if (null === a3) throw Error(l2(402));
    a3.depth === b2.depth ? F2(a3, b2) : bb(a3, b2);
  }
  function cb(a3, b2) {
    var c2 = b2.parent;
    if (null === c2) throw Error(l2(402));
    a3.depth === c2.depth ? F2(a3, c2) : cb(a3, c2);
    b2.context._currentValue2 = b2.value;
  }
  function G2(a3) {
    var b2 = E2;
    b2 !== a3 && (null === b2 ? ab(a3) : null === a3 ? $a(b2) : b2.depth === a3.depth ? F2(b2, a3) : b2.depth > a3.depth ? bb(b2, a3) : cb(b2, a3), E2 = a3);
  }
  var db = { isMounted: function() {
    return false;
  }, enqueueSetState: function(a3, b2) {
    a3 = a3._reactInternals;
    null !== a3.queue && a3.queue.push(b2);
  }, enqueueReplaceState: function(a3, b2) {
    a3 = a3._reactInternals;
    a3.replace = true;
    a3.queue = [b2];
  }, enqueueForceUpdate: function() {
  } };
  function eb(a3, b2, c2, d2) {
    var f2 = void 0 !== a3.state ? a3.state : null;
    a3.updater = db;
    a3.props = c2;
    a3.state = f2;
    var e2 = { queue: [], replace: false };
    a3._reactInternals = e2;
    var g2 = b2.contextType;
    a3.context = "object" === typeof g2 && null !== g2 ? g2._currentValue2 : d2;
    g2 = b2.getDerivedStateFromProps;
    "function" === typeof g2 && (g2 = g2(c2, f2), f2 = null === g2 || void 0 === g2 ? f2 : B({}, f2, g2), a3.state = f2);
    if ("function" !== typeof b2.getDerivedStateFromProps && "function" !== typeof a3.getSnapshotBeforeUpdate && ("function" === typeof a3.UNSAFE_componentWillMount || "function" === typeof a3.componentWillMount)) if (b2 = a3.state, "function" === typeof a3.componentWillMount && a3.componentWillMount(), "function" === typeof a3.UNSAFE_componentWillMount && a3.UNSAFE_componentWillMount(), b2 !== a3.state && db.enqueueReplaceState(a3, a3.state, null), null !== e2.queue && 0 < e2.queue.length) if (b2 = e2.queue, g2 = e2.replace, e2.queue = null, e2.replace = false, g2 && 1 === b2.length) a3.state = b2[0];
    else {
      e2 = g2 ? b2[0] : a3.state;
      f2 = true;
      for (g2 = g2 ? 1 : 0; g2 < b2.length; g2++) {
        var h2 = b2[g2];
        h2 = "function" === typeof h2 ? h2.call(a3, e2, c2, d2) : h2;
        null != h2 && (f2 ? (f2 = false, e2 = B({}, e2, h2)) : B(e2, h2));
      }
      a3.state = e2;
    }
    else e2.queue = null;
  }
  var fb = { id: 1, overflow: "" };
  function gb(a3, b2, c2) {
    var d2 = a3.id;
    a3 = a3.overflow;
    var f2 = 32 - H2(d2) - 1;
    d2 &= ~(1 << f2);
    c2 += 1;
    var e2 = 32 - H2(b2) + f2;
    if (30 < e2) {
      var g2 = f2 - f2 % 5;
      e2 = (d2 & (1 << g2) - 1).toString(32);
      d2 >>= g2;
      f2 -= g2;
      return { id: 1 << 32 - H2(b2) + f2 | c2 << f2 | d2, overflow: e2 + a3 };
    }
    return { id: 1 << e2 | c2 << f2 | d2, overflow: a3 };
  }
  var H2 = Math.clz32 ? Math.clz32 : hb, ib = Math.log, jb = Math.LN2;
  function hb(a3) {
    a3 >>>= 0;
    return 0 === a3 ? 32 : 31 - (ib(a3) / jb | 0) | 0;
  }
  function kb(a3, b2) {
    return a3 === b2 && (0 !== a3 || 1 / a3 === 1 / b2) || a3 !== a3 && b2 !== b2;
  }
  var lb = "function" === typeof Object.is ? Object.is : kb, I2 = null, ob = null, J2 = null, K2 = null, L2 = false, M2 = false, N2 = 0, O2 = null, P2 = 0;
  function Q2() {
    if (null === I2) throw Error(l2(321));
    return I2;
  }
  function pb() {
    if (0 < P2) throw Error(l2(312));
    return { memoizedState: null, queue: null, next: null };
  }
  function qb() {
    null === K2 ? null === J2 ? (L2 = false, J2 = K2 = pb()) : (L2 = true, K2 = J2) : null === K2.next ? (L2 = false, K2 = K2.next = pb()) : (L2 = true, K2 = K2.next);
    return K2;
  }
  function rb() {
    ob = I2 = null;
    M2 = false;
    J2 = null;
    P2 = 0;
    K2 = O2 = null;
  }
  function sb(a3, b2) {
    return "function" === typeof b2 ? b2(a3) : b2;
  }
  function tb(a3, b2, c2) {
    I2 = Q2();
    K2 = qb();
    if (L2) {
      var d2 = K2.queue;
      b2 = d2.dispatch;
      if (null !== O2 && (c2 = O2.get(d2), void 0 !== c2)) {
        O2.delete(d2);
        d2 = K2.memoizedState;
        do
          d2 = a3(d2, c2.action), c2 = c2.next;
        while (null !== c2);
        K2.memoizedState = d2;
        return [d2, b2];
      }
      return [K2.memoizedState, b2];
    }
    a3 = a3 === sb ? "function" === typeof b2 ? b2() : b2 : void 0 !== c2 ? c2(b2) : b2;
    K2.memoizedState = a3;
    a3 = K2.queue = { last: null, dispatch: null };
    a3 = a3.dispatch = ub.bind(null, I2, a3);
    return [K2.memoizedState, a3];
  }
  function vb(a3, b2) {
    I2 = Q2();
    K2 = qb();
    b2 = void 0 === b2 ? null : b2;
    if (null !== K2) {
      var c2 = K2.memoizedState;
      if (null !== c2 && null !== b2) {
        var d2 = c2[1];
        a: if (null === d2) d2 = false;
        else {
          for (var f2 = 0; f2 < d2.length && f2 < b2.length; f2++) if (!lb(b2[f2], d2[f2])) {
            d2 = false;
            break a;
          }
          d2 = true;
        }
        if (d2) return c2[0];
      }
    }
    a3 = a3();
    K2.memoizedState = [a3, b2];
    return a3;
  }
  function ub(a3, b2, c2) {
    if (25 <= P2) throw Error(l2(301));
    if (a3 === I2) if (M2 = true, a3 = { action: c2, next: null }, null === O2 && (O2 = /* @__PURE__ */ new Map()), c2 = O2.get(b2), void 0 === c2) O2.set(b2, a3);
    else {
      for (b2 = c2; null !== b2.next; ) b2 = b2.next;
      b2.next = a3;
    }
  }
  function wb() {
    throw Error(l2(394));
  }
  function R2() {
  }
  var xb = { readContext: function(a3) {
    return a3._currentValue2;
  }, useContext: function(a3) {
    Q2();
    return a3._currentValue2;
  }, useMemo: vb, useReducer: tb, useRef: function(a3) {
    I2 = Q2();
    K2 = qb();
    var b2 = K2.memoizedState;
    return null === b2 ? (a3 = { current: a3 }, K2.memoizedState = a3) : b2;
  }, useState: function(a3) {
    return tb(sb, a3);
  }, useInsertionEffect: R2, useLayoutEffect: function() {
  }, useCallback: function(a3, b2) {
    return vb(function() {
      return a3;
    }, b2);
  }, useImperativeHandle: R2, useEffect: R2, useDebugValue: R2, useDeferredValue: function(a3) {
    Q2();
    return a3;
  }, useTransition: function() {
    Q2();
    return [
      false,
      wb
    ];
  }, useId: function() {
    var a3 = ob.treeContext;
    var b2 = a3.overflow;
    a3 = a3.id;
    a3 = (a3 & ~(1 << 32 - H2(a3) - 1)).toString(32) + b2;
    var c2 = S2;
    if (null === c2) throw Error(l2(404));
    b2 = N2++;
    a3 = ":" + c2.idPrefix + "R" + a3;
    0 < b2 && (a3 += "H" + b2.toString(32));
    return a3 + ":";
  }, useMutableSource: function(a3, b2) {
    Q2();
    return b2(a3._source);
  }, useSyncExternalStore: function(a3, b2, c2) {
    if (void 0 === c2) throw Error(l2(407));
    return c2();
  } }, S2 = null, yb = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;
  function zb(a3) {
    console.error(a3);
    return null;
  }
  function T3() {
  }
  function Ab(a3, b2, c2, d2, f2, e2, g2, h2, k2) {
    var m2 = [], n2 = /* @__PURE__ */ new Set();
    b2 = { destination: null, responseState: b2, progressiveChunkSize: void 0 === d2 ? 12800 : d2, status: 0, fatalError: null, nextSegmentId: 0, allPendingTasks: 0, pendingRootTasks: 0, completedRootSegment: null, abortableTasks: n2, pingedTasks: m2, clientRenderedBoundaries: [], completedBoundaries: [], partialBoundaries: [], onError: void 0 === f2 ? zb : f2, onAllReady: T3, onShellReady: void 0 === g2 ? T3 : g2, onShellError: T3, onFatalError: T3 };
    c2 = U2(b2, 0, null, c2, false, false);
    c2.parentFlushed = true;
    a3 = Bb(b2, a3, null, c2, n2, Ya, null, fb);
    m2.push(a3);
    return b2;
  }
  function Bb(a3, b2, c2, d2, f2, e2, g2, h2) {
    a3.allPendingTasks++;
    null === c2 ? a3.pendingRootTasks++ : c2.pendingTasks++;
    var k2 = { node: b2, ping: function() {
      var b3 = a3.pingedTasks;
      b3.push(k2);
      1 === b3.length && Cb(a3);
    }, blockedBoundary: c2, blockedSegment: d2, abortSet: f2, legacyContext: e2, context: g2, treeContext: h2 };
    f2.add(k2);
    return k2;
  }
  function U2(a3, b2, c2, d2, f2, e2) {
    return { status: 0, id: -1, index: b2, parentFlushed: false, chunks: [], children: [], formatContext: d2, boundary: c2, lastPushedText: f2, textEmbedded: e2 };
  }
  function V2(a3, b2) {
    a3 = a3.onError(b2);
    if (null != a3 && "string" !== typeof a3) throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + typeof a3 + '" instead');
    return a3;
  }
  function W2(a3, b2) {
    var c2 = a3.onShellError;
    c2(b2);
    c2 = a3.onFatalError;
    c2(b2);
    null !== a3.destination ? (a3.status = 2, a3.destination.destroy(b2)) : (a3.status = 1, a3.fatalError = b2);
  }
  function Db(a3, b2, c2, d2, f2) {
    I2 = {};
    ob = b2;
    N2 = 0;
    for (a3 = c2(d2, f2); M2; ) M2 = false, N2 = 0, P2 += 1, K2 = null, a3 = c2(d2, f2);
    rb();
    return a3;
  }
  function Eb(a3, b2, c2, d2) {
    var f2 = c2.render(), e2 = d2.childContextTypes;
    if (null !== e2 && void 0 !== e2) {
      var g2 = b2.legacyContext;
      if ("function" !== typeof c2.getChildContext) d2 = g2;
      else {
        c2 = c2.getChildContext();
        for (var h2 in c2) if (!(h2 in e2)) throw Error(l2(108, Xa(d2) || "Unknown", h2));
        d2 = B({}, g2, c2);
      }
      b2.legacyContext = d2;
      X2(a3, b2, f2);
      b2.legacyContext = g2;
    } else X2(a3, b2, f2);
  }
  function Fb(a3, b2) {
    if (a3 && a3.defaultProps) {
      b2 = B({}, b2);
      a3 = a3.defaultProps;
      for (var c2 in a3) void 0 === b2[c2] && (b2[c2] = a3[c2]);
      return b2;
    }
    return b2;
  }
  function Gb(a3, b2, c2, d2, f2) {
    if ("function" === typeof c2) if (c2.prototype && c2.prototype.isReactComponent) {
      f2 = Za(c2, b2.legacyContext);
      var e2 = c2.contextType;
      e2 = new c2(d2, "object" === typeof e2 && null !== e2 ? e2._currentValue2 : f2);
      eb(e2, c2, d2, f2);
      Eb(a3, b2, e2, c2);
    } else {
      e2 = Za(c2, b2.legacyContext);
      f2 = Db(a3, b2, c2, d2, e2);
      var g2 = 0 !== N2;
      if ("object" === typeof f2 && null !== f2 && "function" === typeof f2.render && void 0 === f2.$$typeof) eb(f2, c2, d2, e2), Eb(a3, b2, f2, c2);
      else if (g2) {
        d2 = b2.treeContext;
        b2.treeContext = gb(d2, 1, 0);
        try {
          X2(a3, b2, f2);
        } finally {
          b2.treeContext = d2;
        }
      } else X2(a3, b2, f2);
    }
    else if ("string" === typeof c2) {
      f2 = b2.blockedSegment;
      e2 = ya(f2.chunks, c2, d2, a3.responseState, f2.formatContext);
      f2.lastPushedText = false;
      g2 = f2.formatContext;
      f2.formatContext = ra(g2, c2, d2);
      Hb(a3, b2, e2);
      f2.formatContext = g2;
      switch (c2) {
        case "area":
        case "base":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "img":
        case "input":
        case "keygen":
        case "link":
        case "meta":
        case "param":
        case "source":
        case "track":
        case "wbr":
          break;
        default:
          f2.chunks.push("</", c2, ">");
      }
      f2.lastPushedText = false;
    } else {
      switch (c2) {
        case Ua:
        case Ta:
        case Ja:
        case Ka:
        case Ia:
          X2(a3, b2, d2.children);
          return;
        case Pa:
          X2(a3, b2, d2.children);
          return;
        case Sa:
          throw Error(l2(343));
        case Oa:
          a: {
            c2 = b2.blockedBoundary;
            f2 = b2.blockedSegment;
            e2 = d2.fallback;
            d2 = d2.children;
            g2 = /* @__PURE__ */ new Set();
            var h2 = { id: null, rootSegmentID: -1, parentFlushed: false, pendingTasks: 0, forceClientRender: false, completedSegments: [], byteSize: 0, fallbackAbortableTasks: g2, errorDigest: null }, k2 = U2(a3, f2.chunks.length, h2, f2.formatContext, false, false);
            f2.children.push(k2);
            f2.lastPushedText = false;
            var m2 = U2(a3, 0, null, f2.formatContext, false, false);
            m2.parentFlushed = true;
            b2.blockedBoundary = h2;
            b2.blockedSegment = m2;
            try {
              if (Hb(
                a3,
                b2,
                d2
              ), a3.responseState.generateStaticMarkup || m2.lastPushedText && m2.textEmbedded && m2.chunks.push("<!-- -->"), m2.status = 1, Y2(h2, m2), 0 === h2.pendingTasks) break a;
            } catch (n2) {
              m2.status = 4, h2.forceClientRender = true, h2.errorDigest = V2(a3, n2);
            } finally {
              b2.blockedBoundary = c2, b2.blockedSegment = f2;
            }
            b2 = Bb(a3, e2, c2, k2, g2, b2.legacyContext, b2.context, b2.treeContext);
            a3.pingedTasks.push(b2);
          }
          return;
      }
      if ("object" === typeof c2 && null !== c2) switch (c2.$$typeof) {
        case Na:
          d2 = Db(a3, b2, c2.render, d2, f2);
          if (0 !== N2) {
            c2 = b2.treeContext;
            b2.treeContext = gb(c2, 1, 0);
            try {
              X2(a3, b2, d2);
            } finally {
              b2.treeContext = c2;
            }
          } else X2(a3, b2, d2);
          return;
        case Qa:
          c2 = c2.type;
          d2 = Fb(c2, d2);
          Gb(a3, b2, c2, d2, f2);
          return;
        case La:
          f2 = d2.children;
          c2 = c2._context;
          d2 = d2.value;
          e2 = c2._currentValue2;
          c2._currentValue2 = d2;
          g2 = E2;
          E2 = d2 = { parent: g2, depth: null === g2 ? 0 : g2.depth + 1, context: c2, parentValue: e2, value: d2 };
          b2.context = d2;
          X2(a3, b2, f2);
          a3 = E2;
          if (null === a3) throw Error(l2(403));
          d2 = a3.parentValue;
          a3.context._currentValue2 = d2 === Va ? a3.context._defaultValue : d2;
          a3 = E2 = a3.parent;
          b2.context = a3;
          return;
        case Ma:
          d2 = d2.children;
          d2 = d2(c2._currentValue2);
          X2(a3, b2, d2);
          return;
        case Ra:
          f2 = c2._init;
          c2 = f2(c2._payload);
          d2 = Fb(c2, d2);
          Gb(
            a3,
            b2,
            c2,
            d2,
            void 0
          );
          return;
      }
      throw Error(l2(130, null == c2 ? c2 : typeof c2, ""));
    }
  }
  function X2(a3, b2, c2) {
    b2.node = c2;
    if ("object" === typeof c2 && null !== c2) {
      switch (c2.$$typeof) {
        case Ga:
          Gb(a3, b2, c2.type, c2.props, c2.ref);
          return;
        case Ha:
          throw Error(l2(257));
        case Ra:
          var d2 = c2._init;
          c2 = d2(c2._payload);
          X2(a3, b2, c2);
          return;
      }
      if (qa(c2)) {
        Ib(a3, b2, c2);
        return;
      }
      null === c2 || "object" !== typeof c2 ? d2 = null : (d2 = Wa && c2[Wa] || c2["@@iterator"], d2 = "function" === typeof d2 ? d2 : null);
      if (d2 && (d2 = d2.call(c2))) {
        c2 = d2.next();
        if (!c2.done) {
          var f2 = [];
          do
            f2.push(c2.value), c2 = d2.next();
          while (!c2.done);
          Ib(a3, b2, f2);
        }
        return;
      }
      a3 = Object.prototype.toString.call(c2);
      throw Error(l2(31, "[object Object]" === a3 ? "object with keys {" + Object.keys(c2).join(", ") + "}" : a3));
    }
    "string" === typeof c2 ? (d2 = b2.blockedSegment, d2.lastPushedText = Fa(b2.blockedSegment.chunks, c2, a3.responseState, d2.lastPushedText)) : "number" === typeof c2 && (d2 = b2.blockedSegment, d2.lastPushedText = Fa(b2.blockedSegment.chunks, "" + c2, a3.responseState, d2.lastPushedText));
  }
  function Ib(a3, b2, c2) {
    for (var d2 = c2.length, f2 = 0; f2 < d2; f2++) {
      var e2 = b2.treeContext;
      b2.treeContext = gb(e2, d2, f2);
      try {
        Hb(a3, b2, c2[f2]);
      } finally {
        b2.treeContext = e2;
      }
    }
  }
  function Hb(a3, b2, c2) {
    var d2 = b2.blockedSegment.formatContext, f2 = b2.legacyContext, e2 = b2.context;
    try {
      return X2(a3, b2, c2);
    } catch (k2) {
      if (rb(), "object" === typeof k2 && null !== k2 && "function" === typeof k2.then) {
        c2 = k2;
        var g2 = b2.blockedSegment, h2 = U2(a3, g2.chunks.length, null, g2.formatContext, g2.lastPushedText, true);
        g2.children.push(h2);
        g2.lastPushedText = false;
        a3 = Bb(a3, b2.node, b2.blockedBoundary, h2, b2.abortSet, b2.legacyContext, b2.context, b2.treeContext).ping;
        c2.then(a3, a3);
        b2.blockedSegment.formatContext = d2;
        b2.legacyContext = f2;
        b2.context = e2;
        G2(e2);
      } else throw b2.blockedSegment.formatContext = d2, b2.legacyContext = f2, b2.context = e2, G2(e2), k2;
    }
  }
  function Jb(a3) {
    var b2 = a3.blockedBoundary;
    a3 = a3.blockedSegment;
    a3.status = 3;
    Kb(this, b2, a3);
  }
  function Lb(a3, b2, c2) {
    var d2 = a3.blockedBoundary;
    a3.blockedSegment.status = 3;
    null === d2 ? (b2.allPendingTasks--, 2 !== b2.status && (b2.status = 2, null !== b2.destination && b2.destination.push(null))) : (d2.pendingTasks--, d2.forceClientRender || (d2.forceClientRender = true, a3 = void 0 === c2 ? Error(l2(432)) : c2, d2.errorDigest = b2.onError(a3), d2.parentFlushed && b2.clientRenderedBoundaries.push(d2)), d2.fallbackAbortableTasks.forEach(function(a4) {
      return Lb(a4, b2, c2);
    }), d2.fallbackAbortableTasks.clear(), b2.allPendingTasks--, 0 === b2.allPendingTasks && (d2 = b2.onAllReady, d2()));
  }
  function Y2(a3, b2) {
    if (0 === b2.chunks.length && 1 === b2.children.length && null === b2.children[0].boundary) {
      var c2 = b2.children[0];
      c2.id = b2.id;
      c2.parentFlushed = true;
      1 === c2.status && Y2(a3, c2);
    } else a3.completedSegments.push(b2);
  }
  function Kb(a3, b2, c2) {
    if (null === b2) {
      if (c2.parentFlushed) {
        if (null !== a3.completedRootSegment) throw Error(l2(389));
        a3.completedRootSegment = c2;
      }
      a3.pendingRootTasks--;
      0 === a3.pendingRootTasks && (a3.onShellError = T3, b2 = a3.onShellReady, b2());
    } else b2.pendingTasks--, b2.forceClientRender || (0 === b2.pendingTasks ? (c2.parentFlushed && 1 === c2.status && Y2(b2, c2), b2.parentFlushed && a3.completedBoundaries.push(b2), b2.fallbackAbortableTasks.forEach(Jb, a3), b2.fallbackAbortableTasks.clear()) : c2.parentFlushed && 1 === c2.status && (Y2(b2, c2), 1 === b2.completedSegments.length && b2.parentFlushed && a3.partialBoundaries.push(b2)));
    a3.allPendingTasks--;
    0 === a3.allPendingTasks && (a3 = a3.onAllReady, a3());
  }
  function Cb(a3) {
    if (2 !== a3.status) {
      var b2 = E2, c2 = yb.current;
      yb.current = xb;
      var d2 = S2;
      S2 = a3.responseState;
      try {
        var f2 = a3.pingedTasks, e2;
        for (e2 = 0; e2 < f2.length; e2++) {
          var g2 = f2[e2];
          var h2 = a3, k2 = g2.blockedSegment;
          if (0 === k2.status) {
            G2(g2.context);
            try {
              X2(h2, g2, g2.node), h2.responseState.generateStaticMarkup || k2.lastPushedText && k2.textEmbedded && k2.chunks.push("<!-- -->"), g2.abortSet.delete(g2), k2.status = 1, Kb(h2, g2.blockedBoundary, k2);
            } catch (z2) {
              if (rb(), "object" === typeof z2 && null !== z2 && "function" === typeof z2.then) {
                var m2 = g2.ping;
                z2.then(m2, m2);
              } else {
                g2.abortSet.delete(g2);
                k2.status = 4;
                var n2 = g2.blockedBoundary, q3 = z2, C2 = V2(h2, q3);
                null === n2 ? W2(h2, q3) : (n2.pendingTasks--, n2.forceClientRender || (n2.forceClientRender = true, n2.errorDigest = C2, n2.parentFlushed && h2.clientRenderedBoundaries.push(n2)));
                h2.allPendingTasks--;
                if (0 === h2.allPendingTasks) {
                  var D2 = h2.onAllReady;
                  D2();
                }
              }
            } finally {
            }
          }
        }
        f2.splice(0, e2);
        null !== a3.destination && Mb(a3, a3.destination);
      } catch (z2) {
        V2(a3, z2), W2(a3, z2);
      } finally {
        S2 = d2, yb.current = c2, c2 === xb && G2(b2);
      }
    }
  }
  function Z2(a3, b2, c2) {
    c2.parentFlushed = true;
    switch (c2.status) {
      case 0:
        var d2 = c2.id = a3.nextSegmentId++;
        c2.lastPushedText = false;
        c2.textEmbedded = false;
        a3 = a3.responseState;
        b2.push('<template id="');
        b2.push(a3.placeholderPrefix);
        a3 = d2.toString(16);
        b2.push(a3);
        return b2.push('"></template>');
      case 1:
        c2.status = 2;
        var f2 = true;
        d2 = c2.chunks;
        var e2 = 0;
        c2 = c2.children;
        for (var g2 = 0; g2 < c2.length; g2++) {
          for (f2 = c2[g2]; e2 < f2.index; e2++) b2.push(d2[e2]);
          f2 = Nb(a3, b2, f2);
        }
        for (; e2 < d2.length - 1; e2++) b2.push(d2[e2]);
        e2 < d2.length && (f2 = b2.push(d2[e2]));
        return f2;
      default:
        throw Error(l2(390));
    }
  }
  function Nb(a3, b2, c2) {
    var d2 = c2.boundary;
    if (null === d2) return Z2(a3, b2, c2);
    d2.parentFlushed = true;
    if (d2.forceClientRender) return a3.responseState.generateStaticMarkup || (d2 = d2.errorDigest, b2.push("<!--$!-->"), b2.push("<template"), d2 && (b2.push(' data-dgst="'), d2 = v5(d2), b2.push(d2), b2.push('"')), b2.push("></template>")), Z2(a3, b2, c2), a3 = a3.responseState.generateStaticMarkup ? true : b2.push("<!--/$-->"), a3;
    if (0 < d2.pendingTasks) {
      d2.rootSegmentID = a3.nextSegmentId++;
      0 < d2.completedSegments.length && a3.partialBoundaries.push(d2);
      var f2 = a3.responseState;
      var e2 = f2.nextSuspenseID++;
      f2 = f2.boundaryPrefix + e2.toString(16);
      d2 = d2.id = f2;
      za(b2, a3.responseState, d2);
      Z2(a3, b2, c2);
      return b2.push("<!--/$-->");
    }
    if (d2.byteSize > a3.progressiveChunkSize) return d2.rootSegmentID = a3.nextSegmentId++, a3.completedBoundaries.push(d2), za(b2, a3.responseState, d2.id), Z2(a3, b2, c2), b2.push("<!--/$-->");
    a3.responseState.generateStaticMarkup || b2.push("<!--$-->");
    c2 = d2.completedSegments;
    if (1 !== c2.length) throw Error(l2(391));
    Nb(a3, b2, c2[0]);
    a3 = a3.responseState.generateStaticMarkup ? true : b2.push("<!--/$-->");
    return a3;
  }
  function Ob(a3, b2, c2) {
    Aa(b2, a3.responseState, c2.formatContext, c2.id);
    Nb(a3, b2, c2);
    return Ba(b2, c2.formatContext);
  }
  function Pb(a3, b2, c2) {
    for (var d2 = c2.completedSegments, f2 = 0; f2 < d2.length; f2++) Qb(a3, b2, c2, d2[f2]);
    d2.length = 0;
    a3 = a3.responseState;
    d2 = c2.id;
    c2 = c2.rootSegmentID;
    b2.push(a3.startInlineScript);
    a3.sentCompleteBoundaryFunction ? b2.push('$RC("') : (a3.sentCompleteBoundaryFunction = true, b2.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'));
    if (null === d2) throw Error(l2(395));
    c2 = c2.toString(16);
    b2.push(d2);
    b2.push('","');
    b2.push(a3.segmentPrefix);
    b2.push(c2);
    return b2.push('")<\/script>');
  }
  function Qb(a3, b2, c2, d2) {
    if (2 === d2.status) return true;
    var f2 = d2.id;
    if (-1 === f2) {
      if (-1 === (d2.id = c2.rootSegmentID)) throw Error(l2(392));
      return Ob(a3, b2, d2);
    }
    Ob(a3, b2, d2);
    a3 = a3.responseState;
    b2.push(a3.startInlineScript);
    a3.sentCompleteSegmentFunction ? b2.push('$RS("') : (a3.sentCompleteSegmentFunction = true, b2.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'));
    b2.push(a3.segmentPrefix);
    f2 = f2.toString(16);
    b2.push(f2);
    b2.push('","');
    b2.push(a3.placeholderPrefix);
    b2.push(f2);
    return b2.push('")<\/script>');
  }
  function Mb(a3, b2) {
    try {
      var c2 = a3.completedRootSegment;
      if (null !== c2 && 0 === a3.pendingRootTasks) {
        Nb(a3, b2, c2);
        a3.completedRootSegment = null;
        var d2 = a3.responseState.bootstrapChunks;
        for (c2 = 0; c2 < d2.length - 1; c2++) b2.push(d2[c2]);
        c2 < d2.length && b2.push(d2[c2]);
      }
      var f2 = a3.clientRenderedBoundaries, e2;
      for (e2 = 0; e2 < f2.length; e2++) {
        var g2 = f2[e2];
        d2 = b2;
        var h2 = a3.responseState, k2 = g2.id, m2 = g2.errorDigest, n2 = g2.errorMessage, q3 = g2.errorComponentStack;
        d2.push(h2.startInlineScript);
        h2.sentClientRenderFunction ? d2.push('$RX("') : (h2.sentClientRenderFunction = true, d2.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'));
        if (null === k2) throw Error(l2(395));
        d2.push(k2);
        d2.push('"');
        if (m2 || n2 || q3) {
          d2.push(",");
          var C2 = Da(m2 || "");
          d2.push(C2);
        }
        if (n2 || q3) {
          d2.push(",");
          var D2 = Da(n2 || "");
          d2.push(D2);
        }
        if (q3) {
          d2.push(",");
          var z2 = Da(q3);
          d2.push(z2);
        }
        if (!d2.push(")<\/script>")) {
          a3.destination = null;
          e2++;
          f2.splice(0, e2);
          return;
        }
      }
      f2.splice(0, e2);
      var ba = a3.completedBoundaries;
      for (e2 = 0; e2 < ba.length; e2++) if (!Pb(a3, b2, ba[e2])) {
        a3.destination = null;
        e2++;
        ba.splice(0, e2);
        return;
      }
      ba.splice(0, e2);
      var ca = a3.partialBoundaries;
      for (e2 = 0; e2 < ca.length; e2++) {
        var mb = ca[e2];
        a: {
          f2 = a3;
          g2 = b2;
          var da2 = mb.completedSegments;
          for (h2 = 0; h2 < da2.length; h2++) if (!Qb(f2, g2, mb, da2[h2])) {
            h2++;
            da2.splice(0, h2);
            var nb = false;
            break a;
          }
          da2.splice(0, h2);
          nb = true;
        }
        if (!nb) {
          a3.destination = null;
          e2++;
          ca.splice(0, e2);
          return;
        }
      }
      ca.splice(0, e2);
      var ea2 = a3.completedBoundaries;
      for (e2 = 0; e2 < ea2.length; e2++) if (!Pb(a3, b2, ea2[e2])) {
        a3.destination = null;
        e2++;
        ea2.splice(0, e2);
        return;
      }
      ea2.splice(0, e2);
    } finally {
      0 === a3.allPendingTasks && 0 === a3.pingedTasks.length && 0 === a3.clientRenderedBoundaries.length && 0 === a3.completedBoundaries.length && b2.push(null);
    }
  }
  function Rb(a3, b2) {
    try {
      var c2 = a3.abortableTasks;
      c2.forEach(function(c3) {
        return Lb(c3, a3, b2);
      });
      c2.clear();
      null !== a3.destination && Mb(a3, a3.destination);
    } catch (d2) {
      V2(a3, d2), W2(a3, d2);
    }
  }
  function Sb() {
  }
  function Tb(a3, b2, c2, d2) {
    var f2 = false, e2 = null, g2 = "", h2 = { push: function(a4) {
      null !== a4 && (g2 += a4);
      return true;
    }, destroy: function(a4) {
      f2 = true;
      e2 = a4;
    } }, k2 = false;
    a3 = Ab(a3, Ea(c2, b2 ? b2.identifierPrefix : void 0), { insertionMode: 1, selectedValue: null }, Infinity, Sb, void 0, function() {
      k2 = true;
    });
    Cb(a3);
    Rb(a3, d2);
    if (1 === a3.status) a3.status = 2, h2.destroy(a3.fatalError);
    else if (2 !== a3.status && null === a3.destination) {
      a3.destination = h2;
      try {
        Mb(a3, h2);
      } catch (m2) {
        V2(a3, m2), W2(a3, m2);
      }
    }
    if (f2) throw e2;
    if (!k2) throw Error(l2(426));
    return g2;
  }
  reactDomServerLegacy_browser_production_min.renderToNodeStream = function() {
    throw Error(l2(207));
  };
  reactDomServerLegacy_browser_production_min.renderToStaticMarkup = function(a3, b2) {
    return Tb(a3, b2, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
  };
  reactDomServerLegacy_browser_production_min.renderToStaticNodeStream = function() {
    throw Error(l2(208));
  };
  reactDomServerLegacy_browser_production_min.renderToString = function(a3, b2) {
    return Tb(a3, b2, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server');
  };
  reactDomServerLegacy_browser_production_min.version = "18.3.1";
  return reactDomServerLegacy_browser_production_min;
}
var reactDomServer_browser_production_min = {};
/**
 * @license React
 * react-dom-server.browser.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactDomServer_browser_production_min;
function requireReactDomServer_browser_production_min() {
  if (hasRequiredReactDomServer_browser_production_min) return reactDomServer_browser_production_min;
  hasRequiredReactDomServer_browser_production_min = 1;
  var aa = requireReact();
  function k2(a3) {
    for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a3, c2 = 1; c2 < arguments.length; c2++) b2 += "&args[]=" + encodeURIComponent(arguments[c2]);
    return "Minified React error #" + a3 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  var l2 = null, n2 = 0;
  function p2(a3, b2) {
    if (0 !== b2.length) if (512 < b2.length) 0 < n2 && (a3.enqueue(new Uint8Array(l2.buffer, 0, n2)), l2 = new Uint8Array(512), n2 = 0), a3.enqueue(b2);
    else {
      var c2 = l2.length - n2;
      c2 < b2.length && (0 === c2 ? a3.enqueue(l2) : (l2.set(b2.subarray(0, c2), n2), a3.enqueue(l2), b2 = b2.subarray(c2)), l2 = new Uint8Array(512), n2 = 0);
      l2.set(b2, n2);
      n2 += b2.length;
    }
  }
  function t2(a3, b2) {
    p2(a3, b2);
    return true;
  }
  function ba(a3) {
    l2 && 0 < n2 && (a3.enqueue(new Uint8Array(l2.buffer, 0, n2)), l2 = null, n2 = 0);
  }
  var ca = new TextEncoder();
  function u2(a3) {
    return ca.encode(a3);
  }
  function w2(a3) {
    return ca.encode(a3);
  }
  function da2(a3, b2) {
    "function" === typeof a3.error ? a3.error(b2) : a3.close();
  }
  var x = Object.prototype.hasOwnProperty, ea2 = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, fa = {}, ha = {};
  function ia(a3) {
    if (x.call(ha, a3)) return true;
    if (x.call(fa, a3)) return false;
    if (ea2.test(a3)) return ha[a3] = true;
    fa[a3] = true;
    return false;
  }
  function y2(a3, b2, c2, d2, f2, e2, g2) {
    this.acceptsBooleans = 2 === b2 || 3 === b2 || 4 === b2;
    this.attributeName = d2;
    this.attributeNamespace = f2;
    this.mustUseProperty = c2;
    this.propertyName = a3;
    this.type = b2;
    this.sanitizeURL = e2;
    this.removeEmptyString = g2;
  }
  var z2 = {};
  "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a3) {
    z2[a3] = new y2(a3, 0, false, a3, null, false, false);
  });
  [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a3) {
    var b2 = a3[0];
    z2[b2] = new y2(b2, 1, false, a3[1], null, false, false);
  });
  ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a3) {
    z2[a3] = new y2(a3, 2, false, a3.toLowerCase(), null, false, false);
  });
  ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a3) {
    z2[a3] = new y2(a3, 2, false, a3, null, false, false);
  });
  "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a3) {
    z2[a3] = new y2(a3, 3, false, a3.toLowerCase(), null, false, false);
  });
  ["checked", "multiple", "muted", "selected"].forEach(function(a3) {
    z2[a3] = new y2(a3, 3, true, a3, null, false, false);
  });
  ["capture", "download"].forEach(function(a3) {
    z2[a3] = new y2(a3, 4, false, a3, null, false, false);
  });
  ["cols", "rows", "size", "span"].forEach(function(a3) {
    z2[a3] = new y2(a3, 6, false, a3, null, false, false);
  });
  ["rowSpan", "start"].forEach(function(a3) {
    z2[a3] = new y2(a3, 5, false, a3.toLowerCase(), null, false, false);
  });
  var ja = /[\-:]([a-z])/g;
  function ka(a3) {
    return a3[1].toUpperCase();
  }
  "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a3) {
    var b2 = a3.replace(
      ja,
      ka
    );
    z2[b2] = new y2(b2, 1, false, a3, null, false, false);
  });
  "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a3) {
    var b2 = a3.replace(ja, ka);
    z2[b2] = new y2(b2, 1, false, a3, "http://www.w3.org/1999/xlink", false, false);
  });
  ["xml:base", "xml:lang", "xml:space"].forEach(function(a3) {
    var b2 = a3.replace(ja, ka);
    z2[b2] = new y2(b2, 1, false, a3, "http://www.w3.org/XML/1998/namespace", false, false);
  });
  ["tabIndex", "crossOrigin"].forEach(function(a3) {
    z2[a3] = new y2(a3, 1, false, a3.toLowerCase(), null, false, false);
  });
  z2.xlinkHref = new y2("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
  ["src", "href", "action", "formAction"].forEach(function(a3) {
    z2[a3] = new y2(a3, 1, false, a3.toLowerCase(), null, true, true);
  });
  var B = {
    animationIterationCount: true,
    aspectRatio: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridArea: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  }, la2 = ["Webkit", "ms", "Moz", "O"];
  Object.keys(B).forEach(function(a3) {
    la2.forEach(function(b2) {
      b2 = b2 + a3.charAt(0).toUpperCase() + a3.substring(1);
      B[b2] = B[a3];
    });
  });
  var oa = /["'&<>]/;
  function C2(a3) {
    if ("boolean" === typeof a3 || "number" === typeof a3) return "" + a3;
    a3 = "" + a3;
    var b2 = oa.exec(a3);
    if (b2) {
      var c2 = "", d2, f2 = 0;
      for (d2 = b2.index; d2 < a3.length; d2++) {
        switch (a3.charCodeAt(d2)) {
          case 34:
            b2 = "&quot;";
            break;
          case 38:
            b2 = "&amp;";
            break;
          case 39:
            b2 = "&#x27;";
            break;
          case 60:
            b2 = "&lt;";
            break;
          case 62:
            b2 = "&gt;";
            break;
          default:
            continue;
        }
        f2 !== d2 && (c2 += a3.substring(f2, d2));
        f2 = d2 + 1;
        c2 += b2;
      }
      a3 = f2 !== d2 ? c2 + a3.substring(f2, d2) : c2;
    }
    return a3;
  }
  var pa2 = /([A-Z])/g, qa = /^ms-/, ra = Array.isArray, sa = w2("<script>"), ta = w2("<\/script>"), ua2 = w2('<script src="'), va = w2('<script type="module" src="'), wa = w2('" async=""><\/script>'), xa = /(<\/|<)(s)(cript)/gi;
  function ya(a3, b2, c2, d2) {
    return "" + b2 + ("s" === c2 ? "\\u0073" : "\\u0053") + d2;
  }
  function za(a3, b2, c2, d2, f2) {
    a3 = void 0 === a3 ? "" : a3;
    b2 = void 0 === b2 ? sa : w2('<script nonce="' + C2(b2) + '">');
    var e2 = [];
    void 0 !== c2 && e2.push(b2, u2(("" + c2).replace(xa, ya)), ta);
    if (void 0 !== d2) for (c2 = 0; c2 < d2.length; c2++) e2.push(ua2, u2(C2(d2[c2])), wa);
    if (void 0 !== f2) for (d2 = 0; d2 < f2.length; d2++) e2.push(va, u2(C2(f2[d2])), wa);
    return { bootstrapChunks: e2, startInlineScript: b2, placeholderPrefix: w2(a3 + "P:"), segmentPrefix: w2(a3 + "S:"), boundaryPrefix: a3 + "B:", idPrefix: a3, nextSuspenseID: 0, sentCompleteSegmentFunction: false, sentCompleteBoundaryFunction: false, sentClientRenderFunction: false };
  }
  function D2(a3, b2) {
    return { insertionMode: a3, selectedValue: b2 };
  }
  function Aa(a3) {
    return D2("http://www.w3.org/2000/svg" === a3 ? 2 : "http://www.w3.org/1998/Math/MathML" === a3 ? 3 : 0, null);
  }
  function Ba(a3, b2, c2) {
    switch (b2) {
      case "select":
        return D2(1, null != c2.value ? c2.value : c2.defaultValue);
      case "svg":
        return D2(2, null);
      case "math":
        return D2(3, null);
      case "foreignObject":
        return D2(1, null);
      case "table":
        return D2(4, null);
      case "thead":
      case "tbody":
      case "tfoot":
        return D2(5, null);
      case "colgroup":
        return D2(7, null);
      case "tr":
        return D2(6, null);
    }
    return 4 <= a3.insertionMode || 0 === a3.insertionMode ? D2(1, null) : a3;
  }
  var Ca = w2("<!-- -->");
  function Da(a3, b2, c2, d2) {
    if ("" === b2) return d2;
    d2 && a3.push(Ca);
    a3.push(u2(C2(b2)));
    return true;
  }
  var Ea = /* @__PURE__ */ new Map(), Fa = w2(' style="'), Ga = w2(":"), Ha = w2(";");
  function Ia(a3, b2, c2) {
    if ("object" !== typeof c2) throw Error(k2(62));
    b2 = true;
    for (var d2 in c2) if (x.call(c2, d2)) {
      var f2 = c2[d2];
      if (null != f2 && "boolean" !== typeof f2 && "" !== f2) {
        if (0 === d2.indexOf("--")) {
          var e2 = u2(C2(d2));
          f2 = u2(C2(("" + f2).trim()));
        } else {
          e2 = d2;
          var g2 = Ea.get(e2);
          void 0 !== g2 ? e2 = g2 : (g2 = w2(C2(e2.replace(pa2, "-$1").toLowerCase().replace(qa, "-ms-"))), Ea.set(e2, g2), e2 = g2);
          f2 = "number" === typeof f2 ? 0 === f2 || x.call(B, d2) ? u2("" + f2) : u2(f2 + "px") : u2(C2(("" + f2).trim()));
        }
        b2 ? (b2 = false, a3.push(Fa, e2, Ga, f2)) : a3.push(Ha, e2, Ga, f2);
      }
    }
    b2 || a3.push(E2);
  }
  var H2 = w2(" "), I2 = w2('="'), E2 = w2('"'), Ja = w2('=""');
  function J2(a3, b2, c2, d2) {
    switch (c2) {
      case "style":
        Ia(a3, b2, d2);
        return;
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
        return;
    }
    if (!(2 < c2.length) || "o" !== c2[0] && "O" !== c2[0] || "n" !== c2[1] && "N" !== c2[1]) {
      if (b2 = z2.hasOwnProperty(c2) ? z2[c2] : null, null !== b2) {
        switch (typeof d2) {
          case "function":
          case "symbol":
            return;
          case "boolean":
            if (!b2.acceptsBooleans) return;
        }
        c2 = u2(b2.attributeName);
        switch (b2.type) {
          case 3:
            d2 && a3.push(H2, c2, Ja);
            break;
          case 4:
            true === d2 ? a3.push(H2, c2, Ja) : false !== d2 && a3.push(H2, c2, I2, u2(C2(d2)), E2);
            break;
          case 5:
            isNaN(d2) || a3.push(H2, c2, I2, u2(C2(d2)), E2);
            break;
          case 6:
            !isNaN(d2) && 1 <= d2 && a3.push(H2, c2, I2, u2(C2(d2)), E2);
            break;
          default:
            b2.sanitizeURL && (d2 = "" + d2), a3.push(H2, c2, I2, u2(C2(d2)), E2);
        }
      } else if (ia(c2)) {
        switch (typeof d2) {
          case "function":
          case "symbol":
            return;
          case "boolean":
            if (b2 = c2.toLowerCase().slice(0, 5), "data-" !== b2 && "aria-" !== b2) return;
        }
        a3.push(H2, u2(c2), I2, u2(C2(d2)), E2);
      }
    }
  }
  var K2 = w2(">"), Ka = w2("/>");
  function L2(a3, b2, c2) {
    if (null != b2) {
      if (null != c2) throw Error(k2(60));
      if ("object" !== typeof b2 || !("__html" in b2)) throw Error(k2(61));
      b2 = b2.__html;
      null !== b2 && void 0 !== b2 && a3.push(u2("" + b2));
    }
  }
  function La(a3) {
    var b2 = "";
    aa.Children.forEach(a3, function(a4) {
      null != a4 && (b2 += a4);
    });
    return b2;
  }
  var Ma = w2(' selected=""');
  function Na(a3, b2, c2, d2) {
    a3.push(M2(c2));
    var f2 = c2 = null, e2;
    for (e2 in b2) if (x.call(b2, e2)) {
      var g2 = b2[e2];
      if (null != g2) switch (e2) {
        case "children":
          c2 = g2;
          break;
        case "dangerouslySetInnerHTML":
          f2 = g2;
          break;
        default:
          J2(a3, d2, e2, g2);
      }
    }
    a3.push(K2);
    L2(a3, f2, c2);
    return "string" === typeof c2 ? (a3.push(u2(C2(c2))), null) : c2;
  }
  var Oa = w2("\n"), Pa = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, Qa = /* @__PURE__ */ new Map();
  function M2(a3) {
    var b2 = Qa.get(a3);
    if (void 0 === b2) {
      if (!Pa.test(a3)) throw Error(k2(65, a3));
      b2 = w2("<" + a3);
      Qa.set(a3, b2);
    }
    return b2;
  }
  var Ra = w2("<!DOCTYPE html>");
  function Sa(a3, b2, c2, d2, f2) {
    switch (b2) {
      case "select":
        a3.push(M2("select"));
        var e2 = null, g2 = null;
        for (r2 in c2) if (x.call(c2, r2)) {
          var h2 = c2[r2];
          if (null != h2) switch (r2) {
            case "children":
              e2 = h2;
              break;
            case "dangerouslySetInnerHTML":
              g2 = h2;
              break;
            case "defaultValue":
            case "value":
              break;
            default:
              J2(a3, d2, r2, h2);
          }
        }
        a3.push(K2);
        L2(a3, g2, e2);
        return e2;
      case "option":
        g2 = f2.selectedValue;
        a3.push(M2("option"));
        var m2 = h2 = null, q3 = null;
        var r2 = null;
        for (e2 in c2) if (x.call(c2, e2)) {
          var v5 = c2[e2];
          if (null != v5) switch (e2) {
            case "children":
              h2 = v5;
              break;
            case "selected":
              q3 = v5;
              break;
            case "dangerouslySetInnerHTML":
              r2 = v5;
              break;
            case "value":
              m2 = v5;
            default:
              J2(a3, d2, e2, v5);
          }
        }
        if (null != g2) if (c2 = null !== m2 ? "" + m2 : La(h2), ra(g2)) for (d2 = 0; d2 < g2.length; d2++) {
          if ("" + g2[d2] === c2) {
            a3.push(Ma);
            break;
          }
        }
        else "" + g2 === c2 && a3.push(Ma);
        else q3 && a3.push(Ma);
        a3.push(K2);
        L2(a3, r2, h2);
        return h2;
      case "textarea":
        a3.push(M2("textarea"));
        r2 = g2 = e2 = null;
        for (h2 in c2) if (x.call(c2, h2) && (m2 = c2[h2], null != m2)) switch (h2) {
          case "children":
            r2 = m2;
            break;
          case "value":
            e2 = m2;
            break;
          case "defaultValue":
            g2 = m2;
            break;
          case "dangerouslySetInnerHTML":
            throw Error(k2(91));
          default:
            J2(a3, d2, h2, m2);
        }
        null === e2 && null !== g2 && (e2 = g2);
        a3.push(K2);
        if (null != r2) {
          if (null != e2) throw Error(k2(92));
          if (ra(r2) && 1 < r2.length) throw Error(k2(93));
          e2 = "" + r2;
        }
        "string" === typeof e2 && "\n" === e2[0] && a3.push(Oa);
        null !== e2 && a3.push(u2(C2("" + e2)));
        return null;
      case "input":
        a3.push(M2("input"));
        m2 = r2 = h2 = e2 = null;
        for (g2 in c2) if (x.call(c2, g2) && (q3 = c2[g2], null != q3)) switch (g2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(k2(399, "input"));
          case "defaultChecked":
            m2 = q3;
            break;
          case "defaultValue":
            h2 = q3;
            break;
          case "checked":
            r2 = q3;
            break;
          case "value":
            e2 = q3;
            break;
          default:
            J2(a3, d2, g2, q3);
        }
        null !== r2 ? J2(
          a3,
          d2,
          "checked",
          r2
        ) : null !== m2 && J2(a3, d2, "checked", m2);
        null !== e2 ? J2(a3, d2, "value", e2) : null !== h2 && J2(a3, d2, "value", h2);
        a3.push(Ka);
        return null;
      case "menuitem":
        a3.push(M2("menuitem"));
        for (var A2 in c2) if (x.call(c2, A2) && (e2 = c2[A2], null != e2)) switch (A2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(k2(400));
          default:
            J2(a3, d2, A2, e2);
        }
        a3.push(K2);
        return null;
      case "title":
        a3.push(M2("title"));
        e2 = null;
        for (v5 in c2) if (x.call(c2, v5) && (g2 = c2[v5], null != g2)) switch (v5) {
          case "children":
            e2 = g2;
            break;
          case "dangerouslySetInnerHTML":
            throw Error(k2(434));
          default:
            J2(a3, d2, v5, g2);
        }
        a3.push(K2);
        return e2;
      case "listing":
      case "pre":
        a3.push(M2(b2));
        g2 = e2 = null;
        for (m2 in c2) if (x.call(c2, m2) && (h2 = c2[m2], null != h2)) switch (m2) {
          case "children":
            e2 = h2;
            break;
          case "dangerouslySetInnerHTML":
            g2 = h2;
            break;
          default:
            J2(a3, d2, m2, h2);
        }
        a3.push(K2);
        if (null != g2) {
          if (null != e2) throw Error(k2(60));
          if ("object" !== typeof g2 || !("__html" in g2)) throw Error(k2(61));
          c2 = g2.__html;
          null !== c2 && void 0 !== c2 && ("string" === typeof c2 && 0 < c2.length && "\n" === c2[0] ? a3.push(Oa, u2(c2)) : a3.push(u2("" + c2)));
        }
        "string" === typeof e2 && "\n" === e2[0] && a3.push(Oa);
        return e2;
      case "area":
      case "base":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "img":
      case "keygen":
      case "link":
      case "meta":
      case "param":
      case "source":
      case "track":
      case "wbr":
        a3.push(M2(b2));
        for (var F2 in c2) if (x.call(c2, F2) && (e2 = c2[F2], null != e2)) switch (F2) {
          case "children":
          case "dangerouslySetInnerHTML":
            throw Error(k2(399, b2));
          default:
            J2(a3, d2, F2, e2);
        }
        a3.push(Ka);
        return null;
      case "annotation-xml":
      case "color-profile":
      case "font-face":
      case "font-face-src":
      case "font-face-uri":
      case "font-face-format":
      case "font-face-name":
      case "missing-glyph":
        return Na(a3, c2, b2, d2);
      case "html":
        return 0 === f2.insertionMode && a3.push(Ra), Na(a3, c2, b2, d2);
      default:
        if (-1 === b2.indexOf("-") && "string" !== typeof c2.is) return Na(a3, c2, b2, d2);
        a3.push(M2(b2));
        g2 = e2 = null;
        for (q3 in c2) if (x.call(c2, q3) && (h2 = c2[q3], null != h2)) switch (q3) {
          case "children":
            e2 = h2;
            break;
          case "dangerouslySetInnerHTML":
            g2 = h2;
            break;
          case "style":
            Ia(a3, d2, h2);
            break;
          case "suppressContentEditableWarning":
          case "suppressHydrationWarning":
            break;
          default:
            ia(q3) && "function" !== typeof h2 && "symbol" !== typeof h2 && a3.push(H2, u2(q3), I2, u2(C2(h2)), E2);
        }
        a3.push(K2);
        L2(a3, g2, e2);
        return e2;
    }
  }
  var Ta = w2("</"), Ua = w2(">"), Va = w2('<template id="'), Wa = w2('"></template>'), Xa = w2("<!--$-->"), Ya = w2('<!--$?--><template id="'), Za = w2('"></template>'), $a = w2("<!--$!-->"), ab = w2("<!--/$-->"), bb = w2("<template"), cb = w2('"'), db = w2(' data-dgst="');
  w2(' data-msg="');
  w2(' data-stck="');
  var eb = w2("></template>");
  function fb(a3, b2, c2) {
    p2(a3, Ya);
    if (null === c2) throw Error(k2(395));
    p2(a3, c2);
    return t2(a3, Za);
  }
  var gb = w2('<div hidden id="'), hb = w2('">'), ib = w2("</div>"), jb = w2('<svg aria-hidden="true" style="display:none" id="'), kb = w2('">'), lb = w2("</svg>"), mb = w2('<math aria-hidden="true" style="display:none" id="'), nb = w2('">'), ob = w2("</math>"), pb = w2('<table hidden id="'), qb = w2('">'), rb = w2("</table>"), sb = w2('<table hidden><tbody id="'), tb = w2('">'), ub = w2("</tbody></table>"), vb = w2('<table hidden><tr id="'), wb = w2('">'), xb = w2("</tr></table>"), yb = w2('<table hidden><colgroup id="'), zb = w2('">'), Ab = w2("</colgroup></table>");
  function Bb(a3, b2, c2, d2) {
    switch (c2.insertionMode) {
      case 0:
      case 1:
        return p2(a3, gb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, hb);
      case 2:
        return p2(a3, jb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, kb);
      case 3:
        return p2(a3, mb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, nb);
      case 4:
        return p2(a3, pb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, qb);
      case 5:
        return p2(a3, sb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, tb);
      case 6:
        return p2(a3, vb), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, wb);
      case 7:
        return p2(
          a3,
          yb
        ), p2(a3, b2.segmentPrefix), p2(a3, u2(d2.toString(16))), t2(a3, zb);
      default:
        throw Error(k2(397));
    }
  }
  function Cb(a3, b2) {
    switch (b2.insertionMode) {
      case 0:
      case 1:
        return t2(a3, ib);
      case 2:
        return t2(a3, lb);
      case 3:
        return t2(a3, ob);
      case 4:
        return t2(a3, rb);
      case 5:
        return t2(a3, ub);
      case 6:
        return t2(a3, xb);
      case 7:
        return t2(a3, Ab);
      default:
        throw Error(k2(397));
    }
  }
  var Db = w2('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'), Eb = w2('$RS("'), Gb = w2('","'), Hb = w2('")<\/script>'), Ib = w2('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'), Jb = w2('$RC("'), Kb = w2('","'), Lb = w2('")<\/script>'), Mb = w2('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'), Nb = w2('$RX("'), Ob = w2('"'), Pb = w2(")<\/script>"), Qb = w2(","), Rb = /[<\u2028\u2029]/g;
  function Sb(a3) {
    return JSON.stringify(a3).replace(Rb, function(a4) {
      switch (a4) {
        case "<":
          return "\\u003c";
        case "\u2028":
          return "\\u2028";
        case "\u2029":
          return "\\u2029";
        default:
          throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React");
      }
    });
  }
  var N2 = Object.assign, Tb = Symbol.for("react.element"), Ub = Symbol.for("react.portal"), Vb = Symbol.for("react.fragment"), Wb = Symbol.for("react.strict_mode"), Xb = Symbol.for("react.profiler"), Yb = Symbol.for("react.provider"), Zb = Symbol.for("react.context"), $b = Symbol.for("react.forward_ref"), ac = Symbol.for("react.suspense"), bc = Symbol.for("react.suspense_list"), cc = Symbol.for("react.memo"), dc = Symbol.for("react.lazy"), ec = Symbol.for("react.scope"), fc = Symbol.for("react.debug_trace_mode"), gc = Symbol.for("react.legacy_hidden"), hc = Symbol.for("react.default_value"), ic = Symbol.iterator;
  function jc(a3) {
    if (null == a3) return null;
    if ("function" === typeof a3) return a3.displayName || a3.name || null;
    if ("string" === typeof a3) return a3;
    switch (a3) {
      case Vb:
        return "Fragment";
      case Ub:
        return "Portal";
      case Xb:
        return "Profiler";
      case Wb:
        return "StrictMode";
      case ac:
        return "Suspense";
      case bc:
        return "SuspenseList";
    }
    if ("object" === typeof a3) switch (a3.$$typeof) {
      case Zb:
        return (a3.displayName || "Context") + ".Consumer";
      case Yb:
        return (a3._context.displayName || "Context") + ".Provider";
      case $b:
        var b2 = a3.render;
        a3 = a3.displayName;
        a3 || (a3 = b2.displayName || b2.name || "", a3 = "" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
        return a3;
      case cc:
        return b2 = a3.displayName || null, null !== b2 ? b2 : jc(a3.type) || "Memo";
      case dc:
        b2 = a3._payload;
        a3 = a3._init;
        try {
          return jc(a3(b2));
        } catch (c2) {
        }
    }
    return null;
  }
  var kc = {};
  function lc(a3, b2) {
    a3 = a3.contextTypes;
    if (!a3) return kc;
    var c2 = {}, d2;
    for (d2 in a3) c2[d2] = b2[d2];
    return c2;
  }
  var O2 = null;
  function P2(a3, b2) {
    if (a3 !== b2) {
      a3.context._currentValue = a3.parentValue;
      a3 = a3.parent;
      var c2 = b2.parent;
      if (null === a3) {
        if (null !== c2) throw Error(k2(401));
      } else {
        if (null === c2) throw Error(k2(401));
        P2(a3, c2);
      }
      b2.context._currentValue = b2.value;
    }
  }
  function mc(a3) {
    a3.context._currentValue = a3.parentValue;
    a3 = a3.parent;
    null !== a3 && mc(a3);
  }
  function nc(a3) {
    var b2 = a3.parent;
    null !== b2 && nc(b2);
    a3.context._currentValue = a3.value;
  }
  function oc(a3, b2) {
    a3.context._currentValue = a3.parentValue;
    a3 = a3.parent;
    if (null === a3) throw Error(k2(402));
    a3.depth === b2.depth ? P2(a3, b2) : oc(a3, b2);
  }
  function pc(a3, b2) {
    var c2 = b2.parent;
    if (null === c2) throw Error(k2(402));
    a3.depth === c2.depth ? P2(a3, c2) : pc(a3, c2);
    b2.context._currentValue = b2.value;
  }
  function Q2(a3) {
    var b2 = O2;
    b2 !== a3 && (null === b2 ? nc(a3) : null === a3 ? mc(b2) : b2.depth === a3.depth ? P2(b2, a3) : b2.depth > a3.depth ? oc(b2, a3) : pc(b2, a3), O2 = a3);
  }
  var qc = { isMounted: function() {
    return false;
  }, enqueueSetState: function(a3, b2) {
    a3 = a3._reactInternals;
    null !== a3.queue && a3.queue.push(b2);
  }, enqueueReplaceState: function(a3, b2) {
    a3 = a3._reactInternals;
    a3.replace = true;
    a3.queue = [b2];
  }, enqueueForceUpdate: function() {
  } };
  function rc(a3, b2, c2, d2) {
    var f2 = void 0 !== a3.state ? a3.state : null;
    a3.updater = qc;
    a3.props = c2;
    a3.state = f2;
    var e2 = { queue: [], replace: false };
    a3._reactInternals = e2;
    var g2 = b2.contextType;
    a3.context = "object" === typeof g2 && null !== g2 ? g2._currentValue : d2;
    g2 = b2.getDerivedStateFromProps;
    "function" === typeof g2 && (g2 = g2(c2, f2), f2 = null === g2 || void 0 === g2 ? f2 : N2({}, f2, g2), a3.state = f2);
    if ("function" !== typeof b2.getDerivedStateFromProps && "function" !== typeof a3.getSnapshotBeforeUpdate && ("function" === typeof a3.UNSAFE_componentWillMount || "function" === typeof a3.componentWillMount)) if (b2 = a3.state, "function" === typeof a3.componentWillMount && a3.componentWillMount(), "function" === typeof a3.UNSAFE_componentWillMount && a3.UNSAFE_componentWillMount(), b2 !== a3.state && qc.enqueueReplaceState(a3, a3.state, null), null !== e2.queue && 0 < e2.queue.length) if (b2 = e2.queue, g2 = e2.replace, e2.queue = null, e2.replace = false, g2 && 1 === b2.length) a3.state = b2[0];
    else {
      e2 = g2 ? b2[0] : a3.state;
      f2 = true;
      for (g2 = g2 ? 1 : 0; g2 < b2.length; g2++) {
        var h2 = b2[g2];
        h2 = "function" === typeof h2 ? h2.call(a3, e2, c2, d2) : h2;
        null != h2 && (f2 ? (f2 = false, e2 = N2({}, e2, h2)) : N2(e2, h2));
      }
      a3.state = e2;
    }
    else e2.queue = null;
  }
  var sc = { id: 1, overflow: "" };
  function tc(a3, b2, c2) {
    var d2 = a3.id;
    a3 = a3.overflow;
    var f2 = 32 - uc(d2) - 1;
    d2 &= ~(1 << f2);
    c2 += 1;
    var e2 = 32 - uc(b2) + f2;
    if (30 < e2) {
      var g2 = f2 - f2 % 5;
      e2 = (d2 & (1 << g2) - 1).toString(32);
      d2 >>= g2;
      f2 -= g2;
      return { id: 1 << 32 - uc(b2) + f2 | c2 << f2 | d2, overflow: e2 + a3 };
    }
    return { id: 1 << e2 | c2 << f2 | d2, overflow: a3 };
  }
  var uc = Math.clz32 ? Math.clz32 : vc, wc = Math.log, xc = Math.LN2;
  function vc(a3) {
    a3 >>>= 0;
    return 0 === a3 ? 32 : 31 - (wc(a3) / xc | 0) | 0;
  }
  function yc(a3, b2) {
    return a3 === b2 && (0 !== a3 || 1 / a3 === 1 / b2) || a3 !== a3 && b2 !== b2;
  }
  var zc = "function" === typeof Object.is ? Object.is : yc, R2 = null, Ac = null, Bc = null, S2 = null, T3 = false, Cc = false, U2 = 0, V2 = null, Dc = 0;
  function W2() {
    if (null === R2) throw Error(k2(321));
    return R2;
  }
  function Ec() {
    if (0 < Dc) throw Error(k2(312));
    return { memoizedState: null, queue: null, next: null };
  }
  function Fc() {
    null === S2 ? null === Bc ? (T3 = false, Bc = S2 = Ec()) : (T3 = true, S2 = Bc) : null === S2.next ? (T3 = false, S2 = S2.next = Ec()) : (T3 = true, S2 = S2.next);
    return S2;
  }
  function Gc() {
    Ac = R2 = null;
    Cc = false;
    Bc = null;
    Dc = 0;
    S2 = V2 = null;
  }
  function Hc(a3, b2) {
    return "function" === typeof b2 ? b2(a3) : b2;
  }
  function Ic(a3, b2, c2) {
    R2 = W2();
    S2 = Fc();
    if (T3) {
      var d2 = S2.queue;
      b2 = d2.dispatch;
      if (null !== V2 && (c2 = V2.get(d2), void 0 !== c2)) {
        V2.delete(d2);
        d2 = S2.memoizedState;
        do
          d2 = a3(d2, c2.action), c2 = c2.next;
        while (null !== c2);
        S2.memoizedState = d2;
        return [d2, b2];
      }
      return [S2.memoizedState, b2];
    }
    a3 = a3 === Hc ? "function" === typeof b2 ? b2() : b2 : void 0 !== c2 ? c2(b2) : b2;
    S2.memoizedState = a3;
    a3 = S2.queue = { last: null, dispatch: null };
    a3 = a3.dispatch = Jc.bind(null, R2, a3);
    return [S2.memoizedState, a3];
  }
  function Kc(a3, b2) {
    R2 = W2();
    S2 = Fc();
    b2 = void 0 === b2 ? null : b2;
    if (null !== S2) {
      var c2 = S2.memoizedState;
      if (null !== c2 && null !== b2) {
        var d2 = c2[1];
        a: if (null === d2) d2 = false;
        else {
          for (var f2 = 0; f2 < d2.length && f2 < b2.length; f2++) if (!zc(b2[f2], d2[f2])) {
            d2 = false;
            break a;
          }
          d2 = true;
        }
        if (d2) return c2[0];
      }
    }
    a3 = a3();
    S2.memoizedState = [a3, b2];
    return a3;
  }
  function Jc(a3, b2, c2) {
    if (25 <= Dc) throw Error(k2(301));
    if (a3 === R2) if (Cc = true, a3 = { action: c2, next: null }, null === V2 && (V2 = /* @__PURE__ */ new Map()), c2 = V2.get(b2), void 0 === c2) V2.set(b2, a3);
    else {
      for (b2 = c2; null !== b2.next; ) b2 = b2.next;
      b2.next = a3;
    }
  }
  function Lc() {
    throw Error(k2(394));
  }
  function Mc() {
  }
  var Oc = { readContext: function(a3) {
    return a3._currentValue;
  }, useContext: function(a3) {
    W2();
    return a3._currentValue;
  }, useMemo: Kc, useReducer: Ic, useRef: function(a3) {
    R2 = W2();
    S2 = Fc();
    var b2 = S2.memoizedState;
    return null === b2 ? (a3 = { current: a3 }, S2.memoizedState = a3) : b2;
  }, useState: function(a3) {
    return Ic(Hc, a3);
  }, useInsertionEffect: Mc, useLayoutEffect: function() {
  }, useCallback: function(a3, b2) {
    return Kc(function() {
      return a3;
    }, b2);
  }, useImperativeHandle: Mc, useEffect: Mc, useDebugValue: Mc, useDeferredValue: function(a3) {
    W2();
    return a3;
  }, useTransition: function() {
    W2();
    return [false, Lc];
  }, useId: function() {
    var a3 = Ac.treeContext;
    var b2 = a3.overflow;
    a3 = a3.id;
    a3 = (a3 & ~(1 << 32 - uc(a3) - 1)).toString(32) + b2;
    var c2 = Nc;
    if (null === c2) throw Error(k2(404));
    b2 = U2++;
    a3 = ":" + c2.idPrefix + "R" + a3;
    0 < b2 && (a3 += "H" + b2.toString(32));
    return a3 + ":";
  }, useMutableSource: function(a3, b2) {
    W2();
    return b2(a3._source);
  }, useSyncExternalStore: function(a3, b2, c2) {
    if (void 0 === c2) throw Error(k2(407));
    return c2();
  } }, Nc = null, Pc = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;
  function Qc(a3) {
    console.error(a3);
    return null;
  }
  function X2() {
  }
  function Rc(a3, b2, c2, d2, f2, e2, g2, h2, m2) {
    var q3 = [], r2 = /* @__PURE__ */ new Set();
    b2 = { destination: null, responseState: b2, progressiveChunkSize: void 0 === d2 ? 12800 : d2, status: 0, fatalError: null, nextSegmentId: 0, allPendingTasks: 0, pendingRootTasks: 0, completedRootSegment: null, abortableTasks: r2, pingedTasks: q3, clientRenderedBoundaries: [], completedBoundaries: [], partialBoundaries: [], onError: void 0 === f2 ? Qc : f2, onAllReady: void 0 === e2 ? X2 : e2, onShellReady: void 0 === g2 ? X2 : g2, onShellError: void 0 === h2 ? X2 : h2, onFatalError: void 0 === m2 ? X2 : m2 };
    c2 = Sc(b2, 0, null, c2, false, false);
    c2.parentFlushed = true;
    a3 = Tc(b2, a3, null, c2, r2, kc, null, sc);
    q3.push(a3);
    return b2;
  }
  function Tc(a3, b2, c2, d2, f2, e2, g2, h2) {
    a3.allPendingTasks++;
    null === c2 ? a3.pendingRootTasks++ : c2.pendingTasks++;
    var m2 = { node: b2, ping: function() {
      var b3 = a3.pingedTasks;
      b3.push(m2);
      1 === b3.length && Uc(a3);
    }, blockedBoundary: c2, blockedSegment: d2, abortSet: f2, legacyContext: e2, context: g2, treeContext: h2 };
    f2.add(m2);
    return m2;
  }
  function Sc(a3, b2, c2, d2, f2, e2) {
    return { status: 0, id: -1, index: b2, parentFlushed: false, chunks: [], children: [], formatContext: d2, boundary: c2, lastPushedText: f2, textEmbedded: e2 };
  }
  function Y2(a3, b2) {
    a3 = a3.onError(b2);
    if (null != a3 && "string" !== typeof a3) throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + typeof a3 + '" instead');
    return a3;
  }
  function Vc(a3, b2) {
    var c2 = a3.onShellError;
    c2(b2);
    c2 = a3.onFatalError;
    c2(b2);
    null !== a3.destination ? (a3.status = 2, da2(a3.destination, b2)) : (a3.status = 1, a3.fatalError = b2);
  }
  function Wc(a3, b2, c2, d2, f2) {
    R2 = {};
    Ac = b2;
    U2 = 0;
    for (a3 = c2(d2, f2); Cc; ) Cc = false, U2 = 0, Dc += 1, S2 = null, a3 = c2(d2, f2);
    Gc();
    return a3;
  }
  function Xc(a3, b2, c2, d2) {
    var f2 = c2.render(), e2 = d2.childContextTypes;
    if (null !== e2 && void 0 !== e2) {
      var g2 = b2.legacyContext;
      if ("function" !== typeof c2.getChildContext) d2 = g2;
      else {
        c2 = c2.getChildContext();
        for (var h2 in c2) if (!(h2 in e2)) throw Error(k2(108, jc(d2) || "Unknown", h2));
        d2 = N2({}, g2, c2);
      }
      b2.legacyContext = d2;
      Z2(a3, b2, f2);
      b2.legacyContext = g2;
    } else Z2(a3, b2, f2);
  }
  function Yc(a3, b2) {
    if (a3 && a3.defaultProps) {
      b2 = N2({}, b2);
      a3 = a3.defaultProps;
      for (var c2 in a3) void 0 === b2[c2] && (b2[c2] = a3[c2]);
      return b2;
    }
    return b2;
  }
  function Zc(a3, b2, c2, d2, f2) {
    if ("function" === typeof c2) if (c2.prototype && c2.prototype.isReactComponent) {
      f2 = lc(c2, b2.legacyContext);
      var e2 = c2.contextType;
      e2 = new c2(d2, "object" === typeof e2 && null !== e2 ? e2._currentValue : f2);
      rc(e2, c2, d2, f2);
      Xc(a3, b2, e2, c2);
    } else {
      e2 = lc(c2, b2.legacyContext);
      f2 = Wc(a3, b2, c2, d2, e2);
      var g2 = 0 !== U2;
      if ("object" === typeof f2 && null !== f2 && "function" === typeof f2.render && void 0 === f2.$$typeof) rc(f2, c2, d2, e2), Xc(a3, b2, f2, c2);
      else if (g2) {
        d2 = b2.treeContext;
        b2.treeContext = tc(d2, 1, 0);
        try {
          Z2(a3, b2, f2);
        } finally {
          b2.treeContext = d2;
        }
      } else Z2(a3, b2, f2);
    }
    else if ("string" === typeof c2) {
      f2 = b2.blockedSegment;
      e2 = Sa(f2.chunks, c2, d2, a3.responseState, f2.formatContext);
      f2.lastPushedText = false;
      g2 = f2.formatContext;
      f2.formatContext = Ba(g2, c2, d2);
      $c(a3, b2, e2);
      f2.formatContext = g2;
      switch (c2) {
        case "area":
        case "base":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "img":
        case "input":
        case "keygen":
        case "link":
        case "meta":
        case "param":
        case "source":
        case "track":
        case "wbr":
          break;
        default:
          f2.chunks.push(Ta, u2(c2), Ua);
      }
      f2.lastPushedText = false;
    } else {
      switch (c2) {
        case gc:
        case fc:
        case Wb:
        case Xb:
        case Vb:
          Z2(a3, b2, d2.children);
          return;
        case bc:
          Z2(a3, b2, d2.children);
          return;
        case ec:
          throw Error(k2(343));
        case ac:
          a: {
            c2 = b2.blockedBoundary;
            f2 = b2.blockedSegment;
            e2 = d2.fallback;
            d2 = d2.children;
            g2 = /* @__PURE__ */ new Set();
            var h2 = { id: null, rootSegmentID: -1, parentFlushed: false, pendingTasks: 0, forceClientRender: false, completedSegments: [], byteSize: 0, fallbackAbortableTasks: g2, errorDigest: null }, m2 = Sc(a3, f2.chunks.length, h2, f2.formatContext, false, false);
            f2.children.push(m2);
            f2.lastPushedText = false;
            var q3 = Sc(a3, 0, null, f2.formatContext, false, false);
            q3.parentFlushed = true;
            b2.blockedBoundary = h2;
            b2.blockedSegment = q3;
            try {
              if ($c(
                a3,
                b2,
                d2
              ), q3.lastPushedText && q3.textEmbedded && q3.chunks.push(Ca), q3.status = 1, ad(h2, q3), 0 === h2.pendingTasks) break a;
            } catch (r2) {
              q3.status = 4, h2.forceClientRender = true, h2.errorDigest = Y2(a3, r2);
            } finally {
              b2.blockedBoundary = c2, b2.blockedSegment = f2;
            }
            b2 = Tc(a3, e2, c2, m2, g2, b2.legacyContext, b2.context, b2.treeContext);
            a3.pingedTasks.push(b2);
          }
          return;
      }
      if ("object" === typeof c2 && null !== c2) switch (c2.$$typeof) {
        case $b:
          d2 = Wc(a3, b2, c2.render, d2, f2);
          if (0 !== U2) {
            c2 = b2.treeContext;
            b2.treeContext = tc(c2, 1, 0);
            try {
              Z2(a3, b2, d2);
            } finally {
              b2.treeContext = c2;
            }
          } else Z2(a3, b2, d2);
          return;
        case cc:
          c2 = c2.type;
          d2 = Yc(c2, d2);
          Zc(a3, b2, c2, d2, f2);
          return;
        case Yb:
          f2 = d2.children;
          c2 = c2._context;
          d2 = d2.value;
          e2 = c2._currentValue;
          c2._currentValue = d2;
          g2 = O2;
          O2 = d2 = { parent: g2, depth: null === g2 ? 0 : g2.depth + 1, context: c2, parentValue: e2, value: d2 };
          b2.context = d2;
          Z2(a3, b2, f2);
          a3 = O2;
          if (null === a3) throw Error(k2(403));
          d2 = a3.parentValue;
          a3.context._currentValue = d2 === hc ? a3.context._defaultValue : d2;
          a3 = O2 = a3.parent;
          b2.context = a3;
          return;
        case Zb:
          d2 = d2.children;
          d2 = d2(c2._currentValue);
          Z2(a3, b2, d2);
          return;
        case dc:
          f2 = c2._init;
          c2 = f2(c2._payload);
          d2 = Yc(c2, d2);
          Zc(a3, b2, c2, d2, void 0);
          return;
      }
      throw Error(k2(
        130,
        null == c2 ? c2 : typeof c2,
        ""
      ));
    }
  }
  function Z2(a3, b2, c2) {
    b2.node = c2;
    if ("object" === typeof c2 && null !== c2) {
      switch (c2.$$typeof) {
        case Tb:
          Zc(a3, b2, c2.type, c2.props, c2.ref);
          return;
        case Ub:
          throw Error(k2(257));
        case dc:
          var d2 = c2._init;
          c2 = d2(c2._payload);
          Z2(a3, b2, c2);
          return;
      }
      if (ra(c2)) {
        bd(a3, b2, c2);
        return;
      }
      null === c2 || "object" !== typeof c2 ? d2 = null : (d2 = ic && c2[ic] || c2["@@iterator"], d2 = "function" === typeof d2 ? d2 : null);
      if (d2 && (d2 = d2.call(c2))) {
        c2 = d2.next();
        if (!c2.done) {
          var f2 = [];
          do
            f2.push(c2.value), c2 = d2.next();
          while (!c2.done);
          bd(a3, b2, f2);
        }
        return;
      }
      a3 = Object.prototype.toString.call(c2);
      throw Error(k2(31, "[object Object]" === a3 ? "object with keys {" + Object.keys(c2).join(", ") + "}" : a3));
    }
    "string" === typeof c2 ? (d2 = b2.blockedSegment, d2.lastPushedText = Da(b2.blockedSegment.chunks, c2, a3.responseState, d2.lastPushedText)) : "number" === typeof c2 && (d2 = b2.blockedSegment, d2.lastPushedText = Da(b2.blockedSegment.chunks, "" + c2, a3.responseState, d2.lastPushedText));
  }
  function bd(a3, b2, c2) {
    for (var d2 = c2.length, f2 = 0; f2 < d2; f2++) {
      var e2 = b2.treeContext;
      b2.treeContext = tc(e2, d2, f2);
      try {
        $c(a3, b2, c2[f2]);
      } finally {
        b2.treeContext = e2;
      }
    }
  }
  function $c(a3, b2, c2) {
    var d2 = b2.blockedSegment.formatContext, f2 = b2.legacyContext, e2 = b2.context;
    try {
      return Z2(a3, b2, c2);
    } catch (m2) {
      if (Gc(), "object" === typeof m2 && null !== m2 && "function" === typeof m2.then) {
        c2 = m2;
        var g2 = b2.blockedSegment, h2 = Sc(a3, g2.chunks.length, null, g2.formatContext, g2.lastPushedText, true);
        g2.children.push(h2);
        g2.lastPushedText = false;
        a3 = Tc(a3, b2.node, b2.blockedBoundary, h2, b2.abortSet, b2.legacyContext, b2.context, b2.treeContext).ping;
        c2.then(a3, a3);
        b2.blockedSegment.formatContext = d2;
        b2.legacyContext = f2;
        b2.context = e2;
        Q2(e2);
      } else throw b2.blockedSegment.formatContext = d2, b2.legacyContext = f2, b2.context = e2, Q2(e2), m2;
    }
  }
  function cd(a3) {
    var b2 = a3.blockedBoundary;
    a3 = a3.blockedSegment;
    a3.status = 3;
    dd(this, b2, a3);
  }
  function ed(a3, b2, c2) {
    var d2 = a3.blockedBoundary;
    a3.blockedSegment.status = 3;
    null === d2 ? (b2.allPendingTasks--, 2 !== b2.status && (b2.status = 2, null !== b2.destination && b2.destination.close())) : (d2.pendingTasks--, d2.forceClientRender || (d2.forceClientRender = true, a3 = void 0 === c2 ? Error(k2(432)) : c2, d2.errorDigest = b2.onError(a3), d2.parentFlushed && b2.clientRenderedBoundaries.push(d2)), d2.fallbackAbortableTasks.forEach(function(a4) {
      return ed(a4, b2, c2);
    }), d2.fallbackAbortableTasks.clear(), b2.allPendingTasks--, 0 === b2.allPendingTasks && (d2 = b2.onAllReady, d2()));
  }
  function ad(a3, b2) {
    if (0 === b2.chunks.length && 1 === b2.children.length && null === b2.children[0].boundary) {
      var c2 = b2.children[0];
      c2.id = b2.id;
      c2.parentFlushed = true;
      1 === c2.status && ad(a3, c2);
    } else a3.completedSegments.push(b2);
  }
  function dd(a3, b2, c2) {
    if (null === b2) {
      if (c2.parentFlushed) {
        if (null !== a3.completedRootSegment) throw Error(k2(389));
        a3.completedRootSegment = c2;
      }
      a3.pendingRootTasks--;
      0 === a3.pendingRootTasks && (a3.onShellError = X2, b2 = a3.onShellReady, b2());
    } else b2.pendingTasks--, b2.forceClientRender || (0 === b2.pendingTasks ? (c2.parentFlushed && 1 === c2.status && ad(b2, c2), b2.parentFlushed && a3.completedBoundaries.push(b2), b2.fallbackAbortableTasks.forEach(cd, a3), b2.fallbackAbortableTasks.clear()) : c2.parentFlushed && 1 === c2.status && (ad(b2, c2), 1 === b2.completedSegments.length && b2.parentFlushed && a3.partialBoundaries.push(b2)));
    a3.allPendingTasks--;
    0 === a3.allPendingTasks && (a3 = a3.onAllReady, a3());
  }
  function Uc(a3) {
    if (2 !== a3.status) {
      var b2 = O2, c2 = Pc.current;
      Pc.current = Oc;
      var d2 = Nc;
      Nc = a3.responseState;
      try {
        var f2 = a3.pingedTasks, e2;
        for (e2 = 0; e2 < f2.length; e2++) {
          var g2 = f2[e2];
          var h2 = a3, m2 = g2.blockedSegment;
          if (0 === m2.status) {
            Q2(g2.context);
            try {
              Z2(h2, g2, g2.node), m2.lastPushedText && m2.textEmbedded && m2.chunks.push(Ca), g2.abortSet.delete(g2), m2.status = 1, dd(h2, g2.blockedBoundary, m2);
            } catch (G2) {
              if (Gc(), "object" === typeof G2 && null !== G2 && "function" === typeof G2.then) {
                var q3 = g2.ping;
                G2.then(q3, q3);
              } else {
                g2.abortSet.delete(g2);
                m2.status = 4;
                var r2 = g2.blockedBoundary, v5 = G2, A2 = Y2(h2, v5);
                null === r2 ? Vc(h2, v5) : (r2.pendingTasks--, r2.forceClientRender || (r2.forceClientRender = true, r2.errorDigest = A2, r2.parentFlushed && h2.clientRenderedBoundaries.push(r2)));
                h2.allPendingTasks--;
                if (0 === h2.allPendingTasks) {
                  var F2 = h2.onAllReady;
                  F2();
                }
              }
            } finally {
            }
          }
        }
        f2.splice(0, e2);
        null !== a3.destination && fd2(a3, a3.destination);
      } catch (G2) {
        Y2(a3, G2), Vc(a3, G2);
      } finally {
        Nc = d2, Pc.current = c2, c2 === Oc && Q2(b2);
      }
    }
  }
  function gd(a3, b2, c2) {
    c2.parentFlushed = true;
    switch (c2.status) {
      case 0:
        var d2 = c2.id = a3.nextSegmentId++;
        c2.lastPushedText = false;
        c2.textEmbedded = false;
        a3 = a3.responseState;
        p2(b2, Va);
        p2(b2, a3.placeholderPrefix);
        a3 = u2(d2.toString(16));
        p2(b2, a3);
        return t2(b2, Wa);
      case 1:
        c2.status = 2;
        var f2 = true;
        d2 = c2.chunks;
        var e2 = 0;
        c2 = c2.children;
        for (var g2 = 0; g2 < c2.length; g2++) {
          for (f2 = c2[g2]; e2 < f2.index; e2++) p2(b2, d2[e2]);
          f2 = hd(a3, b2, f2);
        }
        for (; e2 < d2.length - 1; e2++) p2(b2, d2[e2]);
        e2 < d2.length && (f2 = t2(b2, d2[e2]));
        return f2;
      default:
        throw Error(k2(390));
    }
  }
  function hd(a3, b2, c2) {
    var d2 = c2.boundary;
    if (null === d2) return gd(a3, b2, c2);
    d2.parentFlushed = true;
    if (d2.forceClientRender) d2 = d2.errorDigest, t2(b2, $a), p2(b2, bb), d2 && (p2(b2, db), p2(b2, u2(C2(d2))), p2(b2, cb)), t2(b2, eb), gd(a3, b2, c2);
    else if (0 < d2.pendingTasks) {
      d2.rootSegmentID = a3.nextSegmentId++;
      0 < d2.completedSegments.length && a3.partialBoundaries.push(d2);
      var f2 = a3.responseState;
      var e2 = f2.nextSuspenseID++;
      f2 = w2(f2.boundaryPrefix + e2.toString(16));
      d2 = d2.id = f2;
      fb(b2, a3.responseState, d2);
      gd(a3, b2, c2);
    } else if (d2.byteSize > a3.progressiveChunkSize) d2.rootSegmentID = a3.nextSegmentId++, a3.completedBoundaries.push(d2), fb(b2, a3.responseState, d2.id), gd(a3, b2, c2);
    else {
      t2(b2, Xa);
      c2 = d2.completedSegments;
      if (1 !== c2.length) throw Error(k2(391));
      hd(a3, b2, c2[0]);
    }
    return t2(b2, ab);
  }
  function id(a3, b2, c2) {
    Bb(b2, a3.responseState, c2.formatContext, c2.id);
    hd(a3, b2, c2);
    return Cb(b2, c2.formatContext);
  }
  function jd(a3, b2, c2) {
    for (var d2 = c2.completedSegments, f2 = 0; f2 < d2.length; f2++) kd(a3, b2, c2, d2[f2]);
    d2.length = 0;
    a3 = a3.responseState;
    d2 = c2.id;
    c2 = c2.rootSegmentID;
    p2(b2, a3.startInlineScript);
    a3.sentCompleteBoundaryFunction ? p2(b2, Jb) : (a3.sentCompleteBoundaryFunction = true, p2(b2, Ib));
    if (null === d2) throw Error(k2(395));
    c2 = u2(c2.toString(16));
    p2(b2, d2);
    p2(b2, Kb);
    p2(b2, a3.segmentPrefix);
    p2(b2, c2);
    return t2(b2, Lb);
  }
  function kd(a3, b2, c2, d2) {
    if (2 === d2.status) return true;
    var f2 = d2.id;
    if (-1 === f2) {
      if (-1 === (d2.id = c2.rootSegmentID)) throw Error(k2(392));
      return id(a3, b2, d2);
    }
    id(a3, b2, d2);
    a3 = a3.responseState;
    p2(b2, a3.startInlineScript);
    a3.sentCompleteSegmentFunction ? p2(b2, Eb) : (a3.sentCompleteSegmentFunction = true, p2(b2, Db));
    p2(b2, a3.segmentPrefix);
    f2 = u2(f2.toString(16));
    p2(b2, f2);
    p2(b2, Gb);
    p2(b2, a3.placeholderPrefix);
    p2(b2, f2);
    return t2(b2, Hb);
  }
  function fd2(a3, b2) {
    l2 = new Uint8Array(512);
    n2 = 0;
    try {
      var c2 = a3.completedRootSegment;
      if (null !== c2 && 0 === a3.pendingRootTasks) {
        hd(a3, b2, c2);
        a3.completedRootSegment = null;
        var d2 = a3.responseState.bootstrapChunks;
        for (c2 = 0; c2 < d2.length - 1; c2++) p2(b2, d2[c2]);
        c2 < d2.length && t2(b2, d2[c2]);
      }
      var f2 = a3.clientRenderedBoundaries, e2;
      for (e2 = 0; e2 < f2.length; e2++) {
        var g2 = f2[e2];
        d2 = b2;
        var h2 = a3.responseState, m2 = g2.id, q3 = g2.errorDigest, r2 = g2.errorMessage, v5 = g2.errorComponentStack;
        p2(d2, h2.startInlineScript);
        h2.sentClientRenderFunction ? p2(d2, Nb) : (h2.sentClientRenderFunction = true, p2(
          d2,
          Mb
        ));
        if (null === m2) throw Error(k2(395));
        p2(d2, m2);
        p2(d2, Ob);
        if (q3 || r2 || v5) p2(d2, Qb), p2(d2, u2(Sb(q3 || "")));
        if (r2 || v5) p2(d2, Qb), p2(d2, u2(Sb(r2 || "")));
        v5 && (p2(d2, Qb), p2(d2, u2(Sb(v5))));
        if (!t2(d2, Pb)) ;
      }
      f2.splice(0, e2);
      var A2 = a3.completedBoundaries;
      for (e2 = 0; e2 < A2.length; e2++) if (!jd(a3, b2, A2[e2])) ;
      A2.splice(0, e2);
      ba(b2);
      l2 = new Uint8Array(512);
      n2 = 0;
      var F2 = a3.partialBoundaries;
      for (e2 = 0; e2 < F2.length; e2++) {
        var G2 = F2[e2];
        a: {
          f2 = a3;
          g2 = b2;
          var ma = G2.completedSegments;
          for (h2 = 0; h2 < ma.length; h2++) if (!kd(
            f2,
            g2,
            G2,
            ma[h2]
          )) {
            h2++;
            ma.splice(0, h2);
            var Fb = false;
            break a;
          }
          ma.splice(0, h2);
          Fb = true;
        }
        if (!Fb) {
          a3.destination = null;
          e2++;
          F2.splice(0, e2);
          return;
        }
      }
      F2.splice(0, e2);
      var na = a3.completedBoundaries;
      for (e2 = 0; e2 < na.length; e2++) if (!jd(a3, b2, na[e2])) ;
      na.splice(0, e2);
    } finally {
      ba(b2), 0 === a3.allPendingTasks && 0 === a3.pingedTasks.length && 0 === a3.clientRenderedBoundaries.length && 0 === a3.completedBoundaries.length && b2.close();
    }
  }
  function ld(a3, b2) {
    try {
      var c2 = a3.abortableTasks;
      c2.forEach(function(c3) {
        return ed(c3, a3, b2);
      });
      c2.clear();
      null !== a3.destination && fd2(a3, a3.destination);
    } catch (d2) {
      Y2(a3, d2), Vc(a3, d2);
    }
  }
  reactDomServer_browser_production_min.renderToReadableStream = function(a3, b2) {
    return new Promise(function(c2, d2) {
      var f2, e2, g2 = new Promise(function(a4, b3) {
        e2 = a4;
        f2 = b3;
      }), h2 = Rc(a3, za(b2 ? b2.identifierPrefix : void 0, b2 ? b2.nonce : void 0, b2 ? b2.bootstrapScriptContent : void 0, b2 ? b2.bootstrapScripts : void 0, b2 ? b2.bootstrapModules : void 0), Aa(b2 ? b2.namespaceURI : void 0), b2 ? b2.progressiveChunkSize : void 0, b2 ? b2.onError : void 0, e2, function() {
        var a4 = new ReadableStream({ type: "bytes", pull: function(a5) {
          if (1 === h2.status) h2.status = 2, da2(a5, h2.fatalError);
          else if (2 !== h2.status && null === h2.destination) {
            h2.destination = a5;
            try {
              fd2(h2, a5);
            } catch (A2) {
              Y2(h2, A2), Vc(h2, A2);
            }
          }
        }, cancel: function() {
          ld(h2);
        } }, { highWaterMark: 0 });
        a4.allReady = g2;
        c2(a4);
      }, function(a4) {
        g2.catch(function() {
        });
        d2(a4);
      }, f2);
      if (b2 && b2.signal) {
        var m2 = b2.signal, q3 = function() {
          ld(h2, m2.reason);
          m2.removeEventListener("abort", q3);
        };
        m2.addEventListener("abort", q3);
      }
      Uc(h2);
    });
  };
  reactDomServer_browser_production_min.version = "18.3.1";
  return reactDomServer_browser_production_min;
}
var hasRequiredServer_browser;
function requireServer_browser() {
  if (hasRequiredServer_browser) return server_browser;
  hasRequiredServer_browser = 1;
  var l2, s2;
  {
    l2 = requireReactDomServerLegacy_browser_production_min();
    s2 = requireReactDomServer_browser_production_min();
  }
  server_browser.version = l2.version;
  server_browser.renderToString = l2.renderToString;
  server_browser.renderToStaticMarkup = l2.renderToStaticMarkup;
  server_browser.renderToNodeStream = l2.renderToNodeStream;
  server_browser.renderToStaticNodeStream = l2.renderToStaticNodeStream;
  server_browser.renderToReadableStream = s2.renderToReadableStream;
  return server_browser;
}
var server_browserExports = requireServer_browser();
function flattenConnection(connection) {
  if (!connection) {
    const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${connection ?? ""}' instead.`;
    {
      console.error(noConnectionErr + ` Returning an empty array`);
      return [];
    }
  }
  if ("nodes" in connection) {
    return connection.nodes;
  }
  if ("edges" in connection && Array.isArray(connection.edges)) {
    return connection.edges.map((edge) => {
      if (!(edge == null ? void 0 : edge.node)) {
        throw new Error(
          "flattenConnection(): Connection edges must contain nodes"
        );
      }
      return edge.node;
    });
  }
  return [];
}
const SFAPI_VERSION = "2024-10";
const MOCK_SHOP_DOMAIN = "mock.shop";
const isMockShop = (domain) => domain.includes(MOCK_SHOP_DOMAIN);
function createStorefrontClient({
  storeDomain,
  privateStorefrontToken,
  publicStorefrontToken,
  storefrontApiVersion = SFAPI_VERSION,
  contentType
}) {
  if (!storeDomain) {
    {
      throw new Error(
        H2_PREFIX_ERROR + `\`storeDomain\` is required when creating a new Storefront client in production.`
      );
    }
  }
  if (storefrontApiVersion !== SFAPI_VERSION) {
    warnOnce$1(
      `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.
You may run into unexpected errors if these versions don't match. Received version: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
    );
  }
  const getShopifyDomain = (overrideProps) => {
    const domain = (overrideProps == null ? void 0 : overrideProps.storeDomain) ?? storeDomain;
    return domain.includes("://") ? domain : `https://${domain}`;
  };
  return {
    getShopifyDomain,
    getStorefrontApiUrl(overrideProps) {
      const domain = getShopifyDomain(overrideProps);
      const apiUrl = domain + (domain.endsWith("/") ? "api" : "/api");
      if (isMockShop(domain))
        return apiUrl;
      return `${apiUrl}/${(overrideProps == null ? void 0 : overrideProps.storefrontApiVersion) ?? storefrontApiVersion}/graphql.json`;
    },
    getPrivateTokenHeaders(overrideProps) {
      if (!privateStorefrontToken && !(overrideProps == null ? void 0 : overrideProps.privateStorefrontToken) && !isMockShop(storeDomain)) {
        throw new Error(
          H2_PREFIX_ERROR + "You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`"
        );
      }
      const finalContentType = (overrideProps == null ? void 0 : overrideProps.contentType) ?? contentType;
      return {
        // default to json
        "content-type": finalContentType === "graphql" ? "application/graphql" : "application/json",
        "X-SDK-Variant": "hydrogen-react",
        "X-SDK-Variant-Source": "react",
        "X-SDK-Version": storefrontApiVersion,
        "Shopify-Storefront-Private-Token": (overrideProps == null ? void 0 : overrideProps.privateStorefrontToken) ?? privateStorefrontToken ?? "",
        ...(overrideProps == null ? void 0 : overrideProps.buyerIp) ? { "Shopify-Storefront-Buyer-IP": overrideProps.buyerIp } : {}
      };
    },
    getPublicTokenHeaders(overrideProps) {
      if (!publicStorefrontToken && !(overrideProps == null ? void 0 : overrideProps.publicStorefrontToken) && !isMockShop(storeDomain)) {
        throw new Error(
          H2_PREFIX_ERROR + "You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`"
        );
      }
      const finalContentType = (overrideProps == null ? void 0 : overrideProps.contentType) ?? contentType ?? "json";
      return getPublicTokenHeadersRaw(
        finalContentType,
        storefrontApiVersion,
        (overrideProps == null ? void 0 : overrideProps.publicStorefrontToken) ?? publicStorefrontToken ?? ""
      );
    }
  };
}
function getPublicTokenHeadersRaw(contentType, storefrontApiVersion, accessToken) {
  return {
    // default to json
    "content-type": contentType === "graphql" ? "application/graphql" : "application/json",
    "X-SDK-Variant": "hydrogen-react",
    "X-SDK-Variant-Source": "react",
    "X-SDK-Version": storefrontApiVersion,
    "X-Shopify-Storefront-Access-Token": accessToken
  };
}
const warnings = /* @__PURE__ */ new Set();
const H2_PREFIX_ERROR = "[h2:error:createStorefrontClient] ";
const warnOnce$1 = (string, type = "warn") => {
  if (!warnings.has(string)) {
    console[type](`[h2:${type}:createStorefrontClient] ` + string);
    warnings.add(string);
  }
};
const defaultShopifyContext = {
  storeDomain: "test",
  storefrontToken: "abc123",
  storefrontApiVersion: SFAPI_VERSION,
  countryIsoCode: "US",
  languageIsoCode: "EN",
  getStorefrontApiUrl() {
    return "";
  },
  getPublicTokenHeaders() {
    return {};
  },
  getShopifyDomain() {
    return "";
  }
};
const ShopifyContext = reactExports.createContext(
  defaultShopifyContext
);
function useShop() {
  const shopContext = reactExports.useContext(ShopifyContext);
  if (!shopContext) {
    throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);
  }
  return shopContext;
}
const SHOPIFY_STOREFRONT_ID_HEADER = "Shopify-Storefront-Id";
const SHOPIFY_STOREFRONT_Y_HEADER = "Shopify-Storefront-Y";
const SHOPIFY_STOREFRONT_S_HEADER = "Shopify-Storefront-S";
const SHOPIFY_VISIT_TOKEN_HEADER = "X-Shopify-VisitToken";
const SHOPIFY_UNIQUE_TOKEN_HEADER = "X-Shopify-UniqueToken";
function parseGid(gid) {
  const defaultReturn = {
    id: "",
    resource: null,
    resourceId: null,
    search: "",
    searchParams: new URLSearchParams(),
    hash: ""
  };
  if (typeof gid !== "string") {
    return defaultReturn;
  }
  try {
    const { search, searchParams, pathname, hash } = new URL(gid);
    const pathnameParts = pathname.split("/");
    const lastPathnamePart = pathnameParts[pathnameParts.length - 1];
    const resourcePart = pathnameParts[pathnameParts.length - 2];
    if (!lastPathnamePart || !resourcePart) {
      return defaultReturn;
    }
    const id = `${lastPathnamePart}${search}${hash}` || "";
    const resourceId = lastPathnamePart || null;
    const resource = resourcePart ?? null;
    return { id, resource, resourceId, search, searchParams, hash };
  } catch {
    return defaultReturn;
  }
}
function useMoney(money) {
  const { countryIsoCode, languageIsoCode } = useShop();
  const locale = languageIsoCode.includes("_") ? languageIsoCode.replace("_", "-") : `${languageIsoCode}-${countryIsoCode}`;
  if (!locale) {
    throw new Error(
      `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`
    );
  }
  const amount = parseFloat(money.amount);
  const {
    defaultFormatter,
    nameFormatter,
    narrowSymbolFormatter,
    withoutTrailingZerosFormatter,
    withoutCurrencyFormatter,
    withoutTrailingZerosOrCurrencyFormatter
  } = reactExports.useMemo(() => {
    const options = {
      style: "currency",
      currency: money.currencyCode
    };
    return {
      defaultFormatter: getLazyFormatter(locale, options),
      nameFormatter: getLazyFormatter(locale, {
        ...options,
        currencyDisplay: "name"
      }),
      narrowSymbolFormatter: getLazyFormatter(locale, {
        ...options,
        currencyDisplay: "narrowSymbol"
      }),
      withoutTrailingZerosFormatter: getLazyFormatter(locale, {
        ...options,
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
      }),
      withoutCurrencyFormatter: getLazyFormatter(locale),
      withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
      })
    };
  }, [money.currencyCode, locale]);
  const isPartCurrency = (part) => part.type === "currency";
  const lazyFormatters = reactExports.useMemo(
    () => ({
      original: () => money,
      currencyCode: () => money.currencyCode,
      localizedString: () => defaultFormatter().format(amount),
      parts: () => defaultFormatter().formatToParts(amount),
      withoutTrailingZeros: () => amount % 1 === 0 ? withoutTrailingZerosFormatter().format(amount) : defaultFormatter().format(amount),
      withoutTrailingZerosAndCurrency: () => amount % 1 === 0 ? withoutTrailingZerosOrCurrencyFormatter().format(amount) : withoutCurrencyFormatter().format(amount),
      currencyName: () => {
        var _a2;
        return ((_a2 = nameFormatter().formatToParts(amount).find(isPartCurrency)) == null ? void 0 : _a2.value) ?? money.currencyCode;
      },
      // e.g. "US dollars"
      currencySymbol: () => {
        var _a2;
        return ((_a2 = defaultFormatter().formatToParts(amount).find(isPartCurrency)) == null ? void 0 : _a2.value) ?? money.currencyCode;
      },
      // e.g. "USD"
      currencyNarrowSymbol: () => {
        var _a2;
        return ((_a2 = narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)) == null ? void 0 : _a2.value) ?? "";
      },
      // e.g. "$"
      amount: () => defaultFormatter().formatToParts(amount).filter(
        (part) => ["decimal", "fraction", "group", "integer", "literal"].includes(
          part.type
        )
      ).map((part) => part.value).join("")
    }),
    [
      money,
      amount,
      nameFormatter,
      defaultFormatter,
      narrowSymbolFormatter,
      withoutCurrencyFormatter,
      withoutTrailingZerosFormatter,
      withoutTrailingZerosOrCurrencyFormatter
    ]
  );
  return reactExports.useMemo(
    () => new Proxy(lazyFormatters, {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
      get: (target, key) => {
        var _a2;
        return (_a2 = Reflect.get(target, key)) == null ? void 0 : _a2.call(null);
      }
    }),
    [lazyFormatters]
  );
}
const formatterCache = /* @__PURE__ */ new Map();
function getLazyFormatter(locale, options) {
  const key = JSON.stringify([locale, options]);
  return function() {
    let formatter = formatterCache.get(key);
    if (!formatter) {
      formatter = new Intl.NumberFormat(locale, options);
      formatterCache.set(key, formatter);
    }
    return formatter;
  };
}
function Money({
  data,
  as,
  withoutCurrency,
  withoutTrailingZeros,
  measurement,
  measurementSeparator = "/",
  ...passthroughProps
}) {
  if (!isMoney(data)) {
    throw new Error(
      `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`
    );
  }
  const moneyObject = useMoney(data);
  const Wrapper = as ?? "div";
  let output = moneyObject.localizedString;
  if (withoutCurrency || withoutTrailingZeros) {
    if (withoutCurrency && !withoutTrailingZeros) {
      output = moneyObject.amount;
    } else if (!withoutCurrency && withoutTrailingZeros) {
      output = moneyObject.withoutTrailingZeros;
    } else {
      output = moneyObject.withoutTrailingZerosAndCurrency;
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Wrapper, { ...passthroughProps, children: [
    output,
    measurement && measurement.referenceUnit && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      measurementSeparator,
      measurement.referenceUnit
    ] })
  ] });
}
function isMoney(maybeMoney) {
  return typeof maybeMoney.amount === "string" && !!maybeMoney.amount && typeof maybeMoney.currencyCode === "string" && !!maybeMoney.currencyCode;
}
const Image = reactExports.forwardRef(
  ({
    alt,
    aspectRatio,
    crop = "center",
    data,
    decoding = "async",
    height = "auto",
    loader: loader2 = shopifyLoader,
    loading: loading2 = "lazy",
    sizes,
    src,
    srcSetOptions = {
      intervals: 15,
      startingWidth: 200,
      incrementSize: 200,
      placeholderWidth: 100
    },
    width = "100%",
    ...passthroughProps
  }, ref) => {
    const normalizedData = reactExports.useMemo(() => {
      const dataWidth = (data == null ? void 0 : data.width) && (data == null ? void 0 : data.height) ? data == null ? void 0 : data.width : void 0;
      const dataHeight = (data == null ? void 0 : data.width) && (data == null ? void 0 : data.height) ? data == null ? void 0 : data.height : void 0;
      return {
        width: dataWidth,
        height: dataHeight,
        unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight))
      };
    }, [data]);
    const normalizedProps = reactExports.useMemo(() => {
      const nWidthProp = width || "100%";
      const widthParts = getUnitValueParts(nWidthProp.toString());
      const nWidth = `${widthParts.number}${widthParts.unit}`;
      const autoHeight = height === void 0 || height === null;
      const heightParts = autoHeight ? null : getUnitValueParts(height.toString());
      const fixedHeight = heightParts ? `${heightParts.number}${heightParts.unit}` : "";
      const nHeight = autoHeight ? "auto" : fixedHeight;
      const nSrc = src || (data == null ? void 0 : data.url);
      const nAlt = (data == null ? void 0 : data.altText) && !alt ? data == null ? void 0 : data.altText : alt || "";
      const nAspectRatio = aspectRatio ? aspectRatio : normalizedData.unitsMatch ? [
        getNormalizedFixedUnit(normalizedData.width),
        getNormalizedFixedUnit(normalizedData.height)
      ].join("/") : void 0;
      return {
        width: nWidth,
        height: nHeight,
        src: nSrc,
        alt: nAlt,
        aspectRatio: nAspectRatio
      };
    }, [
      width,
      height,
      src,
      data,
      alt,
      aspectRatio,
      normalizedData,
      passthroughProps == null ? void 0 : passthroughProps.key
    ]);
    const { intervals, startingWidth, incrementSize, placeholderWidth } = srcSetOptions;
    const imageWidths = reactExports.useMemo(() => {
      return generateImageWidths(
        width,
        intervals,
        startingWidth,
        incrementSize
      );
    }, [width, intervals, startingWidth, incrementSize]);
    const fixedWidth = isFixedWidth(normalizedProps.width);
    if (fixedWidth) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        FixedWidthImage,
        {
          aspectRatio,
          crop,
          decoding,
          height,
          imageWidths,
          loader: loader2,
          loading: loading2,
          normalizedProps,
          passthroughProps,
          ref,
          width,
          data
        }
      );
    } else {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        FluidImage,
        {
          aspectRatio,
          crop,
          decoding,
          imageWidths,
          loader: loader2,
          loading: loading2,
          normalizedProps,
          passthroughProps,
          placeholderWidth,
          ref,
          sizes,
          data
        }
      );
    }
  }
);
const FixedWidthImage = reactExports.forwardRef(
  ({
    aspectRatio,
    crop,
    decoding,
    height,
    imageWidths,
    loader: loader2 = shopifyLoader,
    loading: loading2,
    normalizedProps,
    passthroughProps,
    width,
    data
  }, ref) => {
    const fixed = reactExports.useMemo(() => {
      const intWidth = getNormalizedFixedUnit(width);
      const intHeight = getNormalizedFixedUnit(height);
      const fixedAspectRatio = aspectRatio ? aspectRatio : unitsMatch(normalizedProps.width, normalizedProps.height) ? [intWidth, intHeight].join("/") : normalizedProps.aspectRatio ? normalizedProps.aspectRatio : void 0;
      const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, fixedAspectRatio, crop, {
        width: (data == null ? void 0 : data.width) ?? void 0,
        height: (data == null ? void 0 : data.height) ?? void 0
      });
      const fixedHeight = intHeight ? intHeight : fixedAspectRatio && intWidth ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1) : void 0;
      const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader2);
      const src = loader2({
        src: normalizedProps.src,
        width: intWidth,
        height: fixedHeight,
        crop: normalizedProps.height === "auto" ? void 0 : crop
      });
      return {
        width: intWidth,
        aspectRatio: fixedAspectRatio,
        height: fixedHeight,
        srcSet,
        src
      };
    }, [
      aspectRatio,
      crop,
      data,
      height,
      imageWidths,
      loader2,
      normalizedProps,
      width
    ]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        ref,
        alt: normalizedProps.alt,
        decoding,
        height: fixed.height,
        loading: loading2,
        src: fixed.src,
        srcSet: fixed.srcSet,
        width: fixed.width,
        style: {
          aspectRatio: fixed.aspectRatio,
          ...passthroughProps.style
        },
        ...passthroughProps
      }
    );
  }
);
const FluidImage = reactExports.forwardRef(
  ({
    crop,
    decoding,
    imageWidths,
    loader: loader2 = shopifyLoader,
    loading: loading2,
    normalizedProps,
    passthroughProps,
    placeholderWidth,
    sizes,
    data
  }, ref) => {
    const fluid = reactExports.useMemo(() => {
      const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {
        width: (data == null ? void 0 : data.width) ?? void 0,
        height: (data == null ? void 0 : data.height) ?? void 0
      });
      const placeholderHeight = normalizedProps.aspectRatio && placeholderWidth ? placeholderWidth * (parseAspectRatio(normalizedProps.aspectRatio) ?? 1) : void 0;
      const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader2);
      const src = loader2({
        src: normalizedProps.src,
        width: placeholderWidth,
        height: placeholderHeight,
        crop
      });
      return {
        placeholderHeight,
        srcSet,
        src
      };
    }, [crop, data, imageWidths, loader2, normalizedProps, placeholderWidth]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        ref,
        alt: normalizedProps.alt,
        decoding,
        height: fluid.placeholderHeight,
        loading: loading2,
        sizes,
        src: fluid.src,
        srcSet: fluid.srcSet,
        width: placeholderWidth,
        ...passthroughProps,
        style: {
          width: normalizedProps.width,
          aspectRatio: normalizedProps.aspectRatio,
          ...passthroughProps.style
        }
      }
    );
  }
);
const PLACEHOLDER_DOMAIN = "https://placeholder.shopify.com";
function shopifyLoader({ src, width, height, crop }) {
  if (!src) {
    return "";
  }
  const url = new URL(src, PLACEHOLDER_DOMAIN);
  if (width) {
    url.searchParams.append("width", Math.round(width).toString());
  }
  if (height) {
    url.searchParams.append("height", Math.round(height).toString());
  }
  if (crop) {
    url.searchParams.append("crop", crop);
  }
  return url.href.replace(PLACEHOLDER_DOMAIN, "");
}
function unitsMatch(width = "100%", height = "auto") {
  return getUnitValueParts(width.toString()).unit === getUnitValueParts(height.toString()).unit;
}
function getUnitValueParts(value) {
  const unit = value.replace(/[0-9.]/g, "");
  const number = parseFloat(value.replace(unit, ""));
  return {
    unit: unit === "" ? number === void 0 ? "auto" : "px" : unit,
    number
  };
}
function getNormalizedFixedUnit(value) {
  if (value === void 0) {
    return;
  }
  const { unit, number } = getUnitValueParts(value.toString());
  switch (unit) {
    case "em":
      return number * 16;
    case "rem":
      return number * 16;
    case "px":
      return number;
    case "":
      return number;
    default:
      return;
  }
}
function isFixedWidth(width) {
  const fixedEndings = /\d(px|em|rem)$/;
  return typeof width === "number" || fixedEndings.test(width);
}
function generateSrcSet(src, sizesArray, loader2 = shopifyLoader) {
  if (!src) {
    return "";
  }
  if ((sizesArray == null ? void 0 : sizesArray.length) === 0 || !sizesArray) {
    return src;
  }
  return sizesArray.map(
    (size, i2) => `${loader2({
      src,
      width: size.width,
      height: size.height,
      crop: size.crop
    })} ${sizesArray.length === 3 ? `${i2 + 1}x` : `${size.width ?? 0}w`}`
  ).join(`, `);
}
function generateImageWidths(width = "100%", intervals, startingWidth, incrementSize) {
  const responsive = Array.from(
    { length: intervals },
    (_2, i2) => i2 * incrementSize + startingWidth
  );
  const fixed = Array.from(
    { length: 3 },
    (_2, i2) => (i2 + 1) * (getNormalizedFixedUnit(width) ?? 0)
  );
  return isFixedWidth(width) ? fixed : responsive;
}
function parseAspectRatio(aspectRatio) {
  if (!aspectRatio)
    return;
  const [width, height] = aspectRatio.split("/");
  return 1 / (Number(width) / Number(height));
}
function generateSizes(imageWidths, aspectRatio, crop = "center", sourceDimensions) {
  if (!imageWidths)
    return;
  return imageWidths.map((width) => {
    return {
      width,
      height: aspectRatio ? width * (parseAspectRatio(aspectRatio) ?? 1) : void 0,
      crop
    };
  }).filter(({ width, height }) => {
    if ((sourceDimensions == null ? void 0 : sourceDimensions.width) && width > sourceDimensions.width) {
      return false;
    }
    if ((sourceDimensions == null ? void 0 : sourceDimensions.height) && height && height > sourceDimensions.height) {
      return false;
    }
    return true;
  });
}
const SCRIPTS_LOADED = {};
function loadScript(src, options) {
  const isScriptLoaded = SCRIPTS_LOADED[src];
  if (isScriptLoaded) {
    return isScriptLoaded;
  }
  const promise = new Promise((resolve2, reject) => {
    const script = document.createElement("script");
    if (options == null ? void 0 : options.module) {
      script.type = "module";
    } else {
      script.type = "text/javascript";
    }
    script.src = src;
    script.onload = () => {
      resolve2(true);
    };
    script.onerror = () => {
      reject(false);
    };
    if ((options == null ? void 0 : options.in) === "head") {
      document.head.appendChild(script);
    } else {
      document.body.appendChild(script);
    }
    const attributes = options == null ? void 0 : options.attributes;
    if (attributes) {
      Object.keys(attributes).forEach((key) => {
        script.setAttribute(key, attributes[key]);
      });
    }
  });
  SCRIPTS_LOADED[src] = promise;
  return promise;
}
function useLoadScript(url, options) {
  const [status, setStatus] = reactExports.useState("loading");
  reactExports.useEffect(
    () => {
      loadScript(url, options).then(() => setStatus("done")).catch(() => setStatus("error"));
    },
    // Ignore options changes since it won't trigger a new load.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [url]
  );
  return status;
}
var g$5 = /* @__PURE__ */ new Set([
  "domain",
  "path",
  "max-age",
  "expires",
  "samesite",
  "secure",
  "httponly"
]);
function u$a(a3) {
  let r2 = {}, e2, t2, n2 = 0, m2 = a3.split(/;\s*/g), s2, i2;
  for (; n2 < m2.length; n2++)
    if (t2 = m2[n2], e2 = t2.indexOf("="), ~e2) {
      if (s2 = t2.substring(0, e2++).trim(), i2 = t2.substring(e2).trim(), i2[0] === '"' && (i2 = i2.substring(1, i2.length - 1)), ~i2.indexOf("%"))
        try {
          i2 = decodeURIComponent(i2);
        } catch (f2) {
        }
      g$5.has(t2 = s2.toLowerCase()) ? t2 === "expires" ? r2.expires = new Date(i2) : t2 === "max-age" ? r2.maxage = +i2 : r2[t2] = i2 : r2[s2] = i2;
    } else
      (s2 = t2.trim().toLowerCase()) && (s2 === "httponly" || s2 === "secure") && (r2[s2] = true);
  return r2;
}
function l$8(a3, r2, e2 = {}) {
  let t2 = a3 + "=" + encodeURIComponent(r2);
  return e2.expires && (t2 += "; Expires=" + new Date(e2.expires).toUTCString()), e2.maxage != null && e2.maxage >= 0 && (t2 += "; Max-Age=" + (e2.maxage | 0)), e2.domain && (t2 += "; Domain=" + e2.domain), e2.path && (t2 += "; Path=" + e2.path), e2.samesite && (t2 += "; SameSite=" + e2.samesite), (e2.secure || e2.samesite === "None") && (t2 += "; Secure"), e2.httponly && (t2 += "; HttpOnly"), t2;
}
function buildContentSecurityPolicy({ directives }) {
  const result = [];
  const entries = directives instanceof Map ? directives.entries() : Object.entries(directives);
  const namesSeen = /* @__PURE__ */ new Set();
  for (const [rawName, rawValue] of entries) {
    const name = rawName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
    if (namesSeen.has(name)) {
      throw new Error(`${rawName} is specified more than once`);
    }
    namesSeen.add(name);
    if (rawValue === true) {
      result.push(name);
      continue;
    }
    if (rawValue === false) {
      continue;
    }
    const value = typeof rawValue === "string" ? rawValue : rawValue.join(" ");
    result.push(value ? `${name} ${value}` : name);
  }
  return result.join("; ");
}
var Ve$2 = "public", xo = "private", pt = "no-store", pr = { maxAge: "max-age", staleWhileRevalidate: "stale-while-revalidate", sMaxAge: "s-maxage", staleIfError: "stale-if-error" };
function Pe$1(e2) {
  let t2 = [];
  return Object.keys(e2).forEach((r2) => {
    r2 === "mode" ? t2.push(e2[r2]) : pr[r2] && t2.push(`${pr[r2]}=${e2[r2]}`);
  }), t2.join(", ");
}
function dt$1() {
  return { mode: pt };
}
function lt(e2) {
  if ((e2 == null ? void 0 : e2.mode) && (e2 == null ? void 0 : e2.mode) !== Ve$2 && (e2 == null ? void 0 : e2.mode) !== xo) throw Error("'mode' must be either 'public' or 'private'");
}
function ce(e2) {
  return lt(e2), { mode: Ve$2, maxAge: 1, staleWhileRevalidate: 9, ...e2 };
}
function yt$1(e2) {
  return lt(e2), { mode: Ve$2, maxAge: 3600, staleWhileRevalidate: 82800, ...e2 };
}
function le(e2) {
  return lt(e2), { mode: Ve$2, maxAge: 1, staleWhileRevalidate: 86399, ...e2 };
}
function ft(e2) {
  return e2;
}
function K$1(e2) {
  return String(e2).includes("__proto__") ? JSON.parse(e2, Do) : JSON.parse(e2);
}
function Do(e2, t2) {
  if (e2 !== "__proto__") return t2;
}
function Me$2(e2, t2) {
  return e2 && t2 ? { ...e2, ...t2 } : e2 || le();
}
function mt(e2) {
  return Pe$1(Me$2(e2));
}
async function _o(e2, t2) {
  if (!e2) return;
  let r2 = await e2.match(t2);
  if (!r2) {
    return;
  }
  return r2;
}
async function Uo(e2, t2, r2, o4) {
  if (!e2) return;
  let n2 = Me$2(o4), a3 = mt(Me$2(n2, { maxAge: (n2.maxAge || 0) + (n2.staleWhileRevalidate || 0) })), s2 = mt(Me$2(n2));
  r2.headers.set("cache-control", a3), r2.headers.set("real-cache-control", s2), r2.headers.set("cache-put-date", String(Date.now())), await e2.put(t2, r2);
}
async function ko(e2, t2) {
  e2 && await e2.delete(t2);
}
function Lo(e2, t2) {
  let r2 = e2.headers.get("real-cache-control"), o4 = 0;
  if (r2) {
    let a3 = r2.match(/max-age=(\d*)/);
    a3 && a3.length > 1 && (o4 = parseFloat(a3[1]));
  }
  return [(Date.now() - Number(t2)) / 1e3, o4];
}
function No(e2, t2) {
  let r2 = t2.headers.get("cache-put-date");
  if (!r2) return false;
  let [o4, n2] = Lo(t2, r2), a3 = o4 > n2;
  return a3;
}
var He$4 = { get: _o, set: Uo, delete: ko, generateDefaultCacheControlHeader: mt, isStale: No };
function Ae$2(e2) {
  return `https://shopify.dev/?${e2}`;
}
function Vo(e2) {
  return e2 || le();
}
async function dr(e2, t2) {
  if (!e2) return;
  let r2 = Ae$2(t2), o4 = new Request(r2), n2 = await He$4.get(e2, o4);
  if (!n2) return;
  let a3 = await n2.text();
  try {
    return [K$1(a3), n2];
  } catch {
    return [a3, n2];
  }
}
async function lr(e2, t2, r2, o4) {
  if (!e2) return;
  let n2 = Ae$2(t2), a3 = new Request(n2), s2 = new Response(JSON.stringify(r2));
  await He$4.set(e2, a3, s2, Vo(o4));
}
function yr(e2, t2) {
  return He$4.isStale(new Request(Ae$2(e2)), t2);
}
function fr(e2) {
  let t2 = Array.isArray(e2) ? e2 : [e2], r2 = "";
  for (let o4 of t2) o4 != null && (typeof o4 == "object" ? r2 += JSON.stringify(o4) : r2 += o4.toString());
  return encodeURIComponent(r2);
}
var gt = /* @__PURE__ */ new Set();
async function Fe$3(e2, t2, { strategy: r2 = ce(), cacheInstance: o4, shouldCacheResult: n2 = () => true, waitUntil: a3, debugInfo: s2 }) {
  let i2 = fr([...typeof e2 == "string" ? [e2] : e2]), y2 = (m2) => {
    var _a2, _b2, _c, _d;
    ({ displayName: m2.displayName, url: (_a2 = m2.response) == null ? void 0 : _a2.url, responseInit: { status: ((_b2 = m2.response) == null ? void 0 : _b2.status) || 0, statusText: ((_c = m2.response) == null ? void 0 : _c.statusText) || "", headers: Array.from(((_d = m2.response) == null ? void 0 : _d.headers.entries()) || []) } });
  }, d2 = void 0;
  if (!o4 || !r2 || r2.mode === pt) {
    let m2 = await t2({ addDebugData: y2 });
    return m2;
  }
  let p2 = (m2) => lr(o4, i2, { value: m2, debugInfo: void 0 }, r2), f2 = await dr(o4, i2);
  if (f2 && typeof f2[0] != "string") {
    let [{ value: m2, debugInfo: C2 }, A2] = f2;
    let T3 = yr(i2, A2) ? "STALE" : "HIT";
    if (!gt.has(i2) && T3 === "STALE") {
      gt.add(i2);
      let h2 = Promise.resolve().then(async () => {
        let I2 = Date.now();
        try {
          let S2 = await t2({ addDebugData: y2 });
          n2(S2) && (await p2(S2), d2 == null ? void 0 : d2({ result: S2, cacheStatus: "PUT", overrideStartTime: I2 }));
        } catch (S2) {
          S2.message && (S2.message = "SWR in sub-request failed: " + S2.message), console.error(S2);
        } finally {
          gt.delete(i2);
        }
      });
      a3 == null ? void 0 : a3(h2);
    }
    return m2;
  }
  let P2 = await t2({ addDebugData: y2 });
  if (n2(P2)) {
    let m2 = Promise.resolve().then(async () => {
      await p2(P2);
    });
    a3 == null ? void 0 : a3(m2);
  }
  return P2;
}
var Mo = ["set-cookie", "server-timing"];
function Ho(e2, t2) {
  return [e2, { status: t2.status, statusText: t2.statusText, headers: [...t2.headers].filter(([r2]) => !Mo.includes(r2.toLowerCase())) }];
}
function mr([e2, t2]) {
  return [e2, new Response(e2, t2)];
}
async function qe$1(e2, t2, { cacheInstance: r2, cache: o4, cacheKey: n2 = [e2, t2], shouldCacheResponse: a3, waitUntil: s2, debugInfo: c2, onRawHeaders: i2 }) {
  return !o4 && (!t2.method || t2.method === "GET") && (o4 = ce()), Fe$3(n2, async () => {
    let u2 = await fetch(e2, t2);
    if (i2 == null ? void 0 : i2(u2.headers), !u2.ok) return u2;
    let l2 = await u2.text().catch(() => "");
    try {
      l2 && (l2 = K$1(l2));
    } catch {
    }
    return Ho(l2, u2);
  }, { cacheInstance: r2, waitUntil: s2, strategy: o4 ?? null, debugInfo: c2, shouldCacheResult: (u2) => "ok" in u2 ? false : a3(...mr(u2)) }).then((u2) => "ok" in u2 ? [null, u2] : mr(u2));
}
var $e$2 = "Custom-Storefront-Request-Group-ID", Ge$1 = "X-Shopify-Storefront-Access-Token", ht$1 = "X-SDK-Variant", Ct = "X-SDK-Variant-Source", St = "X-SDK-Version", Pt = "X-Shopify-Client-IP", At = "X-Shopify-Client-IP-Sig", Qe$1 = "_server_tracking";
function We$3() {
  return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `weak-${Math.random().toString(16).substring(2)}`;
}
var gr = /* @__PURE__ */ new Set(), re$1 = (e2) => {
  gr.has(e2) || (console.warn(e2), gr.add(e2));
};
var Te$1 = "2024.10.2";
function ye$1(e2) {
  return e2.replace(/\s*#.*$/gm, "").replace(/\s+/gm, " ").trim();
}
var Fo = /(^|}\s)query[\s({]/im, qo = /(^|}\s)mutation[\s({]/im;
function je$3(e2, t2) {
  if (!Fo.test(e2)) throw new Error(`[h2:error:${t2}] Can only execute queries`);
}
function Ke$4(e2, t2) {
  if (!qo.test(e2)) throw new Error(`[h2:error:${t2}] Can only execute mutations`);
}
var ue$1 = class ue extends Error {
  constructor(t2, r2 = {}) {
    let n2 = (r2.clientOperation ? `[h2:error:${r2.clientOperation}] ` : "") + t2 + (r2.requestId ? ` - Request ID: ${r2.requestId}` : "");
    super(n2);
    __publicField(this, "locations");
    __publicField(this, "path");
    __publicField(this, "extensions");
    this.name = "GraphQLError", this.extensions = r2.extensions, this.locations = r2.locations, this.path = r2.path, this.stack = r2.stack || void 0;
    try {
      this.cause = JSON.stringify({ ...typeof r2.cause == "object" ? r2.cause : {}, requestId: r2.requestId });
    } catch {
      r2.cause && (this.cause = r2.cause);
    }
  }
  get [Symbol.toStringTag]() {
    return this.name;
  }
  toString() {
    let t2 = `${this.name}: ${this.message}`;
    if (this.path) try {
      t2 += ` | path: ${JSON.stringify(this.path)}`;
    } catch {
    }
    if (this.extensions) try {
      t2 += ` | extensions: ${JSON.stringify(this.extensions)}`;
    } catch {
    }
    return t2 += `
`, this.stack && (t2 += `${this.stack.slice(this.stack.indexOf(`
`) + 1)}
`), t2;
  }
  toJSON() {
    return { name: "Error", message: "" };
  }
};
function ve$1({ url: e2, response: t2, errors: r2, type: o4, query: n2, queryVariables: a3, ErrorConstructor: s2 = Error, client: c2 = "storefront" }) {
  var _a2;
  let i2 = (typeof r2 == "string" ? r2 : (_a2 = r2 == null ? void 0 : r2.map) == null ? void 0 : _a2.call(r2, (l2) => l2.message).join(`
`)) || `URL: ${e2}
API response error: ${t2.status}`, u2 = new ue$1(i2, { query: n2, queryVariables: a3, cause: { errors: r2 }, clientOperation: `${c2}.${o4}`, requestId: t2.headers.get("x-request-id") });
  throw new s2(u2.message, { cause: u2.cause });
}
function fe$2(e2, t2 = {}) {
  let r2 = new Error(), o4 = (n2, a3 = "Error") => {
    let s2 = (r2.stack ?? "").split(`
`).slice(3 + (t2.stackOffset ?? 0)).join(`
`).replace(/ at loader(\d+) \(/, (c2, i2) => c2.replace(i2, ""));
    return `${a3}: ${n2}
` + s2;
  };
  return e2.then((n2) => {
    if ((n2 == null ? void 0 : n2.errors) && Array.isArray(n2.errors)) {
      let a3 = typeof t2.logErrors == "function" ? t2.logErrors : () => t2.logErrors ?? false;
      n2.errors.forEach((s2) => {
        s2 && (s2.stack = o4(s2.message, s2.name), a3(s2) && console.error(s2));
      });
    }
    return n2;
  }).catch((n2) => {
    throw n2 && (n2.stack = o4(n2.message, n2.name)), n2;
  });
}
var Q$2 = void 0;
function G$3(e2, t2) {
  return vt(e2.headers, t2);
}
function vt(e2, t2) {
  var _a2;
  let r2 = ((_a2 = e2 == null ? void 0 : e2.get) == null ? void 0 : _a2.call(e2, t2)) ?? (e2 == null ? void 0 : e2[t2]);
  return typeof r2 == "string" ? r2 : null;
}
function oe$1(e2) {
  return { requestId: e2 ? G$3(e2, "request-id") : void 0, purpose: e2 ? G$3(e2, "purpose") : void 0 };
}
var It = /^\/api\/(unstable|2\d{3}-\d{2})\/graphql\.json$/, Rt = (e2) => {
  try {
    return new URL(e2, "http://e.c").pathname;
  } catch {
    return "/";
  }
};
function Et(e2, t2) {
  return t2.reduce((r2, o4) => {
    let n2 = e2(o4);
    return n2 && r2.push([o4, n2]), r2;
  }, []);
}
function $o(e2) {
  return Object.entries(e2).map(([t2, r2]) => r2 ? `${t2};desc=${r2}` : void 0).filter(Boolean).join(", ");
}
function Ie$4(e2, t2) {
  let r2 = typeof t2 == "string" ? t2 : $o(t2);
  r2 && e2.headers.append("Server-Timing", r2);
}
var Go = ["_y", "_s", "_cmp"];
function Cr(e2) {
  let t2 = {};
  if (!e2) return t2;
  let r2 = new RegExp(`\\b(${Go.join("|")});desc="?([^",]+)"?`, "g"), o4;
  for (; (o4 = r2.exec(e2)) !== null; ) t2[o4[1]] = o4[2];
  return t2;
}
var jo = { language: "EN", country: "US" };
function Er(e2) {
  var _a2, _b2;
  let { storefrontHeaders: t2, cache: r2, waitUntil: o4, i18n: n2, storefrontId: a3, logErrors: s2 = true, ...c2 } = e2, { getPublicTokenHeaders: u2, getPrivateTokenHeaders: l2, getStorefrontApiUrl: y2, getShopifyDomain: g2 } = createStorefrontClient(c2), p2 = (c2.privateStorefrontToken ? l2 : u2)({ contentType: "json", buyerIp: (t2 == null ? void 0 : t2.buyerIp) || "" });
  (t2 == null ? void 0 : t2.buyerIp) && (p2[Pt] = t2.buyerIp), (t2 == null ? void 0 : t2.buyerIpSig) && (p2[At] = t2.buyerIpSig), p2[$e$2] = (t2 == null ? void 0 : t2.requestGroupId) || We$3(), a3 && (p2[SHOPIFY_STOREFRONT_ID_HEADER] = a3), p2["user-agent"] = `Hydrogen ${Te$1}`;
  let f2 = (t2 == null ? void 0 : t2.cookie) ?? "";
  f2 && (p2.cookie = f2);
  let P2, m2;
  if (!/\b_shopify_(analytics|marketing)=/.test(f2)) {
    let h2 = (_a2 = f2.match(/\b_shopify_y=([^;]+)/)) == null ? void 0 : _a2[1], I2 = (_b2 = f2.match(/\b_shopify_s=([^;]+)/)) == null ? void 0 : _b2[1];
    h2 && (p2[SHOPIFY_STOREFRONT_Y_HEADER] = h2), I2 && (p2[SHOPIFY_STOREFRONT_S_HEADER] = I2), P2 = h2 ?? We$3(), m2 = I2 ?? We$3(), p2[SHOPIFY_UNIQUE_TOKEN_HEADER] = P2, p2[SHOPIFY_VISIT_TOKEN_HEADER] = m2;
  }
  let C2, A2 = JSON.stringify({ "content-type": p2["content-type"], "user-agent": p2["user-agent"], [ht$1]: p2[ht$1], [Ct]: p2[Ct], [St]: p2[St], [Ge$1]: p2[Ge$1] });
  async function T3({ query: h2, mutation: I2, variables: S2, cache: M2, headers: U2 = [], storefrontApiVersion: Z2, displayName: ct, stackInfo: Le2 }) {
    let ut = U2 instanceof Headers ? Object.fromEntries(U2.entries()) : Array.isArray(U2) ? Object.fromEntries(U2) : U2, ee2 = h2 ?? I2, v5 = { ...S2 };
    n2 && (!(S2 == null ? void 0 : S2.country) && /\$country/.test(ee2) && (v5.country = n2.country), !(S2 == null ? void 0 : S2.language) && /\$language/.test(ee2) && (v5.language = n2.language));
    let R2 = y2({ storefrontApiVersion: Z2 }), w2 = JSON.stringify({ query: ee2, variables: v5 }), b2 = { method: "POST", headers: { ...p2, ...ut }, body: w2 }, W2 = [R2, b2.method, A2, b2.body], [te2, _2] = await qe$1(R2, b2, { cacheInstance: I2 ? void 0 : r2, cache: M2 || le(), cacheKey: W2, waitUntil: o4, shouldCacheResponse: (L2) => !(L2 == null ? void 0 : L2.errors), debugInfo: { requestId: b2.headers[$e$2], displayName: ct, url: R2, stackInfo: Le2, graphql: w2, purpose: t2 == null ? void 0 : t2.purpose }, onRawHeaders: (L2) => {
      C2 ?? (C2 = { setCookie: typeof L2.getSetCookie == "function" ? L2.getSetCookie() : [], serverTiming: L2.get("server-timing") ?? "" });
    } }), F2 = { url: R2, response: _2, type: I2 ? "mutation" : "query", query: ee2, queryVariables: v5, errors: void 0 };
    if (!_2.ok) {
      let L2, B = te2;
      try {
        B ?? (B = await _2.text()), L2 = K$1(B);
      } catch {
        L2 = [{ message: B ?? "Could not parse Storefront API response" }];
      }
      ve$1({ ...F2, errors: L2 });
    }
    let { data: $2, errors: k2 } = te2, j2 = k2 == null ? void 0 : k2.map(({ message: L2, ...B }) => new ue$1(L2, { ...B, clientOperation: `storefront.${F2.type}`, requestId: _2.headers.get("x-request-id"), queryVariables: v5, query: ee2 }));
    return E$5($2, j2);
  }
  return { storefront: { query(h2, I2) {
    h2 = ye$1(h2), je$3(h2, "storefront.query");
    let S2 = Rr == null ? void 0 : Rr(h2);
    return fe$2(T3({ ...I2, query: h2, stackInfo: Q$2 == null ? void 0 : Q$2(S2) }), { stackOffset: S2, logErrors: s2 });
  }, mutate(h2, I2) {
    h2 = ye$1(h2), Ke$4(h2, "storefront.mutate");
    let S2 = Rr == null ? void 0 : Rr(h2);
    return fe$2(T3({ ...I2, mutation: h2, stackInfo: Q$2 == null ? void 0 : Q$2(S2) }), { stackOffset: S2, logErrors: s2 });
  }, cache: r2, CacheNone: dt$1, CacheLong: yt$1, CacheShort: ce, CacheCustom: ft, generateCacheControlHeader: Pe$1, getPublicTokenHeaders: u2, getPrivateTokenHeaders: l2, getHeaders: () => ({ ...p2 }), getShopifyDomain: g2, getApiUrl: y2, i18n: n2 ?? jo, isStorefrontApiUrl(h2) {
    return It.test(Rt(h2.url ?? ""));
  }, async forward(h2, I2) {
    var _a3;
    let S2 = new Headers([...Et((Z2) => h2.headers.get(Z2), ["accept", "accept-encoding", "accept-language", "access-control-request-headers", "access-control-request-method", "content-type", "content-length", "cookie", "origin", "referer", "user-agent", Ge$1, SHOPIFY_UNIQUE_TOKEN_HEADER, SHOPIFY_VISIT_TOKEN_HEADER]), ...Et((Z2) => p2[Z2], [Pt, At, SHOPIFY_STOREFRONT_ID_HEADER, $e$2])]);
    (t2 == null ? void 0 : t2.buyerIp) && S2.set("x-forwarded-for", t2.buyerIp);
    let M2 = (I2 == null ? void 0 : I2.storefrontApiVersion) ?? ((_a3 = Rt(h2.url).match(It)) == null ? void 0 : _a3[1]), U2 = await fetch(y2({ storefrontApiVersion: M2 }), { method: h2.method, body: h2.body, headers: S2 });
    return new Response(U2.body, U2);
  }, setCollectedSubrequestHeaders: (h2) => {
    var _a3;
    if (C2) for (let U2 of C2.setCookie) h2.headers.append("Set-Cookie", U2);
    let I2 = Cr(C2 == null ? void 0 : C2.serverTiming), S2 = (_a3 = h2.headers.get("content-type")) == null ? void 0 : _a3.startsWith("text/html");
    Ie$4(h2, { ...S2 ? { _y: P2, _s: m2 } : void 0, ...I2 }), S2 && C2 && C2.setCookie.length > 1 && (I2 == null ? void 0 : I2._y) && (I2 == null ? void 0 : I2._s) && (I2 == null ? void 0 : I2._cmp) && Ie$4(h2, { [Qe$1]: "1" });
  } } };
}
var Rr = void 0;
function E$5(e2, t2) {
  return { ...e2, ...t2 && { errors: t2 } };
}
function Ye$1(e2) {
  if (!e2) return;
  let { pathname: t2, search: r2 } = new URL(e2), o4 = t2 + r2, n2 = new URLSearchParams(r2), a3 = n2.get("return_to") || n2.get("redirect");
  if (a3) {
    if (br(e2, a3)) return a3;
    console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o4} to ${a3}`);
  }
}
function br(e2, t2) {
  try {
    return new URL(e2).origin === new URL(t2, e2).origin;
  } catch {
    return false;
  }
}
function bt({ requestUrl: e2, defaultUrl: t2, redirectUrl: r2 }) {
  let o4 = e2, n2 = wr(e2, t2), a3 = r2 ? wr(e2, r2) : n2;
  return br(e2, a3.toString()) ? a3.toString() : (console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o4} to ${a3}. Default url ${n2} is used instead.`), n2.toString());
}
function wr(e2, t2) {
  return Yo(t2) ? new URL(t2) : new URL(t2, new URL(e2).origin);
}
function Yo(e2) {
  try {
    return new URL(e2), true;
  } catch {
    return false;
  }
}
async function zo(e2) {
  var _a2, _b2, _c;
  let { storefront: t2, request: r2, noAdminRedirect: o4, matchQueryParams: n2, response: a3 = new Response("Not Found", { status: 404 }) } = e2, s2 = new URL(r2.url), { pathname: c2, searchParams: i2 } = s2, u2 = i2.has("_data");
  i2.delete("redirect"), i2.delete("return_to"), i2.delete("_data");
  let l2 = (n2 ? s2.toString().replace(s2.origin, "") : c2).toLowerCase();
  if (s2.pathname === "/admin" && !o4) return xt(`${t2.getShopifyDomain()}/admin`, u2, i2, n2);
  try {
    let { urlRedirects: y2 } = await t2.query(Jo, { variables: { query: "path:" + l2.replace(/\/+$/, "") } }), g2 = (_c = (_b2 = (_a2 = y2 == null ? void 0 : y2.edges) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.node) == null ? void 0 : _c.target;
    if (g2) return xt(g2, u2, i2, n2);
    let d2 = Ye$1(r2.url);
    if (d2) return xt(d2, u2, i2, n2);
  } catch (y2) {
    console.error(`Failed to fetch redirects from Storefront API for route ${l2}`, y2);
  }
  return a3;
}
var Ot = "https://example.com";
function xt(e2, t2, r2, o4) {
  let n2 = new URL(e2, Ot);
  if (!o4) for (let [a3, s2] of r2) n2.searchParams.append(a3, s2);
  return t2 ? new Response(null, { status: 200, headers: { "X-Remix-Redirect": n2.toString().replace(Ot, ""), "X-Remix-Status": "301" } }) : new Response(null, { status: 301, headers: { location: n2.toString().replace(Ot, "") } });
}
var Jo = `#graphql
  query redirects($query: String) {
    urlRedirects(first: 1, query: $query) {
      edges {
        node {
          target
        }
      }
    }
  }
`;
reactExports.lazy(() => Promise.resolve().then(() => logSeoTagsTY72EQWZ));
function ln({ connection: e2, children: t2 = () => (console.warn("<Pagination> requires children to work properly"), null), namespace: r2 = "" }) {
  let [o4, n2] = reactExports.useState(false), a3 = useNavigation(), s2 = useLocation();
  useNavigate();
  reactExports.useEffect(() => {
    a3.state === "idle" && n2(false);
  }, [a3.state]);
  let { endCursor: i2, hasNextPage: u2, hasPreviousPage: l2, nextPageUrl: y2, nodes: g2, previousPageUrl: d2, startCursor: p2 } = yn(e2, r2), f2 = reactExports.useMemo(() => {
    var _a2;
    return { ...s2.state, pagination: { ...((_a2 = s2.state) == null ? void 0 : _a2.pagination) || {}, [r2]: { pageInfo: { endCursor: i2, hasPreviousPage: l2, hasNextPage: u2, startCursor: p2 }, nodes: g2 } } };
  }, [i2, u2, l2, p2, g2, r2, s2.state]), P2 = reactExports.useMemo(() => reactExports.forwardRef(function(A2, T3) {
    return u2 ? reactExports.createElement(Link, { preventScrollReset: true, ...A2, to: y2, state: f2, replace: true, ref: T3, onClick: () => n2(true) }) : null;
  }), [u2, y2, f2]), m2 = reactExports.useMemo(() => reactExports.forwardRef(function(A2, T3) {
    return l2 ? reactExports.createElement(Link, { preventScrollReset: true, ...A2, to: d2, state: f2, replace: true, ref: T3, onClick: () => n2(true) }) : null;
  }), [l2, d2, f2]);
  return t2({ state: f2, hasNextPage: u2, hasPreviousPage: l2, isLoading: o4, nextPageUrl: y2, nodes: g2, previousPageUrl: d2, NextLink: P2, PreviousLink: m2 });
}
function Je$1(e2, t2) {
  let r2 = new URLSearchParams(e2);
  return Object.keys((t2 == null ? void 0 : t2.pagination) || {}).forEach((n2) => {
    let a3 = n2 === "" ? "" : `${n2}_`, s2 = `${a3}cursor`, c2 = `${a3}direction`;
    r2.delete(s2), r2.delete(c2);
  }), r2.toString();
}
function Ee$1(e2) {
  throw new Error(`The Pagination component requires ${"`" + e2 + "`"} to be a part of your query. See the guide on how to setup your query to include ${"`" + e2 + "`"}: https://shopify.dev/docs/custom-storefronts/hydrogen/data-fetching/pagination#setup-the-paginated-query`);
}
function yn(e2, t2 = "") {
  e2.pageInfo || Ee$1("pageInfo"), typeof e2.pageInfo.startCursor > "u" && Ee$1("pageInfo.startCursor"), typeof e2.pageInfo.endCursor > "u" && Ee$1("pageInfo.endCursor"), typeof e2.pageInfo.hasNextPage > "u" && Ee$1("pageInfo.hasNextPage"), typeof e2.pageInfo.hasPreviousPage > "u" && Ee$1("pageInfo.hasPreviousPage");
  let r2 = useNavigation(), o4 = useNavigate(), { state: n2, search: a3, pathname: s2 } = useLocation(), c2 = t2 ? `${t2}_cursor` : "cursor", i2 = t2 ? `${t2}_direction` : "direction", y2 = new URLSearchParams(a3).get(i2) === "previous", g2 = reactExports.useMemo(() => {
    var _a2, _b2, _c;
    return !((_a2 = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : _a2.__hydrogenHydrated) || !((_c = (_b2 = n2 == null ? void 0 : n2.pagination) == null ? void 0 : _b2[t2]) == null ? void 0 : _c.nodes) ? flattenConnection(e2) : y2 ? [...flattenConnection(e2), ...n2.pagination[t2].nodes || []] : [...n2.pagination[t2].nodes || [], ...flattenConnection(e2)];
  }, [n2, e2, t2]), d2 = reactExports.useMemo(() => {
    var _a2, _b2, _c, _d, _e2;
    let m2 = (_a2 = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : _a2.__hydrogenHydrated, C2 = (_c = (_b2 = n2 == null ? void 0 : n2.pagination) == null ? void 0 : _b2[t2]) == null ? void 0 : _c.pageInfo, A2 = !m2 || (C2 == null ? void 0 : C2.startCursor) === void 0 ? e2.pageInfo.startCursor : C2.startCursor, T3 = !m2 || (C2 == null ? void 0 : C2.endCursor) === void 0 ? e2.pageInfo.endCursor : C2.endCursor, h2 = !m2 || (C2 == null ? void 0 : C2.hasPreviousPage) === void 0 ? e2.pageInfo.hasPreviousPage : C2.hasPreviousPage, I2 = !m2 || (C2 == null ? void 0 : C2.hasNextPage) === void 0 ? e2.pageInfo.hasNextPage : C2.hasNextPage;
    return ((_e2 = (_d = n2 == null ? void 0 : n2.pagination) == null ? void 0 : _d[t2]) == null ? void 0 : _e2.nodes) && (y2 ? (A2 = e2.pageInfo.startCursor, h2 = e2.pageInfo.hasPreviousPage) : (T3 = e2.pageInfo.endCursor, I2 = e2.pageInfo.hasNextPage)), { startCursor: A2, endCursor: T3, hasPreviousPage: h2, hasNextPage: I2 };
  }, [y2, n2, t2, e2.pageInfo.hasNextPage, e2.pageInfo.hasPreviousPage, e2.pageInfo.startCursor, e2.pageInfo.endCursor]), p2 = reactExports.useRef({ params: Je$1(a3, n2), pathname: s2 });
  reactExports.useEffect(() => {
    window.__hydrogenHydrated = true;
  }, []), reactExports.useEffect(() => {
    let m2 = Je$1(a3, n2), C2 = p2.current.params;
    (s2 !== p2.current.pathname || m2 !== C2) && !(r2.state === "idle" && !r2.location) && (p2.current = { pathname: s2, params: Je$1(a3, n2) }, o4(`${s2}?${Je$1(a3, n2)}`, { replace: true, preventScrollReset: true, state: { nodes: void 0, pageInfo: void 0 } }));
  }, [s2, a3, n2]);
  let f2 = reactExports.useMemo(() => {
    let m2 = new URLSearchParams(a3);
    return m2.set(i2, "previous"), d2.startCursor && m2.set(c2, d2.startCursor), `?${m2.toString()}`;
  }, [a3, d2.startCursor]), P2 = reactExports.useMemo(() => {
    let m2 = new URLSearchParams(a3);
    return m2.set(i2, "next"), d2.endCursor && m2.set(c2, d2.endCursor), `?${m2.toString()}`;
  }, [a3, d2.endCursor]);
  return { ...d2, previousPageUrl: f2, nextPageUrl: P2, nodes: g2 };
}
function fn(e2, t2 = { pageBy: 20 }) {
  if (typeof (e2 == null ? void 0 : e2.url) > "u") throw new Error("getPaginationVariables must be called with the Request object passed to your loader function");
  let { pageBy: r2, namespace: o4 = "" } = t2, n2 = new URLSearchParams(new URL(e2.url).search), a3 = o4 ? `${o4}_cursor` : "cursor", s2 = o4 ? `${o4}_direction` : "direction", c2 = n2.get(a3) ?? void 0;
  return (n2.get(s2) === "previous" ? "previous" : "next") === "previous" ? { last: r2, startCursor: c2 ?? null } : { first: r2, endCursor: c2 ?? null };
}
var Xe$2 = "2024-10", me$2 = `Shopify Hydrogen ${Te$1}`, Mr = "30243aa5-17c1-465a-8493-944bcc4e88aa", V$5 = "customerAccount", ge$2 = "buyer";
var q$1 = class q extends Response {
  constructor(t2, r2, o4) {
    super(`Bad request: ${t2}`, { status: 400, headers: o4 });
  }
};
function be$1(e2, t2 = {}) {
  let r2 = t2.headers ? new Headers(t2.headers) : new Headers({});
  return r2.set("location", e2), new Response(null, { status: t2.status || 302, headers: r2 });
}
async function mn({ session: e2, customerAccountId: t2, customerAccountTokenExchangeUrl: r2, httpsOrigin: o4, debugInfo: n2, exchangeForStorefrontCustomerAccessToken: a3 }) {
  let s2 = new URLSearchParams(), c2 = e2.get(V$5), i2 = c2 == null ? void 0 : c2.refreshToken, u2 = c2 == null ? void 0 : c2.idToken;
  if (!i2) throw new q$1("Unauthorized", "No refreshToken found in the session. Make sure your session is configured correctly and passed to `createCustomerAccountClient`.");
  s2.append("grant_type", "refresh_token"), s2.append("refresh_token", i2), s2.append("client_id", t2);
  let l2 = { "content-type": "application/x-www-form-urlencoded", "User-Agent": me$2, Origin: o4 };
  (/* @__PURE__ */ new Date()).getTime();
  let g2 = r2, d2 = await fetch(g2, { method: "POST", headers: l2, body: s2 });
  if (!d2.ok) {
    let C2 = await d2.text();
    throw new Response(C2, { status: d2.status, headers: { "Content-Type": "text/html; charset=utf-8" } });
  }
  let { access_token: p2, expires_in: f2, refresh_token: P2 } = await d2.json(), m2 = await Nt(p2, t2, r2, o4);
  e2.set(V$5, { accessToken: m2, expiresAt: new Date((/* @__PURE__ */ new Date()).getTime() + (f2 - 120) * 1e3).getTime() + "", refreshToken: P2, idToken: u2 }), await a3();
}
function he$1(e2) {
  e2.unset(V$5), e2.unset(ge$2);
}
async function Hr({ locks: e2, expiresAt: t2, session: r2, customerAccountId: o4, customerAccountTokenExchangeUrl: n2, httpsOrigin: a3, debugInfo: s2, exchangeForStorefrontCustomerAccessToken: c2 }) {
  if (parseInt(t2, 10) - 1e3 < (/* @__PURE__ */ new Date()).getTime()) try {
    e2.refresh || (e2.refresh = mn({ session: r2, customerAccountId: o4, customerAccountTokenExchangeUrl: n2, httpsOrigin: a3, debugInfo: s2, exchangeForStorefrontCustomerAccessToken: c2 })), await e2.refresh, delete e2.refresh;
  } catch (i2) {
    throw he$1(r2), i2 && i2.status !== 401 ? i2 : new q$1("Unauthorized", "Login before querying the Customer Account API.");
  }
}
function Fr() {
  let e2 = gn();
  return $r(e2);
}
async function qr(e2) {
  let t2 = await crypto.subtle.digest({ name: "SHA-256" }, new TextEncoder().encode(e2)), r2 = hn(t2);
  return $r(r2);
}
function gn() {
  let e2 = new Uint8Array(32);
  return crypto.getRandomValues(e2), String.fromCharCode.apply(null, Array.from(e2));
}
function $r(e2) {
  return btoa(e2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hn(e2) {
  let t2 = new Uint8Array(e2), r2 = Array.from(t2);
  return String.fromCharCode(...r2);
}
function Gr() {
  let e2 = Date.now().toString(), t2 = Math.random().toString(36).substring(2);
  return e2 + t2;
}
async function Nt(e2, t2, r2, o4, n2) {
  let a3 = t2;
  if (!e2) throw new q$1("Unauthorized", "oAuth access token was not provided during token exchange.");
  let s2 = new URLSearchParams();
  s2.append("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"), s2.append("client_id", a3), s2.append("audience", Mr), s2.append("subject_token", e2), s2.append("subject_token_type", "urn:ietf:params:oauth:token-type:access_token"), s2.append("scopes", "https://api.customers.com/auth/customer.graphql");
  let c2 = { "content-type": "application/x-www-form-urlencoded", "User-Agent": me$2, Origin: o4 };
  (/* @__PURE__ */ new Date()).getTime();
  let u2 = r2, l2 = await fetch(u2, { method: "POST", headers: c2, body: s2 });
  let y2 = await l2.json();
  if (y2.error) throw new q$1(y2.error_description);
  return y2.access_token;
}
function Br(e2) {
  return Cn(e2).payload.nonce;
}
function Cn(e2) {
  let [t2, r2, o4] = e2.split("."), n2 = JSON.parse(atob(t2)), a3 = JSON.parse(atob(r2));
  return { header: n2, payload: a3, signature: o4 };
}
function Ze() {
  return Pn(Sn());
}
function Sn() {
  try {
    return crypto.getRandomValues(new Uint8Array(16));
  } catch {
    return new Uint8Array(16).map(() => Math.random() * 255 | 0);
  }
}
function Pn(e2) {
  return Array.from(e2, function(t2) {
    return ("0" + (t2 & 255).toString(16)).slice(-2);
  }).join("");
}
function Qr(e2, t2, r2) {
  let o4 = r2 ? `https://shopify.com/${r2}` : t2, n2 = r2 ? `https://shopify.com/authentication/${r2}` : `${t2}/auth`;
  return function(s2) {
    switch (s2) {
      case "CA_BASE_URL":
        return o4;
      case "CA_BASE_AUTH_URL":
        return n2;
      case "GRAPHQL":
        return `${o4}/account/customer/api/${e2}/graphql`;
      case "AUTH":
        return `${n2}/oauth/authorize`;
      case "LOGIN_SCOPE":
        return r2 ? "openid email customer-account-api:full" : "openid email https://api.customers.com/auth/customer.graphql";
      case "TOKEN_EXCHANGE":
        return `${n2}/oauth/token`;
      case "LOGOUT":
        return `${n2}/logout`;
    }
  };
}
function An(e2, t2) {
  if (!e2.url) return t2;
  let { pathname: r2 } = new URL(e2.url), o4 = t2 + `?${new URLSearchParams({ return_to: r2 }).toString()}`;
  return be$1(o4);
}
function Vt({ session: e2, customerAccountId: t2, customerAccountUrl: r2, shopId: o4, customerApiVersion: n2 = Xe$2, request: a3, waitUntil: s2, authUrl: c2, customAuthStatusHandler: i2, logErrors: u2 = true, unstableB2b: l2 = false, loginPath: y2 = "/account/login", authorizePath: g2 = "/account/authorize", defaultRedirectPath: d2 = "/account" }) {
  if (n2 !== Xe$2 && console.warn(`[h2:warn:createCustomerAccountClient] You are using Customer Account API version ${n2} when this version of Hydrogen was built for ${Xe$2}.`), e2 || console.warn("[h2:warn:createCustomerAccountClient] session is required to use Customer Account API. Ensure the session object passed in exist."), !(a3 == null ? void 0 : a3.url)) throw new Error("[h2:error:createCustomerAccountClient] The request object does not contain a URL.");
  r2 && !o4 && re$1("[h2:warn:createCustomerAccountClient] The `customerAccountUrl` option is deprecated and will be removed in a future version. Please remove `customerAccountUrl` and supply a `shopId: env.SHOP_ID` option instead.\n\nIf using `createHydrogenContext`, ensure there is a SHOP_ID defined in your local .env file.");
  let p2 = i2 || (() => An(a3, y2)), f2 = new URL(a3.url), P2 = f2.protocol === "http:" ? f2.origin.replace("http", "https") : f2.origin, m2 = bt({ requestUrl: P2, defaultUrl: g2, redirectUrl: c2 }), C2 = Qr(n2, r2, o4), A2 = Tn(C2, t2), T3 = C2("GRAPHQL"), h2 = {};
  async function I2({ query: v5, type: R2, variables: w2 = {} }) {
    let b2 = await U2();
    if (!b2) throw p2();
    (/* @__PURE__ */ new Date()).getTime();
    let _2 = await fetch(T3, { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": me$2, Origin: P2, Authorization: b2 }, body: JSON.stringify({ query: v5, variables: w2 }) });
    let F2 = await _2.text(), $2 = { url: T3, response: _2, type: R2, query: v5, queryVariables: w2, errors: void 0, client: "customer" };
    if (!_2.ok) {
      if (_2.status === 401) throw he$1(e2), p2();
      let k2;
      try {
        k2 = K$1(F2);
      } catch {
        k2 = [{ message: F2 }];
      }
      ve$1({ ...$2, errors: k2 });
    }
    try {
      let k2 = K$1(F2), { errors: j2 } = k2, L2 = j2 == null ? void 0 : j2.map(({ message: B, ...Ne2 }) => new ue$1(B, { ...Ne2, clientOperation: `customerAccount.${$2.type}`, requestId: _2.headers.get("x-request-id"), queryVariables: w2, query: v5 }));
      return { ...k2, ...j2 && { errors: L2 } };
    } catch {
      ve$1({ ...$2, errors: [{ message: F2 }] });
    }
  }
  async function S2() {
    if (!o4 && (!r2 || !t2)) return false;
    let v5 = e2.get(V$5), R2 = v5 == null ? void 0 : v5.accessToken, w2 = v5 == null ? void 0 : v5.expiresAt;
    if (!R2 || !w2) return false;
    let b2 = Q$2 == null ? void 0 : Q$2();
    try {
      await Hr({ locks: h2, expiresAt: w2, session: e2, customerAccountId: t2, customerAccountTokenExchangeUrl: C2("TOKEN_EXCHANGE"), httpsOrigin: P2, debugInfo: { waitUntil: s2, stackInfo: b2, ...oe$1(a3) }, exchangeForStorefrontCustomerAccessToken: ee2 });
    } catch {
      return false;
    }
    return true;
  }
  async function M2() {
    if (!await S2()) throw p2();
  }
  async function U2() {
    var _a2;
    if (await S2()) return (_a2 = e2.get(V$5)) == null ? void 0 : _a2.accessToken;
  }
  async function Z2(v5, R2) {
    return A2(), v5 = ye$1(v5), Ke$4(v5, "customer.mutate"), fe$2(I2({ query: v5, type: "mutation", ...R2 }), { logErrors: u2 });
  }
  async function ct(v5, R2) {
    return A2(), v5 = ye$1(v5), je$3(v5, "customer.query"), fe$2(I2({ query: v5, type: "query", ...R2 }), { logErrors: u2 });
  }
  function Le2(v5) {
    e2.set(ge$2, { ...e2.get(ge$2), ...v5 });
  }
  async function ut() {
    if (await S2()) return e2.get(ge$2);
  }
  async function ee2() {
    var _a2;
    if (!l2) return;
    let v5 = `#graphql
      mutation storefrontCustomerAccessTokenCreate {
        storefrontCustomerAccessTokenCreate {
          customerAccessToken
        }
      }
    `, { data: R2 } = await Z2(v5), w2 = (_a2 = R2 == null ? void 0 : R2.storefrontCustomerAccessTokenCreate) == null ? void 0 : _a2.customerAccessToken;
    w2 && Le2({ customerAccessToken: w2 });
  }
  return { login: async (v5) => {
    A2();
    let R2 = new URL(C2("AUTH")), w2 = Gr(), b2 = Ze();
    if (R2.searchParams.set("client_id", t2), R2.searchParams.set("scope", "openid email"), R2.searchParams.append("response_type", "code"), R2.searchParams.append("redirect_uri", m2), R2.searchParams.set("scope", C2("LOGIN_SCOPE")), R2.searchParams.append("state", w2), R2.searchParams.append("nonce", b2), v5 == null ? void 0 : v5.uiLocales) {
      let [_2, F2] = v5.uiLocales.split("-"), $2 = _2.toLowerCase();
      F2 && ($2 += `-${F2.toUpperCase()}`), R2.searchParams.append("ui_locales", $2);
    }
    let W2 = Fr(), te2 = await qr(W2);
    return e2.set(V$5, { ...e2.get(V$5), codeVerifier: W2, state: w2, nonce: b2, redirectPath: Ye$1(a3.url) || G$3(a3, "Referer") || d2 }), R2.searchParams.append("code_challenge", te2), R2.searchParams.append("code_challenge_method", "S256"), be$1(R2.toString());
  }, logout: async (v5) => {
    var _a2;
    A2();
    let R2 = (_a2 = e2.get(V$5)) == null ? void 0 : _a2.idToken, w2 = bt({ requestUrl: P2, defaultUrl: P2, redirectUrl: v5 == null ? void 0 : v5.postLogoutRedirectUri }), b2 = R2 ? new URL(`${C2("LOGOUT")}?${new URLSearchParams([["id_token_hint", R2], ["post_logout_redirect_uri", w2]]).toString()}`).toString() : w2;
    return he$1(e2), be$1(b2, { headers: (v5 == null ? void 0 : v5.headers) || {} });
  }, isLoggedIn: S2, handleAuthStatus: M2, getAccessToken: U2, getApiUrl: () => T3, mutate: Z2, query: ct, authorize: async () => {
    var _a2, _b2, _c, _d;
    A2();
    let v5 = f2.searchParams.get("code"), R2 = f2.searchParams.get("state");
    if (!v5 || !R2) throw he$1(e2), new q$1("Unauthorized", "No code or state parameter found in the redirect URL.");
    if (((_a2 = e2.get(V$5)) == null ? void 0 : _a2.state) !== R2) throw he$1(e2), new q$1("Unauthorized", "The session state does not match the state parameter. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.");
    let w2 = t2, b2 = new URLSearchParams();
    b2.append("grant_type", "authorization_code"), b2.append("client_id", w2), b2.append("redirect_uri", m2), b2.append("code", v5);
    let W2 = (_b2 = e2.get(V$5)) == null ? void 0 : _b2.codeVerifier;
    if (!W2) throw new q$1("Unauthorized", "No code verifier found in the session. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.");
    b2.append("code_verifier", W2);
    let te2 = { "content-type": "application/x-www-form-urlencoded", "User-Agent": me$2, Origin: P2 };
    (/* @__PURE__ */ new Date()).getTime();
    let $2 = C2("TOKEN_EXCHANGE"), k2 = await fetch($2, { method: "POST", headers: te2, body: b2 });
    if (!k2.ok) throw new Response(await k2.text(), { status: k2.status, headers: { "Content-Type": "text/html; charset=utf-8" } });
    let { access_token: j2, expires_in: L2, id_token: B, refresh_token: Ne2 } = await k2.json(), ir = (_c = e2.get(V$5)) == null ? void 0 : _c.nonce, cr = await Br(B);
    if (ir !== cr) throw new q$1("Unauthorized", `Returned nonce does not match: ${ir} !== ${cr}`);
    let ur = j2;
    o4 || (ur = await Nt(j2, t2, C2("TOKEN_EXCHANGE"), P2, { ...oe$1(a3) }));
    let Oo = (_d = e2.get(V$5)) == null ? void 0 : _d.redirectPath;
    return e2.set(V$5, { accessToken: ur, expiresAt: new Date((/* @__PURE__ */ new Date()).getTime() + (L2 - 120) * 1e3).getTime() + "", refreshToken: Ne2, idToken: B }), await ee2(), be$1(Oo || d2);
  }, UNSTABLE_setBuyer: Le2, UNSTABLE_getBuyer: ut };
}
function Tn(e2, t2) {
  return function() {
    try {
      if (!t2) throw Error();
      new URL(e2("CA_BASE_URL")), new URL(e2("CA_BASE_AUTH_URL"));
    } catch {
      console.error(new Error("[h2:error:customerAccount] You do not have the valid credential to use Customer Account API.\nRun `h2 env pull` to link your store credentials."));
      let o4 = "Internal Server Error";
      throw new Response(o4, { status: 500 });
    }
  };
}
var Wr = "cartFormInput";
function J$1({ children: e2, action: t2, inputs: r2, route: o4, fetcherKey: n2 }) {
  let a3 = useFetcher({ key: n2 });
  return jsxRuntimeExports.jsxs(a3.Form, { action: o4 || "", method: "post", children: [(t2 || r2) && jsxRuntimeExports.jsx("input", { type: "hidden", name: Wr, value: JSON.stringify({ action: t2, inputs: r2 }) }), typeof e2 == "function" ? e2(a3) : e2] });
}
J$1.INPUT_NAME = Wr;
J$1.ACTIONS = { AttributesUpdateInput: "AttributesUpdateInput", BuyerIdentityUpdate: "BuyerIdentityUpdate", Create: "Create", DiscountCodesUpdate: "DiscountCodesUpdate", GiftCardCodesUpdate: "GiftCardCodesUpdate", LinesAdd: "LinesAdd", LinesRemove: "LinesRemove", LinesUpdate: "LinesUpdate", NoteUpdate: "NoteUpdate", SelectedDeliveryOptionsUpdate: "SelectedDeliveryOptionsUpdate", MetafieldsSet: "MetafieldsSet", MetafieldDelete: "MetafieldDelete" };
function En(e2) {
  let t2 = {};
  for (let s2 of e2.entries()) {
    let c2 = s2[0], i2 = e2.getAll(c2);
    t2[c2] = i2.length > 1 ? i2 : s2[1];
  }
  let { cartFormInput: r2, ...o4 } = t2, { action: n2, inputs: a3 } = r2 ? JSON.parse(String(r2)) : {};
  return { action: n2, inputs: { ...a3, ...o4 } };
}
J$1.getFormInput = En;
var O$3 = `#graphql
  fragment CartApiError on CartUserError {
    message
    field
    code
  }
`, x$7 = `#graphql
  fragment CartApiMutation on Cart {
    id
    totalQuantity
    checkoutUrl
  }
`, D$5 = `#graphql
  fragment CartApiWarning on CartWarning {
    code
    message
    target
  }
`;
function Mt(e2) {
  return async (t2, r2) => {
    let o4 = e2.customerAccount ? await e2.customerAccount.UNSTABLE_getBuyer() : void 0, { cartId: n2, ...a3 } = r2 || {}, { buyerIdentity: s2, ...c2 } = t2, { cartCreate: i2, errors: u2 } = await e2.storefront.mutate(On(e2.cartFragment), { variables: { input: { ...c2, buyerIdentity: { ...o4, ...s2 } }, ...a3 } });
    return E$5(i2, u2);
  };
}
var On = (e2 = x$7) => `#graphql
  mutation cartCreate(
    $input: CartInput!
    $country: CountryCode = ZZ
    $language: LanguageCode
  ) @inContext(country: $country, language: $language) {
    cartCreate(input: $input) {
      cart {
        ...CartApiMutation
        checkoutUrl
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Ht({ storefront: e2, customerAccount: t2, getCartId: r2, cartFragment: o4 }) {
  return async (n2) => {
    let a3 = r2();
    if (!a3) return null;
    let [s2, { cart: c2, errors: i2 }] = await Promise.all([t2 ? t2.isLoggedIn() : false, e2.query(xn(o4), { variables: { cartId: a3, ...n2 }, cache: e2.CacheNone() })]);
    if (s2 && (c2 == null ? void 0 : c2.checkoutUrl)) {
      let u2 = new URL(c2.checkoutUrl);
      u2.searchParams.set("logged_in", "true"), c2.checkoutUrl = u2.toString();
    }
    return c2 || i2 ? E$5(c2, i2) : null;
  };
}
var xn = (e2 = Dn) => `#graphql
  query CartQuery(
    $cartId: ID!
    $numCartLines: Int = 100
    $country: CountryCode = ZZ
    $language: LanguageCode
  ) @inContext(country: $country, language: $language) {
    cart(id: $cartId) {
      ...CartApiQuery
    }
  }

  ${e2}
`, Dn = `#graphql
  fragment CartApiQuery on Cart {
    updatedAt
    id
    checkoutUrl
    totalQuantity
    buyerIdentity {
      countryCode
      customer {
        id
        email
        firstName
        lastName
        displayName
      }
      email
      phone
    }
    lines(first: $numCartLines) {
      edges {
        node {
          id
          quantity
          attributes {
            key
            value
          }
          cost {
            totalAmount {
              amount
              currencyCode
            }
            amountPerQuantity {
              amount
              currencyCode
            }
            compareAtAmountPerQuantity {
              amount
              currencyCode
            }
          }
          merchandise {
            ... on ProductVariant {
              id
              availableForSale
              compareAtPrice {
                ...CartApiMoney
              }
              price {
                ...CartApiMoney
              }
              requiresShipping
              title
              image {
                ...CartApiImage
              }
              product {
                handle
                title
                id
                vendor
              }
              selectedOptions {
                name
                value
              }
            }
          }
        }
      }
    }
    cost {
      subtotalAmount {
        ...CartApiMoney
      }
      totalAmount {
        ...CartApiMoney
      }
      totalDutyAmount {
        ...CartApiMoney
      }
      totalTaxAmount {
        ...CartApiMoney
      }
    }
    note
    attributes {
      key
      value
    }
    discountCodes {
      applicable
      code
    }
  }

  fragment CartApiMoney on MoneyV2 {
    currencyCode
    amount
  }

  fragment CartApiImage on Image {
    id
    url
    altText
    width
    height
  }
`;
function Ft(e2) {
  return async (t2, r2) => {
    let { cartLinesAdd: o4, errors: n2 } = await e2.storefront.mutate(_n(e2.cartFragment), { variables: { cartId: e2.getCartId(), lines: t2, ...r2 } });
    return E$5(o4, n2);
  };
}
var _n = (e2 = x$7) => `#graphql
  mutation cartLinesAdd(
    $cartId: ID!
    $lines: [CartLineInput!]!
    $country: CountryCode = ZZ
    $language: LanguageCode
  ) @inContext(country: $country, language: $language) {
    cartLinesAdd(cartId: $cartId, lines: $lines) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
var jr = "__h_pending_";
function et$1(e2) {
  return e2.startsWith(jr);
}
function tt(e2, t2) {
  if (t2.some((r2) => et$1(typeof r2 == "string" ? r2 : r2.id))) throw new Error(`Tried to perform an action on an optimistic line. Make sure to disable your "${e2}" CartForm action when the line is optimistic.`);
}
function qt(e2) {
  return async (t2, r2) => {
    tt("updateLines", t2);
    let { cartLinesUpdate: o4, errors: n2 } = await e2.storefront.mutate(Un(e2.cartFragment), { variables: { cartId: e2.getCartId(), lines: t2, ...r2 } });
    return E$5(o4, n2);
  };
}
var Un = (e2 = x$7) => `#graphql
  mutation cartLinesUpdate(
    $cartId: ID!
    $lines: [CartLineUpdateInput!]!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartLinesUpdate(cartId: $cartId, lines: $lines) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function $t(e2) {
  return async (t2, r2) => {
    tt("removeLines", t2);
    let { cartLinesRemove: o4, errors: n2 } = await e2.storefront.mutate(kn(e2.cartFragment), { variables: { cartId: e2.getCartId(), lineIds: t2, ...r2 } });
    return E$5(o4, n2);
  };
}
var kn = (e2 = x$7) => `#graphql
  mutation cartLinesRemove(
    $cartId: ID!
    $lineIds: [ID!]!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Gt(e2) {
  return async (t2, r2) => {
    let o4 = t2.filter((s2, c2, i2) => i2.indexOf(s2) === c2), { cartDiscountCodesUpdate: n2, errors: a3 } = await e2.storefront.mutate(Ln(e2.cartFragment), { variables: { cartId: e2.getCartId(), discountCodes: o4, ...r2 } });
    return E$5(n2, a3);
  };
}
var Ln = (e2 = x$7) => `#graphql
  mutation cartDiscountCodesUpdate(
    $cartId: ID!
    $discountCodes: [String!]
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Bt(e2) {
  return async (t2, r2) => {
    let o4 = t2.filter((s2, c2, i2) => i2.indexOf(s2) === c2), { cartGiftCardCodesUpdate: n2, errors: a3 } = await e2.storefront.mutate(Nn(e2.cartFragment), { variables: { cartId: e2.getCartId(), giftCardCodes: o4, ...r2 } });
    return E$5(n2, a3);
  };
}
var Nn = (e2 = x$7) => `#graphql
  mutation cartGiftCardCodesUpdate(
    $cartId: ID!
    $giftCardCodes: [String!]!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartGiftCardCodesUpdate(cartId: $cartId, giftCardCodes: $giftCardCodes) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Qt(e2) {
  return async (t2, r2) => {
    t2.companyLocationId && e2.customerAccount && e2.customerAccount.UNSTABLE_setBuyer({ companyLocationId: t2.companyLocationId });
    let o4 = e2.customerAccount ? await e2.customerAccount.UNSTABLE_getBuyer() : void 0, { cartBuyerIdentityUpdate: n2, errors: a3 } = await e2.storefront.mutate(Vn(e2.cartFragment), { variables: { cartId: e2.getCartId(), buyerIdentity: { ...o4, ...t2 }, ...r2 } });
    return E$5(n2, a3);
  };
}
var Vn = (e2 = x$7) => `#graphql
  mutation cartBuyerIdentityUpdate(
    $cartId: ID!
    $buyerIdentity: CartBuyerIdentityInput!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Wt(e2) {
  return async (t2, r2) => {
    let { cartNoteUpdate: o4, errors: n2 } = await e2.storefront.mutate(Mn(e2.cartFragment), { variables: { cartId: e2.getCartId(), note: t2, ...r2 } });
    return E$5(o4, n2);
  };
}
var Mn = (e2 = x$7) => `#graphql
  mutation cartNoteUpdate(
    $cartId: ID!
    $note: String!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartNoteUpdate(cartId: $cartId, note: $note) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function jt(e2) {
  return async (t2, r2) => {
    let { cartSelectedDeliveryOptionsUpdate: o4, errors: n2 } = await e2.storefront.mutate(Hn(e2.cartFragment), { variables: { cartId: e2.getCartId(), selectedDeliveryOptions: t2, ...r2 } });
    return E$5(o4, n2);
  };
}
var Hn = (e2 = x$7) => `#graphql
  mutation cartSelectedDeliveryOptionsUpdate(
    $cartId: ID!
    $selectedDeliveryOptions: [CartSelectedDeliveryOptionInput!]!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartSelectedDeliveryOptionsUpdate(cartId: $cartId, selectedDeliveryOptions: $selectedDeliveryOptions) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Kt(e2) {
  return async (t2, r2) => {
    let { cartAttributesUpdate: o4, errors: n2 } = await e2.storefront.mutate(Fn(e2.cartFragment), { variables: { cartId: (r2 == null ? void 0 : r2.cartId) || e2.getCartId(), attributes: t2 } });
    return E$5(o4, n2);
  };
}
var Fn = (e2 = x$7) => `#graphql
  mutation cartAttributesUpdate(
    $cartId: ID!
    $attributes: [AttributeInput!]!
  ) {
    cartAttributesUpdate(cartId: $cartId, attributes: $attributes) {
      cart {
        ...CartApiMutation
      }
      userErrors {
        ...CartApiError
      }
      warnings {
        ...CartApiWarning
      }
    }
  }
  ${e2}
  ${O$3}
  ${D$5}
`;
function Yt(e2) {
  return async (t2, r2) => {
    let o4 = (r2 == null ? void 0 : r2.cartId) || e2.getCartId(), n2 = t2.map((c2) => ({ ...c2, ownerId: o4 })), { cartMetafieldsSet: a3, errors: s2 } = await e2.storefront.mutate(qn(), { variables: { metafields: n2 } });
    return E$5({ cart: { id: o4 }, ...a3 }, s2);
  };
}
var qn = () => `#graphql
  mutation cartMetafieldsSet(
    $metafields: [CartMetafieldsSetInput!]!
    $language: LanguageCode
    $country: CountryCode
  ) @inContext(country: $country, language: $language) {
    cartMetafieldsSet(metafields: $metafields) {
      userErrors {
        code
        elementIndex
        field
        message
      }
    }
  }
`;
function zt(e2) {
  return async (t2, r2) => {
    let o4 = (r2 == null ? void 0 : r2.cartId) || e2.getCartId(), { cartMetafieldDelete: n2, errors: a3 } = await e2.storefront.mutate($n(), { variables: { input: { ownerId: o4, key: t2 } } });
    return E$5({ cart: { id: o4 }, ...n2 }, a3);
  };
}
var $n = () => `#graphql
  mutation cartMetafieldDelete(
    $input: CartMetafieldDeleteInput!
  ) {
    cartMetafieldDelete(input: $input) {
      userErrors {
        code
        field
        message
      }
    }
  }
`;
var Jt = (e2) => {
  let t2 = u$a(vt(e2, "Cookie") || "");
  return () => t2.cart ? `gid://shopify/Cart/${t2.cart}` : void 0;
};
var Xt = (e2) => (t2) => {
  let r2 = new Headers();
  return r2.append("Set-Cookie", l$8("cart", t2.split("/").pop() || "", { path: "/", ...e2 })), r2;
};
function Zt(e2) {
  let { getCartId: t2, setCartId: r2, storefront: o4, customerAccount: n2, cartQueryFragment: a3, cartMutateFragment: s2 } = e2, c2 = t2(), i2 = () => c2 || t2(), u2 = { storefront: o4, getCartId: i2, cartFragment: s2, customerAccount: n2 }, l2 = Mt(u2), y2 = async function(...d2) {
    var _a2;
    let p2 = await l2(...d2);
    return c2 = (_a2 = p2 == null ? void 0 : p2.cart) == null ? void 0 : _a2.id, p2;
  }, g2 = { get: Ht({ storefront: o4, customerAccount: n2, getCartId: i2, cartFragment: a3 }), getCartId: i2, setCartId: r2, create: y2, addLines: async (d2, p2) => {
    let f2 = d2.map((P2) => ({ attributes: P2.attributes, quantity: P2.quantity, merchandiseId: P2.merchandiseId, sellingPlanId: P2.sellingPlanId }));
    return c2 || (p2 == null ? void 0 : p2.cartId) ? await Ft(u2)(f2, p2) : await y2({ lines: f2 }, p2);
  }, updateLines: qt(u2), removeLines: $t(u2), updateDiscountCodes: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Gt(u2)(d2, p2) : await y2({ discountCodes: d2 }, p2), updateGiftCardCodes: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Bt(u2)(d2, p2) : await y2({ giftCardCodes: d2 }, p2), updateBuyerIdentity: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Qt(u2)(d2, p2) : await y2({ buyerIdentity: d2 }, p2), updateNote: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Wt(u2)(d2, p2) : await y2({ note: d2 }, p2), updateSelectedDeliveryOption: jt(u2), updateAttributes: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Kt(u2)(d2, p2) : await y2({ attributes: d2 }, p2), setMetafields: async (d2, p2) => c2 || (p2 == null ? void 0 : p2.cartId) ? await Yt(u2)(d2, p2) : await y2({ metafields: d2 }, p2), deleteMetafield: zt(u2) };
  return "customMethods" in e2 ? { ...g2, ...e2.customMethods ?? {} } : g2;
}
function Xn({ handle: e2, options: t2 = [], variants: r2 = [], productPath: o4 = "products", waitForNavigation: n2 = false, selectedVariant: a3, children: s2 }) {
  var _a2, _b2;
  let c2 = t2;
  ((_a2 = c2[0]) == null ? void 0 : _a2.values) && (re$1("[h2:warn:VariantSelector] product.options.values is deprecated. Use product.options.optionValues instead."), c2[0] && !c2[0].optionValues && (c2 = t2.map((p2) => {
    var _a3;
    return { ...p2, optionValues: ((_a3 = p2.values) == null ? void 0 : _a3.map((f2) => ({ name: f2 }))) || [] };
  })));
  let i2 = r2 instanceof Array ? r2 : flattenConnection(r2), { searchParams: u2, path: l2, alreadyOnProductPage: y2 } = ea(e2, o4, n2), g2 = c2.filter((p2) => {
    var _a3;
    return ((_a3 = p2 == null ? void 0 : p2.optionValues) == null ? void 0 : _a3.length) === 1;
  }), d2 = a3 ? (_b2 = a3 == null ? void 0 : a3.selectedOptions) == null ? void 0 : _b2.reduce((p2, f2) => (p2[f2.name] = f2.value, p2), {}) : {};
  return reactExports.createElement(reactExports.Fragment, null, ...reactExports.useMemo(() => c2.map((p2) => {
    let f2, P2 = [];
    for (let m2 of p2.optionValues) {
      let C2 = new URLSearchParams(y2 ? u2 : void 0);
      C2.set(p2.name, m2.name), g2.forEach((S2) => {
        S2.optionValues[0].name && C2.set(S2.name, S2.optionValues[0].name);
      });
      let A2 = i2.find((S2) => {
        var _a3;
        return (_a3 = S2 == null ? void 0 : S2.selectedOptions) == null ? void 0 : _a3.every((M2) => (C2.get(M2 == null ? void 0 : M2.name) || (d2 == null ? void 0 : d2[M2 == null ? void 0 : M2.name])) === (M2 == null ? void 0 : M2.value));
      }), T3 = u2.get(p2.name);
      !T3 && a3 && (T3 = (d2 == null ? void 0 : d2[p2.name]) || null);
      let h2 = T3 ? T3 === m2.name : false;
      h2 && (f2 = m2.name);
      let I2 = "?" + C2.toString();
      P2.push({ value: m2.name, optionValue: m2, isAvailable: A2 ? A2.availableForSale : true, to: l2 + I2, search: I2, isActive: h2, variant: A2 });
    }
    return s2({ option: { name: p2.name, value: f2, values: P2 } });
  }), [c2, i2, s2]));
}
var Zn = (e2) => {
  if (typeof (e2 == null ? void 0 : e2.url) > "u") throw new TypeError(`Expected a Request instance, got ${typeof e2}`);
  let t2 = new URL(e2.url).searchParams, r2 = [];
  return t2.forEach((o4, n2) => {
    r2.push({ name: n2, value: o4 });
  }), r2;
};
function ea(e2, t2, r2) {
  let { pathname: o4, search: n2 } = useLocation(), a3 = useNavigation();
  return reactExports.useMemo(() => {
    let s2 = /(\/[a-zA-Z]{2}-[a-zA-Z]{2}\/)/g.exec(o4), c2 = s2 && s2.length > 0;
    t2 = t2.startsWith("/") ? t2.substring(1) : t2;
    let i2 = c2 ? `${s2[0]}${t2}/${e2}` : `/${t2}/${e2}`;
    return { searchParams: new URLSearchParams(r2 || a3.state !== "loading" ? n2 : a3.location.search), alreadyOnProductPage: i2 === o4, path: i2 };
  }, [o4, n2, r2, e2, t2, a3]);
}
var zr = reactExports.createContext(void 0), ua = zr.Provider, er = () => reactExports.useContext(zr);
function pa(e2) {
  let t2 = Ze(), r2 = da(t2, e2);
  return { nonce: t2, header: r2, NonceProvider: ({ children: n2 }) => reactExports.createElement(ua, { value: t2 }, n2) };
}
function da(e2, t2) {
  let { shop: r2, ...o4 } = t2 ?? {}, n2 = `'nonce-${e2}'`, a3 = ["'self'", "'unsafe-inline'", "https://cdn.shopify.com"], s2 = ["'self'", "https://monorail-edge.shopifysvc.com"];
  r2 && r2.checkoutDomain && s2.push(`https://${r2.checkoutDomain}`), r2 && r2.storeDomain && s2.push(`https://${r2.storeDomain}`);
  let i2 = { baseUri: ["'self'"], defaultSrc: ["'self'", n2, "https://cdn.shopify.com", "https://shopify.com"], frameAncestors: ["'none'"], styleSrc: a3, connectSrc: s2 }, u2 = Object.assign({}, i2, o4);
  for (let l2 in i2) {
    let y2 = o4[l2];
    l2 && y2 && (u2[l2] = la(y2, i2[l2]));
  }
  return u2.scriptSrc instanceof Array ? u2.scriptSrc = [...u2.scriptSrc.filter((l2) => !l2.startsWith("'nonce")), n2] : u2.defaultSrc instanceof Array && (u2.defaultSrc = [...u2.defaultSrc.filter((l2) => !l2.startsWith("'nonce")), n2]), buildContentSecurityPolicy({ directives: u2 });
}
function la(e2, t2) {
  let r2 = typeof t2 == "string" ? [t2] : t2, o4 = Array.isArray(e2) ? e2 : [String(e2)];
  return Array.isArray(r2) ? r2.every((a3) => a3 === "'none'") ? o4 : [...o4, ...r2] : r2;
}
reactExports.forwardRef((e2, t2) => {
  let { waitForHydration: r2, src: o4, ...n2 } = e2;
  if (r2) return jsxRuntimeExports.jsx(ga, { src: o4, options: n2 });
  let a3 = er();
  return jsxRuntimeExports.jsx("script", { suppressHydrationWarning: true, ...n2, src: o4, nonce: a3, ref: t2 });
});
function ga({ src: e2, options: t2 }) {
  if (!e2) throw new Error("`waitForHydration` with the Script component requires a `src` prop");
  return useLoadScript(e2, { attributes: t2 }), null;
}
var ss = { canTrack: () => false, cart: null, customData: {}, prevCart: null, publish: () => {
}, shop: null, subscribe: () => {
}, register: () => ({ ready: () => {
} }), customerPrivacy: null, privacyBanner: null };
reactExports.createContext(ss);
async function handleRequest(request, responseStatusCode, responseHeaders, remixContext) {
  const { nonce, header, NonceProvider } = pa({
    connectSrc: [
      "'self'",
      "shopify.com",
      "*.shopify.com",
      "wss://deadly-expert-aardvark.ngrok-free.app:*",
      "https://raw.githack.com",
      "https://fonts.googleapis.com",
      "https://fonts.gstatic.com"
    ],
    fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
    imgSrc: [
      "'self'",
      "data:",
      "cdn.shopify.com",
      "*.shopify.com",
      "https://raw.githack.com",
      "https://durafoam.co.uk",
      "*.durafoam.co.uk"
    ]
  });
  const body = await server_browserExports.renderToReadableStream(
    /* @__PURE__ */ jsxRuntimeExports.jsx(NonceProvider, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(RemixServer, { context: remixContext, url: request.url }) }),
    {
      nonce,
      signal: request.signal,
      onError(error2) {
        console.error(error2);
        responseStatusCode = 500;
      }
    }
  );
  if (isbot(request.headers.get("user-agent"))) {
    await body.allReady;
  }
  responseHeaders.set("Content-Type", "text/html");
  responseHeaders.set("Content-Security-Policy", header);
  return new Response(body, {
    headers: responseHeaders,
    status: responseStatusCode
  });
}
const entryServer = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: handleRequest
}, Symbol.toStringTag, { value: "Module" }));
var g$4 = new TextEncoder(), m$5 = async (t2, e2) => {
  let r2 = await x$6(e2, ["sign"]), n2 = g$4.encode(t2), i2 = await crypto.subtle.sign("HMAC", r2, n2), s2 = btoa(String.fromCharCode(...new Uint8Array(i2))).replace(/=+$/, "");
  return t2 + "." + s2;
}, h$5 = async (t2, e2) => {
  let r2 = t2.lastIndexOf("."), n2 = t2.slice(0, r2), i2 = t2.slice(r2 + 1), s2 = await x$6(e2, ["verify"]), p2 = g$4.encode(n2), u2 = R(atob(i2));
  return await crypto.subtle.verify("HMAC", s2, u2, p2) ? n2 : false;
};
async function x$6(t2, e2) {
  return await crypto.subtle.importKey("raw", g$4.encode(t2), { name: "HMAC", hash: "SHA-256" }, false, e2);
}
function R(t2) {
  let e2 = new Uint8Array(t2.length);
  for (let r2 = 0; r2 < t2.length; r2++) e2[r2] = t2.charCodeAt(r2);
  return e2;
}
var f$9 = createCookieFactory({ sign: m$5, unsign: h$5 }), b$4 = createCookieSessionStorageFactory(f$9);
var v$2 = Error.prototype.toString;
Error.prototype.toString = function() {
  return this.stack || v$2.call(this);
};
var T$4 = "_sfapi_proxy", C$8 = false;
function D$4(t2) {
  C$8 || (C$8 = true, console.warn(t2));
}
function O$2(t2) {
  return Object.entries(t2).map(([e2, r2]) => r2 ? `${e2};desc=${r2}` : void 0).filter(Boolean).join(", ");
}
function M$4(t2, e2) {
  let r2 = typeof e2 == "string" ? e2 : O$2(e2);
  r2 && t2.headers.append("Server-Timing", r2);
}
function _$4({ build: t2, mode: e2, poweredByHeader: r2 = true, getLoadContext: n2, collectTrackingInformation: i2 = true, proxyStandardRoutes: s2 = true }) {
  let p2 = createRequestHandler(t2, e2), u2 = r2 ? (o4) => o4.headers.append("powered-by", "Shopify, Hydrogen") : void 0;
  return async (o4) => {
    var _a2;
    let l2 = o4.method;
    if ((l2 === "GET" || l2 === "HEAD") && o4.body) return new Response(`${l2} requests cannot have a body`, { status: 400 });
    let y2 = new URL(o4.url);
    if (y2.pathname.includes("//")) return new Response(null, { status: 301, headers: { location: y2.pathname.replace(/\/+/g, "/") } });
    let S2 = n2 ? await n2(o4) : void 0, a3 = S2 == null ? void 0 : S2.storefront;
    if (s2 && (a3 || D$4("[h2:createRequestHandler] Storefront instance is required to proxy standard routes."), a3 == null ? void 0 : a3.isStorefrontApiUrl(o4))) {
      let c2 = await a3.forward(o4);
      return u2 == null ? void 0 : u2(c2), c2;
    }
    let d2 = await p2(o4, S2);
    if (a3 && s2) {
      i2 && a3.setCollectedSubrequestHeaders(d2);
      let c2 = o4.headers.get("sec-fetch-dest");
      (c2 && c2 === "document" || ((_a2 = o4.headers.get("accept")) == null ? void 0 : _a2.includes("text/html"))) && M$4(d2, { [T$4]: "1" });
    }
    return u2 == null ? void 0 : u2(d2), d2;
  };
}
function I$6(t2) {
  let e2 = t2.headers;
  return { requestGroupId: e2.get("request-id"), buyerIp: e2.get("oxygen-buyer-ip"), buyerIpSig: e2.get("X-Shopify-Client-IP-Sig"), cookie: e2.get("cookie"), purpose: e2.get("sec-purpose") || e2.get("purpose") };
}
const favicon = "/assets/air-mattress-BBwGL7Mw.png";
const resetStyles = "/assets/reset-BBf-Bt_v.css";
const appStyles = "/assets/app-Bx82CZcu.css";
const tailwindStyles = "/assets/tailwind-BNw4IBpX.css";
function Aside({
  children,
  heading,
  id = "aside"
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { "aria-modal": true, className: "overlay z-[100]", id, role: "dialog", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        className: "close-outside",
        onClick: () => {
          history.go(-1);
          window.location.hash = "";
        }
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("aside", { className: "", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { children: heading }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CloseAside, {})
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("main", { children })
    ] })
  ] });
}
function CloseAside() {
  return (
    /* eslint-disable-next-line jsx-a11y/anchor-is-valid */
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        className: "close",
        onClick: () => {
          window.history.back();
        },
        children: "×"
      }
    )
  );
}
const logoImage$1 = "/assets/logo-white-BVvX7Awl.png";
function AdjustmentsHorizontalIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"
  }));
}
const ForwardRef$o = /* @__PURE__ */ reactExports.forwardRef(AdjustmentsHorizontalIcon);
function ArrowPathIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"
  }));
}
const ForwardRef$n = /* @__PURE__ */ reactExports.forwardRef(ArrowPathIcon);
function Bars3Icon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
  }));
}
const ForwardRef$m = /* @__PURE__ */ reactExports.forwardRef(Bars3Icon);
function CheckCircleIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
  }));
}
const ForwardRef$l = /* @__PURE__ */ reactExports.forwardRef(CheckCircleIcon$1);
function ChevronRightIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "m8.25 4.5 7.5 7.5-7.5 7.5"
  }));
}
const ForwardRef$k = /* @__PURE__ */ reactExports.forwardRef(ChevronRightIcon);
function EnvelopeIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75"
  }));
}
const ForwardRef$j = /* @__PURE__ */ reactExports.forwardRef(EnvelopeIcon$1);
function ExclamationCircleIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"
  }));
}
const ForwardRef$i = /* @__PURE__ */ reactExports.forwardRef(ExclamationCircleIcon);
function HeartIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"
  }));
}
const ForwardRef$h = /* @__PURE__ */ reactExports.forwardRef(HeartIcon);
function MagnifyingGlassIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
  }));
}
const ForwardRef$g = /* @__PURE__ */ reactExports.forwardRef(MagnifyingGlassIcon$1);
function MapPinIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
  }), /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1 1 15 0Z"
  }));
}
const ForwardRef$f = /* @__PURE__ */ reactExports.forwardRef(MapPinIcon$1);
function PhoneIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z"
  }));
}
const ForwardRef$e = /* @__PURE__ */ reactExports.forwardRef(PhoneIcon$1);
function PlusIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M12 4.5v15m7.5-7.5h-15"
  }));
}
const ForwardRef$d = /* @__PURE__ */ reactExports.forwardRef(PlusIcon);
function ShieldCheckIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M9 12.75 11.25 15 15 9.75m-3-7.036A11.959 11.959 0 0 1 3.598 6 11.99 11.99 0 0 0 3 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285Z"
  }));
}
const ForwardRef$c = /* @__PURE__ */ reactExports.forwardRef(ShieldCheckIcon);
function ShoppingCartIcon$1({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z"
  }));
}
const ForwardRef$b = /* @__PURE__ */ reactExports.forwardRef(ShoppingCartIcon$1);
function TruckIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M8.25 18.75a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 0 1-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m3 0h1.125c.621 0 1.129-.504 1.09-1.124a17.902 17.902 0 0 0-3.213-9.193 2.056 2.056 0 0 0-1.58-.86H14.25M16.5 18.75h-2.25m0-11.177v-.958c0-.568-.422-1.048-.987-1.106a48.554 48.554 0 0 0-10.026 0 1.106 1.106 0 0 0-.987 1.106v7.635m12-6.677v6.677m0 4.5v-4.5m0 0h-12"
  }));
}
const ForwardRef$a = /* @__PURE__ */ reactExports.forwardRef(TruckIcon);
function UserIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z"
  }));
}
const ForwardRef$9 = /* @__PURE__ */ reactExports.forwardRef(UserIcon);
function XMarkIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    strokeWidth: 1.5,
    stroke: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    strokeLinecap: "round",
    strokeLinejoin: "round",
    d: "M6 18 18 6M6 6l12 12"
  }));
}
const ForwardRef$8 = /* @__PURE__ */ reactExports.forwardRef(XMarkIcon);
const navigation = {
  company: [
    { name: "About Durafoam", href: "/pages/about-us" },
    { name: "Our Blog", href: "/blogs/news" }
  ]
};
function NewFooter({
  shopMenu,
  legalMenu,
  shop
}) {
  var _a2;
  const { publicStoreDomain } = useRootLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("footer", { className: "bg-brand-dark text-white pt-6 pb-8 px-4 sm:px-6 lg:px-12 mt-20 rounded-t-[3rem] shadow-2xl overflow-hidden relative", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-0 right-0 w-full h-1 bg-gradient-to-r from-transparent via-primary-500 to-transparent opacity-50" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-0 right-0 -translate-y-1/2 translate-x-1/4 w-[800px] h-[800px] bg-primary-600/10 rounded-full blur-[120px] pointer-events-none" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute bottom-0 left-0 translate-y-1/2 -translate-x-1/4 w-96 h-96 bg-blue-600/10 rounded-full blur-[80px] pointer-events-none" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-[90rem] mx-auto relative z-10", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "my-10 bg-white/5 backdrop-blur-xl border border-white/10 rounded-[2.5rem] p-8 lg:p-12 flex flex-col lg:flex-row items-center justify-between gap-8 shadow-2xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-2xl text-center lg:text-left", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-3xl font-extrabold font-heading tracking-tight", children: [
            "Stay updated with",
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-400", children: "Durafoam" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-3 text-slate-400 text-lg", children: "Join our newsletter for exclusive discounts, new product announcements, and foam-cutting tips." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { className: "w-full lg:w-auto flex flex-col sm:flex-row gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              type: "email",
              placeholder: "Enter your email address",
              className: "px-6 py-4 bg-black/40 border border-white/10 rounded-2xl text-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-all sm:w-80"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: "px-8 py-4 bg-primary-600 hover:bg-primary-500 text-white font-bold rounded-2xl transition-all shadow-lg shadow-primary-600/20 active:scale-95",
              children: "Subscribe"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-12 gap-16 lg:gap-12 py-12", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-4 space-y-8", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("img", { className: "h-10 w-auto", src: logoImage$1, alt: "Durafoam" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-slate-400 text-base leading-relaxed max-w-sm", children: "The UK's leading provider of premium, sustainable, and affordable foam. Custom cut to your exact requirements with millimeter precision." }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 pt-4 border-t border-white/10", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: "tel:+441592328630",
                className: "flex items-center gap-4 text-slate-300 hover:text-white transition-colors group",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-white/5 border border-white/10 rounded-xl group-hover:bg-primary-600 group-hover:border-primary-500 transition-all shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$e, { className: "h-5 w-5", "aria-hidden": "true" }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-0.5", children: "Call Us" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold", children: "01592 328630" })
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: "mailto:info@durafoam.co.uk",
                className: "flex items-center gap-4 text-slate-300 hover:text-white transition-colors group",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-white/5 border border-white/10 rounded-xl group-hover:bg-blue-600 group-hover:border-blue-500 transition-all shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$j, { className: "h-5 w-5", "aria-hidden": "true" }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-0.5", children: "Email Us" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold", children: "info@durafoam.co.uk" })
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: "https://www.google.com/maps/place/63+Cavendish+Way,+Glenrothes+KY6+2SB",
                target: "_blank",
                rel: "noreferrer",
                className: "flex items-center gap-4 text-slate-300 hover:text-white transition-colors group",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-white/5 border border-white/10 rounded-xl group-hover:bg-slate-600 group-hover:border-slate-500 transition-all shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$f, { className: "h-5 w-5", "aria-hidden": "true" }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-0.5", children: "Location" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold leading-tight", children: "63 Cavendish Way, Glenrothes KY6 2SB" })
                  ] })
                ]
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-8 flex flex-wrap sm:grid sm:grid-cols-3 gap-12 sm:gap-8", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-full sm:w-auto space-y-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xs font-black uppercase tracking-widest text-primary-400", children: "Shop Collections" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-4", children: (_a2 = shopMenu == null ? void 0 : shopMenu.items) == null ? void 0 : _a2.map((item) => {
              var _a3;
              if (!item.url) return null;
              const url = item.url.includes("myshopify.com") || item.url.includes(publicStoreDomain) || item.url.includes((_a3 = shop == null ? void 0 : shop.primaryDomain) == null ? void 0 : _a3.url) ? new URL(item.url).pathname : item.url;
              return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                NavLink,
                {
                  className: "text-sm font-medium text-slate-400 hover:text-primary-400 transition-colors flex items-center gap-2 group",
                  prefetch: "intent",
                  to: url,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "w-1.5 h-1.5 rounded-full bg-slate-700 group-hover:bg-primary-500 transition-colors" }),
                    item.title
                  ]
                }
              ) }, item.id);
            }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-1/2 sm:w-auto space-y-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xs font-black uppercase tracking-widest text-slate-300", children: "Company" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-4", children: navigation.company.map((item) => /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: item.href,
                className: "text-sm font-medium text-slate-400 hover:text-white transition-colors",
                children: item.name
              }
            ) }, item.name)) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-1/2 sm:w-auto space-y-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xs font-black uppercase tracking-widest text-slate-300", children: "Support & Legal" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-4", children: (legalMenu || FALLBACK_FOOTER_MENU).items.map((item) => {
              var _a3;
              if (!item.url) return null;
              const url = item.url.includes("myshopify.com") || item.url.includes(publicStoreDomain) || item.url.includes((_a3 = shop == null ? void 0 : shop.primaryDomain) == null ? void 0 : _a3.url) ? new URL(item.url).pathname : item.url;
              return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                NavLink,
                {
                  className: "text-sm font-medium text-slate-400 hover:text-white transition-colors",
                  prefetch: "intent",
                  to: url,
                  children: item.title
                }
              ) }, item.id);
            }) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-8 pt-8 border-t border-white/5 flex flex-col md:flex-row justify-between items-center gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs font-medium text-slate-500", children: [
          "© ",
          (/* @__PURE__ */ new Date()).getFullYear(),
          " Durafoam. All rights reserved."
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-3 py-1 rounded-full bg-white/5 border border-white/10 text-[10px] font-bold text-slate-400 tracking-widest uppercase", children: "Secure Checkout" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-3 py-1 rounded-full bg-white/5 border border-white/10 text-[10px] font-bold text-slate-400 tracking-widest uppercase", children: "Made in UK" })
        ] })
      ] })
    ] })
  ] });
}
const FALLBACK_FOOTER_MENU = {
  items: [
    {
      id: "gid://shopify/MenuItem/461633060920",
      resourceId: "gid://shopify/ShopPolicy/23358046264",
      tags: [],
      title: "Privacy Policy",
      type: "SHOP_POLICY",
      url: "/policies/privacy-policy",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461633093688",
      resourceId: "gid://shopify/ShopPolicy/23358013496",
      tags: [],
      title: "Refund Policy",
      type: "SHOP_POLICY",
      url: "/policies/refund-policy",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461633126456",
      resourceId: "gid://shopify/ShopPolicy/23358111800",
      tags: [],
      title: "Shipping Policy",
      type: "SHOP_POLICY",
      url: "/policies/shipping-policy",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461633159224",
      resourceId: "gid://shopify/ShopPolicy/23358079032",
      tags: [],
      title: "Terms of Service",
      type: "SHOP_POLICY",
      url: "/policies/terms-of-service",
      items: []
    }
  ]
};
const logoImage = "/assets/logo-DtJBN_Q4.png";
function EnvelopeIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    d: "M1.5 8.67v8.58a3 3 0 0 0 3 3h15a3 3 0 0 0 3-3V8.67l-8.928 5.493a3 3 0 0 1-3.144 0L1.5 8.67Z"
  }), /* @__PURE__ */ reactExports.createElement("path", {
    d: "M22.5 6.908V6.75a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3v.158l9.714 5.978a1.5 1.5 0 0 0 1.572 0L22.5 6.908Z"
  }));
}
const ForwardRef$7 = /* @__PURE__ */ reactExports.forwardRef(EnvelopeIcon);
function MapPinIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "m11.54 22.351.07.04.028.016a.76.76 0 0 0 .723 0l.028-.015.071-.041a16.975 16.975 0 0 0 1.144-.742 19.58 19.58 0 0 0 2.683-2.282c1.944-1.99 3.963-4.98 3.963-8.827a8.25 8.25 0 0 0-16.5 0c0 3.846 2.02 6.837 3.963 8.827a19.58 19.58 0 0 0 2.682 2.282 16.975 16.975 0 0 0 1.145.742ZM12 13.5a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef$6 = /* @__PURE__ */ reactExports.forwardRef(MapPinIcon);
function PhoneIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "M1.5 4.5a3 3 0 0 1 3-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 0 1-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 0 0 6.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 0 1 1.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 0 1-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef$5 = /* @__PURE__ */ reactExports.forwardRef(PhoneIcon);
function StarIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef$4 = /* @__PURE__ */ reactExports.forwardRef(StarIcon);
function Banner() {
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative isolate flex items-center justify-end gap-x-6 overflow-hidden bg-white/40 backdrop-blur-md border-b border-slate-200/50 px-6 py-2 sm:px-12", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center justify-end gap-x-4 gap-y-1 text-xs font-bold text-slate-600", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "a",
      {
        href: "tel:+441592328630",
        className: "flex items-center gap-1.5 hover:text-primary-600 transition-colors",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ForwardRef$5,
            {
              className: "h-3.5 w-3.5 text-primary-500",
              "aria-hidden": "true"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "01592 328630" })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "hidden sm:inline text-slate-300", children: "|" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "a",
      {
        href: "mailto:info@durafoam.co.uk",
        className: "flex items-center gap-1.5 hover:text-primary-600 transition-colors",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ForwardRef$7,
            {
              className: "h-3.5 w-3.5 text-primary-500",
              "aria-hidden": "true"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "info@durafoam.co.uk" })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "hidden lg:inline text-slate-300", children: "|" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "a",
      {
        href: "https://www.google.com/maps/place/63+Cavendish+Way,+Glenrothes+KY6+2SB",
        className: "hidden lg:flex items-center gap-1.5 hover:text-primary-600 transition-colors",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ForwardRef$6,
            {
              className: "h-3.5 w-3.5 text-primary-500",
              "aria-hidden": "true"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Glenrothes, KY6 2SB" })
        ]
      }
    )
  ] }) });
}
function Header({ header, isLoggedIn, cart }) {
  const { shop, menu } = header;
  const [isScrolled, setIsScrolled] = reactExports.useState(false);
  reactExports.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 20);
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Banner, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "header",
      {
        className: `sticky top-0 z-50 transition-all duration-300 ${isScrolled ? "bg-white/90 backdrop-blur-md shadow-premium py-2" : "bg-white py-5"}`,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center h-full", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-[1] flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            NavLink,
            {
              prefetch: "intent",
              to: "/",
              className: "flex-shrink-0 group",
              end: true,
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "img",
                {
                  className: "h-8 w-auto md:h-9 transition-transform duration-300 group-hover:scale-105",
                  src: logoImage,
                  alt: "Durafoam Logo"
                }
              )
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "hidden lg:flex flex-[2] justify-center items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            HeaderMenu,
            {
              menu,
              viewport: "desktop",
              primaryDomainUrl: header.shop.primaryDomain.url
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-[1] flex items-center justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(HeaderCtas, { isLoggedIn, cart }) })
        ] })
      }
    )
  ] });
}
function HeaderMenu({
  menu,
  primaryDomainUrl,
  viewport
}) {
  const { publicStoreDomain } = useRootLoaderData();
  const className = viewport !== "mobile" ? "hidden lg:flex items-center gap-1" : "flex flex-col gap-2 p-4";
  function closeAside(event) {
  }
  const menuItems = (menu || FALLBACK_HEADER_MENU).items;
  return /* @__PURE__ */ jsxRuntimeExports.jsx("nav", { className, role: "navigation", children: menuItems.map((item) => {
    if (!item.url) return null;
    const url = item.url.includes("myshopify.com") || item.url.includes(publicStoreDomain) || item.url.includes(primaryDomainUrl) ? new URL(item.url).pathname : item.url;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      NavLink,
      {
        className: ({ isActive }) => `
              px-4 py-2 text-sm font-medium transition-all rounded-full
              ${isActive ? "text-primary-600 bg-primary-50" : "text-slate-600 hover:text-primary-600 hover:bg-slate-50"}
            `,
        end: true,
        onClick: closeAside,
        prefetch: "intent",
        to: url,
        children: item.title
      },
      item.id
    );
  }) });
}
function HeaderCtas({
  isLoggedIn,
  cart
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "hidden sm:flex items-center gap-2 mr-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        NavLink,
        {
          prefetch: "intent",
          to: "/account",
          className: "p-2 text-slate-600 hover:text-primary-600 transition-colors",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$9, { className: "h-6 w-6" })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Link,
        {
          prefetch: "intent",
          to: "/search",
          className: "p-2 text-slate-600 hover:text-primary-600 transition-colors",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$g, { className: "h-6 w-6" })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CartToggle, { cart }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:hidden ml-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(HeaderMenuMobileToggle, {}) })
  ] });
}
function HeaderMenuMobileToggle() {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "a",
    {
      className: "p-2 text-slate-600 hover:text-primary-600 flex items-center justify-center bg-slate-50 rounded-xl",
      href: "#mobile-menu-aside",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$m, { className: "h-6 w-6" })
    }
  );
}
function CartBadge({ count }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: "/cart?cartOpen=false", className: "group relative", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-2.5 bg-primary-600 text-white rounded-2xl shadow-lg shadow-primary-200 hover:bg-primary-700 transition-all hover:-translate-y-0.5 active:scale-95 flex items-center gap-2 pr-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$b, { className: "h-5 w-5", "aria-hidden": "true" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold", children: count })
  ] }) });
}
function CartToggle({ cart }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(CartBadge, { count: 0 }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: cart, children: (cart2) => {
    if (!cart2) return /* @__PURE__ */ jsxRuntimeExports.jsx(CartBadge, { count: 0 });
    return /* @__PURE__ */ jsxRuntimeExports.jsx(CartBadge, { count: cart2.totalQuantity || 0 });
  } }) });
}
const FALLBACK_HEADER_MENU = {
  items: [
    {
      id: "gid://shopify/MenuItem/461609500728",
      resourceId: null,
      tags: [],
      title: "Collections",
      type: "HTTP",
      url: "/collections",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461609533496",
      resourceId: null,
      tags: [],
      title: "Blog",
      type: "HTTP",
      url: "/blogs/journal",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461609566264",
      resourceId: null,
      tags: [],
      title: "Policies",
      type: "HTTP",
      url: "/policies",
      items: []
    },
    {
      id: "gid://shopify/MenuItem/461609599032",
      resourceId: "gid://shopify/Page/92591030328",
      tags: [],
      title: "About",
      type: "PAGE",
      url: "/pages/about",
      items: []
    }
  ]
};
function useVariantUrl(handle, selectedOptions) {
  const { pathname } = useLocation();
  return reactExports.useMemo(() => {
    return getVariantUrl({
      handle,
      pathname,
      searchParams: new URLSearchParams(),
      selectedOptions
    });
  }, [handle, selectedOptions, pathname]);
}
function getVariantUrl({
  handle,
  pathname,
  searchParams,
  selectedOptions
}) {
  const match = /(\/[a-zA-Z]{2}-[a-zA-Z]{2}\/)/g.exec(pathname);
  const isLocalePathname = match && match.length > 0;
  const path = isLocalePathname ? `${match[0]}products/${handle}` : `/products/${handle}`;
  selectedOptions.forEach((option) => {
    searchParams.set(option.name, option.value);
  });
  const searchString = searchParams.toString();
  return path + (searchString ? "?" + searchParams.toString() : "");
}
function CheckCircleIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 20 20",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef$3 = /* @__PURE__ */ reactExports.forwardRef(CheckCircleIcon);
function CheckIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 20 20",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef$2 = /* @__PURE__ */ reactExports.forwardRef(CheckIcon);
function ShoppingCartIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 20 20",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    d: "M1 1.75A.75.75 0 0 1 1.75 1h1.628a1.75 1.75 0 0 1 1.734 1.51L5.18 3a65.25 65.25 0 0 1 13.36 1.412.75.75 0 0 1 .58.875 48.645 48.645 0 0 1-1.618 6.2.75.75 0 0 1-.712.513H6a2.503 2.503 0 0 0-2.292 1.5H17.25a.75.75 0 0 1 0 1.5H2.76a.75.75 0 0 1-.748-.807 4.002 4.002 0 0 1 2.716-3.486L3.626 2.716a.25.25 0 0 0-.248-.216H1.75A.75.75 0 0 1 1 1.75ZM6 17.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0ZM15.5 19a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"
  }));
}
const ForwardRef$1 = /* @__PURE__ */ reactExports.forwardRef(ShoppingCartIcon);
function EmptyCart() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center h-full flex flex-col items-center justify-center", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$1, { className: "mx-auto size-12 text-gray-400" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "mt-2 text-sm font-semibold text-gray-900", children: "Your cart is empty" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-500", children: "Start shopping to add items to your cart." })
  ] });
}
const placeholderImg = "/assets/placeholder-B3DCLFxA.png";
function CartMain({ layout, cart }) {
  var _a2, _b2, _c, _d;
  const linesCount = Boolean(((_b2 = (_a2 = cart == null ? void 0 : cart.lines) == null ? void 0 : _a2.nodes) == null ? void 0 : _b2.length) || 0);
  cart && Boolean((_d = (_c = cart == null ? void 0 : cart.discountCodes) == null ? void 0 : _c.filter((code) => code.applicable)) == null ? void 0 : _d.length);
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-2xl px-4 py-16 sm:px-6 sm:py-24 lg:px-0", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-center text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl", children: "Shopping Cart" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("form", { className: "mt-12", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { "aria-labelledby": "cart-heading", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "cart-heading", className: "sr-only", children: "Items in your shopping cart" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartEmpty, { hidden: linesCount, layout }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartDetails, { cart, layout })
    ] }) })
  ] }) });
}
function CartDetails({ layout, cart }) {
  const cartHasItems = !!cart && cart.totalQuantity > 0;
  if (!cartHasItems) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CartLines, { lines: cart == null ? void 0 : cart.lines, layout }),
    cartHasItems && /* @__PURE__ */ jsxRuntimeExports.jsxs(CartSummary, { cost: cart.cost, layout, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartDiscounts, { discountCodes: cart.discountCodes }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartCheckoutActions, { checkoutUrl: cart.checkoutUrl })
    ] })
  ] });
}
function CartLines({
  lines,
  layout
}) {
  if (!lines) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "ul",
    {
      role: "list",
      className: "divide-y divide-gray-200 border-b border-t border-gray-200",
      children: lines.nodes.map((line) => /* @__PURE__ */ jsxRuntimeExports.jsx(CartLineItem, { line, layout }, line.id))
    }
  );
}
function CartLineItem({
  layout,
  line
}) {
  const { id, merchandise } = line;
  const { product, title, image, selectedOptions } = merchandise;
  const lineItemUrl = useVariantUrl(product.handle, selectedOptions);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex py-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "shrink-0", children: image ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      Image,
      {
        alt: title,
        aspectRatio: "1/1",
        data: image,
        className: "size-24 rounded-md object-cover sm:size-32",
        loading: "lazy"
      }
    ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        src: placeholderImg,
        alt: title,
        className: "size-24 rounded-md object-cover sm:size-32 opacity-50 bg-gray-50 border border-gray-100"
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ml-4 flex flex-1 flex-col sm:ml-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Link,
            {
              prefetch: "intent",
              to: lineItemUrl,
              onClick: () => {
                if (layout === "aside") {
                  window.location.href = lineItemUrl;
                }
              },
              className: "font-medium text-gray-700 hover:text-gray-800",
              children: product.title
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            CartLinePrice,
            {
              line,
              as: "p",
              className: "ml-4 text-sm font-medium text-gray-900"
            }
          )
        ] }),
        selectedOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1 text-sm text-gray-500", children: [
          option.name,
          ": ",
          option.value
        ] }, option.name))
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 flex flex-1 items-end justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "flex items-center space-x-2 text-sm text-gray-700", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ForwardRef$2,
            {
              "aria-hidden": "true",
              className: "size-5 shrink-0 text-green-500"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "In stock" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CartLineRemoveButton, { lineIds: [id] }) })
      ] })
    ] })
  ] }, id);
}
function CartCheckoutActions({ checkoutUrl }) {
  if (!checkoutUrl) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-10", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        href: checkoutUrl,
        target: "_self",
        className: "w-full rounded-md border border-transparent bg-blue-600 px-4 py-3 text-base font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-50",
        children: "Checkout"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6 text-center text-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { children: [
      "or",
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: "/collections",
          className: "font-medium text-blue-600 hover:text-blue-500",
          children: [
            "Continue Shopping",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-hidden": "true", children: " →" })
          ]
        }
      )
    ] }) })
  ] });
}
function CartSummary({
  cost,
  layout,
  children = null
}) {
  var _a2;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { "aria-labelledby": "summary-heading", className: "mt-10", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "summary-heading", className: "sr-only", children: "Order summary" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-base font-medium text-gray-900", children: "Subtotal" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "ml-4 text-base font-medium text-gray-900", children: ((_a2 = cost == null ? void 0 : cost.subtotalAmount) == null ? void 0 : _a2.amount) ? /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: cost == null ? void 0 : cost.subtotalAmount }) : "-" })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-500", children: "Shipping and taxes will be calculated at checkout." })
    ] }),
    children
  ] });
}
function CartLineRemoveButton({ lineIds }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    J$1,
    {
      route: "/cart",
      action: J$1.ACTIONS.LinesRemove,
      inputs: { lineIds },
      children: (fetcher) => {
        const isLoading = fetcher.state !== "idle";
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "submit",
            className: "font-medium text-blue-600 hover:text-blue-500",
            disabled: isLoading,
            children: isLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-4 animate-spin rounded-full border-2 border-blue-600 border-t-transparent" }) : "Remove"
          }
        );
      }
    }
  );
}
function CartLineQuantity({ line }) {
  if (!line || typeof (line == null ? void 0 : line.quantity) === "undefined") return null;
  const { id: lineId, quantity } = line;
  Number(Math.max(0, quantity - 1).toFixed(0));
  Number((quantity + 1).toFixed(0));
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-1 flex-row", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("small", { children: [
      "Quantity: ",
      quantity
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CartLineRemoveButton, { lineIds: [lineId] })
  ] });
}
function CartLinePrice({
  line,
  priceType = "regular",
  ...passthroughProps
}) {
  var _a2, _b2;
  if (!((_a2 = line == null ? void 0 : line.cost) == null ? void 0 : _a2.amountPerQuantity) || !((_b2 = line == null ? void 0 : line.cost) == null ? void 0 : _b2.totalAmount)) return null;
  const moneyV2 = priceType === "regular" ? line.cost.totalAmount : line.cost.compareAtAmountPerQuantity;
  if (moneyV2 == null || typeof moneyV2.amount === "undefined") {
    return null;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { withoutTrailingZeros: true, ...passthroughProps, data: moneyV2 });
}
function CartEmpty({
  hidden = false,
  layout = "aside"
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { hidden, className: "text-center", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyCart, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Link,
      {
        to: "/collections",
        onClick: () => {
          if (layout === "aside") {
            window.location.href = "/collections";
          }
        },
        className: "text-sm font-medium text-blue-600 hover:text-blue-500",
        children: "Continue shopping →"
      }
    ) })
  ] });
}
function CartDiscounts({
  discountCodes
}) {
  var _a2;
  const codes = ((_a2 = discountCodes == null ? void 0 : discountCodes.filter((discount) => discount.applicable)) == null ? void 0 : _a2.map(({ code }) => code)) || [];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { hidden: !codes.length, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-sm font-medium text-gray-900", children: "Discount(s)" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(UpdateDiscountForm, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "cart-discount", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-sm text-gray-500", children: codes == null ? void 0 : codes.join(", ") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "ml-2 text-sm font-medium text-blue-600 hover:text-blue-500", children: "Remove" })
      ] }) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(UpdateDiscountForm, { discountCodes: codes, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 flex", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          type: "text",
          name: "discountCode",
          placeholder: "Discount code",
          className: "block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "submit",
          className: "ml-4 flex-none rounded-md bg-blue-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600",
          children: "Apply"
        }
      )
    ] }) })
  ] });
}
function UpdateDiscountForm({
  discountCodes,
  children
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    J$1,
    {
      route: "/cart",
      action: J$1.ACTIONS.DiscountCodesUpdate,
      inputs: {
        discountCodes: discountCodes || []
      },
      children
    }
  );
}
function applyTrackingParams(resource, params) {
  if (params) {
    return (resource == null ? void 0 : resource.trackingParameters) ? `?${params}&${resource.trackingParameters}` : `?${params}`;
  } else {
    return (resource == null ? void 0 : resource.trackingParameters) ? `?${resource.trackingParameters}` : "";
  }
}
function MagnifyingGlassIcon({
  title,
  titleId,
  ...props
}, svgRef) {
  return /* @__PURE__ */ reactExports.createElement("svg", Object.assign({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 16 16",
    fill: "currentColor",
    "aria-hidden": "true",
    "data-slot": "icon",
    ref: svgRef,
    "aria-labelledby": titleId
  }, props), title ? /* @__PURE__ */ reactExports.createElement("title", {
    id: titleId
  }, title) : null, /* @__PURE__ */ reactExports.createElement("path", {
    fillRule: "evenodd",
    d: "M9.965 11.026a5 5 0 1 1 1.06-1.06l2.755 2.754a.75.75 0 1 1-1.06 1.06l-2.755-2.754ZM10.5 7a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Z",
    clipRule: "evenodd"
  }));
}
const ForwardRef = /* @__PURE__ */ reactExports.forwardRef(MagnifyingGlassIcon);
const NO_PREDICTIVE_SEARCH_RESULTS = [
  { type: "products", items: [] },
  { type: "collections", items: [] }
];
function SearchForm({ searchTerm }) {
  const inputRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    function handleKeyDown(event) {
      var _a2, _b2;
      if (event.key === "k" && event.metaKey) {
        event.preventDefault();
        (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
      }
      if (event.key === "Escape") {
        (_b2 = inputRef.current) == null ? void 0 : _b2.blur();
      }
    }
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Form, { method: "get", className: "flex", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "-mr-px grid grow grid-cols-1 focus-within:relative", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          id: "search",
          defaultValue: searchTerm,
          name: "q",
          placeholder: "Search...",
          ref: inputRef,
          type: "search",
          className: "col-start-1 row-start-1 block w-full rounded-l-md bg-white py-1.5 pl-10 pr-3 text-xl text-gray-900 outline outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-blue-600 sm:pl-9"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ForwardRef,
        {
          "aria-hidden": "true",
          className: "pointer-events-none col-start-1 row-start-1 ml-3 size-5 self-center text-gray-400 sm:size-4"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "submit",
        className: "flex shrink-0 items-center gap-x-1.5 rounded-r-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 outline outline-1 -outline-offset-1 outline-gray-300 hover:bg-gray-50 focus:relative focus:outline-2 focus:-outline-offset-2 focus:outline-blue-600",
        children: "Search"
      }
    )
  ] });
}
function SearchResults({
  results,
  searchTerm
}) {
  if (!results) {
    return null;
  }
  const keys = Object.keys(results);
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pb-24", children: results && keys.map((type) => {
    var _a2;
    const resourceResults = results[type];
    if (((_a2 = resourceResults.nodes[0]) == null ? void 0 : _a2.__typename) === "Product") {
      const productResults = resourceResults;
      return resourceResults.nodes.length ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        SearchResultsProductsGrid,
        {
          products: productResults,
          searchTerm
        },
        "products"
      ) : null;
    }
    return null;
  }) });
}
function SearchResultsProductsGrid({
  products,
  searchTerm
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "mt-4 text-2xl font-bold", children: "Products" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6 grid grid-cols-2 gap-x-6 gap-y-6 md:grid-cols-4 xl:gap-x-8", children: products.nodes.map((product) => {
      const trackingParams = applyTrackingParams(
        product,
        `q=${encodeURIComponent(searchTerm)}`
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        Link,
        {
          className: "recommended-product",
          to: `/products/${product.handle}${trackingParams}`,
          prefetch: "intent",
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "group relative", children: [
            product.variants.nodes[0].image && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Image,
              {
                data: product.variants.nodes[0].image,
                aspectRatio: "1/1",
                sizes: "(min-width: 45em) 20vw, 50vw",
                className: "group-hover:scale-105 transition-all"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-sm text-gray-700", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-hidden": "true", className: "absolute inset-0" }),
                product.title
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.variants.nodes[0].price }) })
            ] })
          ] })
        },
        product.id
      );
    }) })
  ] });
}
function NoSearchResults() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center h-full flex flex-col items-center justify-center py-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$i, { className: "mx-auto size-12 text-gray-400" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "mt-2 text-sm font-semibold text-gray-900", children: "No search results found" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-500", children: "Try searching for something else." })
  ] });
}
function NoSearchTerm() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center h-full flex flex-col items-center justify-center py-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef, { className: "mx-auto size-12 text-gray-400" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "mt-2 text-sm font-semibold text-gray-900", children: "Search for products" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-500", children: "Enter a search term to find products." })
  ] });
}
const $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c = typeof document !== "undefined" ? React.useLayoutEffect : () => {
};
const $431fbd86ca7dc216$export$b204af158042fbac = (el) => {
  var _el_ownerDocument;
  return (_el_ownerDocument = el === null || el === void 0 ? void 0 : el.ownerDocument) !== null && _el_ownerDocument !== void 0 ? _el_ownerDocument : document;
};
const $431fbd86ca7dc216$export$f21a1ffae260145a = (el) => {
  if (el && "window" in el && el.window === el) return el;
  const doc = $431fbd86ca7dc216$export$b204af158042fbac(el);
  return doc.defaultView || window;
};
function $431fbd86ca7dc216$var$isNode(value) {
  return value !== null && typeof value === "object" && "nodeType" in value && typeof value.nodeType === "number";
}
function $431fbd86ca7dc216$export$af51f0f06c0f328a(node) {
  return $431fbd86ca7dc216$var$isNode(node) && node.nodeType === Node.DOCUMENT_FRAGMENT_NODE && "host" in node;
}
let $f4e2df6bd15f8569$var$_shadowDOM = false;
function $f4e2df6bd15f8569$export$98658e8c59125e6a() {
  return $f4e2df6bd15f8569$var$_shadowDOM;
}
function $d4ee10de306f2510$export$4282f70798064fe0(node, otherNode) {
  if (!$f4e2df6bd15f8569$export$98658e8c59125e6a()) return otherNode && node ? node.contains(otherNode) : false;
  if (!node || !otherNode) return false;
  let currentNode = otherNode;
  while (currentNode !== null) {
    if (currentNode === node) return true;
    if (currentNode.tagName === "SLOT" && currentNode.assignedSlot)
      currentNode = currentNode.assignedSlot.parentNode;
    else if ($431fbd86ca7dc216$export$af51f0f06c0f328a(currentNode))
      currentNode = currentNode.host;
    else currentNode = currentNode.parentNode;
  }
  return false;
}
const $d4ee10de306f2510$export$cd4e5573fbe2b576 = (doc = document) => {
  var _activeElement_shadowRoot;
  if (!$f4e2df6bd15f8569$export$98658e8c59125e6a()) return doc.activeElement;
  let activeElement = doc.activeElement;
  while (activeElement && "shadowRoot" in activeElement && ((_activeElement_shadowRoot = activeElement.shadowRoot) === null || _activeElement_shadowRoot === void 0 ? void 0 : _activeElement_shadowRoot.activeElement)) activeElement = activeElement.shadowRoot.activeElement;
  return activeElement;
};
function $d4ee10de306f2510$export$e58f029f0fbfdb29(event) {
  if ($f4e2df6bd15f8569$export$98658e8c59125e6a() && event.target instanceof Element && event.target.shadowRoot) {
    var _event_composedPath_, _event_nativeEvent_composedPath_;
    if ("composedPath" in event) return (_event_composedPath_ = event.composedPath()[0]) !== null && _event_composedPath_ !== void 0 ? _event_composedPath_ : null;
    else if ("composedPath" in event.nativeEvent) return (_event_nativeEvent_composedPath_ = event.nativeEvent.composedPath()[0]) !== null && _event_nativeEvent_composedPath_ !== void 0 ? _event_nativeEvent_composedPath_ : null;
  }
  return event.target;
}
function $7215afc6de606d6b$export$de79e2c695e052f3(element) {
  if ($7215afc6de606d6b$var$supportsPreventScroll()) element.focus({
    preventScroll: true
  });
  else {
    let scrollableElements = $7215afc6de606d6b$var$getScrollableElements(element);
    element.focus();
    $7215afc6de606d6b$var$restoreScrollPosition(scrollableElements);
  }
}
let $7215afc6de606d6b$var$supportsPreventScrollCached = null;
function $7215afc6de606d6b$var$supportsPreventScroll() {
  if ($7215afc6de606d6b$var$supportsPreventScrollCached == null) {
    $7215afc6de606d6b$var$supportsPreventScrollCached = false;
    try {
      let focusElem = document.createElement("div");
      focusElem.focus({
        get preventScroll() {
          $7215afc6de606d6b$var$supportsPreventScrollCached = true;
          return true;
        }
      });
    } catch {
    }
  }
  return $7215afc6de606d6b$var$supportsPreventScrollCached;
}
function $7215afc6de606d6b$var$getScrollableElements(element) {
  let parent = element.parentNode;
  let scrollableElements = [];
  let rootScrollingElement = document.scrollingElement || document.documentElement;
  while (parent instanceof HTMLElement && parent !== rootScrollingElement) {
    if (parent.offsetHeight < parent.scrollHeight || parent.offsetWidth < parent.scrollWidth) scrollableElements.push({
      element: parent,
      scrollTop: parent.scrollTop,
      scrollLeft: parent.scrollLeft
    });
    parent = parent.parentNode;
  }
  if (rootScrollingElement instanceof HTMLElement) scrollableElements.push({
    element: rootScrollingElement,
    scrollTop: rootScrollingElement.scrollTop,
    scrollLeft: rootScrollingElement.scrollLeft
  });
  return scrollableElements;
}
function $7215afc6de606d6b$var$restoreScrollPosition(scrollableElements) {
  for (let { element, scrollTop, scrollLeft } of scrollableElements) {
    element.scrollTop = scrollTop;
    element.scrollLeft = scrollLeft;
  }
}
function $c87311424ea30a05$var$testUserAgent(re2) {
  var _window_navigator_userAgentData;
  if (typeof window === "undefined" || window.navigator == null) return false;
  let brands = (_window_navigator_userAgentData = window.navigator["userAgentData"]) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.brands;
  return Array.isArray(brands) && brands.some((brand) => re2.test(brand.brand)) || re2.test(window.navigator.userAgent);
}
function $c87311424ea30a05$var$testPlatform(re2) {
  var _window_navigator_userAgentData;
  return typeof window !== "undefined" && window.navigator != null ? re2.test(((_window_navigator_userAgentData = window.navigator["userAgentData"]) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.platform) || window.navigator.platform) : false;
}
function $c87311424ea30a05$var$cached(fn2) {
  let res = null;
  return () => {
    if (res == null) res = fn2();
    return res;
  };
}
const $c87311424ea30a05$export$9ac100e40613ea10 = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testPlatform(/^Mac/i);
});
const $c87311424ea30a05$export$7bef049ce92e4224 = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testPlatform(/^iPad/i) || // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
  $c87311424ea30a05$export$9ac100e40613ea10() && navigator.maxTouchPoints > 1;
});
const $c87311424ea30a05$export$78551043582a6a98 = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testUserAgent(/AppleWebKit/i) && !$c87311424ea30a05$export$6446a186d09e379e();
});
const $c87311424ea30a05$export$6446a186d09e379e = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testUserAgent(/Chrome/i);
});
const $c87311424ea30a05$export$a11b0059900ceec8 = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testUserAgent(/Android/i);
});
const $c87311424ea30a05$export$b7d78993b74f766d = $c87311424ea30a05$var$cached(function() {
  return $c87311424ea30a05$var$testUserAgent(/Firefox/i);
});
function $ea8dcbcb9ea1b556$export$95185d699e05d4d7(target, modifiers, setOpening = true) {
  var _window_event_type, _window_event;
  let { metaKey, ctrlKey, altKey, shiftKey } = modifiers;
  if ($c87311424ea30a05$export$b7d78993b74f766d() && ((_window_event = window.event) === null || _window_event === void 0 ? void 0 : (_window_event_type = _window_event.type) === null || _window_event_type === void 0 ? void 0 : _window_event_type.startsWith("key")) && target.target === "_blank") {
    if ($c87311424ea30a05$export$9ac100e40613ea10()) metaKey = true;
    else ctrlKey = true;
  }
  let event = $c87311424ea30a05$export$78551043582a6a98() && $c87311424ea30a05$export$9ac100e40613ea10() && !$c87311424ea30a05$export$7bef049ce92e4224() && true ? new KeyboardEvent("keydown", {
    keyIdentifier: "Enter",
    metaKey,
    ctrlKey,
    altKey,
    shiftKey
  }) : new MouseEvent("click", {
    metaKey,
    ctrlKey,
    altKey,
    shiftKey,
    detail: 1,
    bubbles: true,
    cancelable: true
  });
  $ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = setOpening;
  $7215afc6de606d6b$export$de79e2c695e052f3(target);
  target.dispatchEvent(event);
  $ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = false;
}
$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = false;
function $03deb23ff14920c4$export$4eaf04e54aa8eed6() {
  let globalListeners = reactExports.useRef(/* @__PURE__ */ new Map());
  let addGlobalListener = reactExports.useCallback((eventTarget, type, listener, options) => {
    let fn2 = (options === null || options === void 0 ? void 0 : options.once) ? (...args) => {
      globalListeners.current.delete(listener);
      listener(...args);
    } : listener;
    globalListeners.current.set(listener, {
      type,
      eventTarget,
      fn: fn2,
      options
    });
    eventTarget.addEventListener(type, fn2, options);
  }, []);
  let removeGlobalListener = reactExports.useCallback((eventTarget, type, listener, options) => {
    var _globalListeners_current_get;
    let fn2 = ((_globalListeners_current_get = globalListeners.current.get(listener)) === null || _globalListeners_current_get === void 0 ? void 0 : _globalListeners_current_get.fn) || listener;
    eventTarget.removeEventListener(type, fn2, options);
    globalListeners.current.delete(listener);
  }, []);
  let removeAllGlobalListeners = reactExports.useCallback(() => {
    globalListeners.current.forEach((value, key) => {
      removeGlobalListener(value.eventTarget, value.type, key, value.options);
    });
  }, [
    removeGlobalListener
  ]);
  reactExports.useEffect(() => {
    return removeAllGlobalListeners;
  }, [
    removeAllGlobalListeners
  ]);
  return {
    addGlobalListener,
    removeGlobalListener,
    removeAllGlobalListeners
  };
}
function $6a7db85432448f7f$export$60278871457622de(event) {
  if (event.pointerType === "" && event.isTrusted) return true;
  if ($c87311424ea30a05$export$a11b0059900ceec8() && event.pointerType) return event.type === "click" && event.buttons === 1;
  return event.detail === 0 && !event.pointerType;
}
function $8a9cb279dc87e130$export$525bc4921d56d4a(nativeEvent) {
  let event = nativeEvent;
  event.nativeEvent = nativeEvent;
  event.isDefaultPrevented = () => event.defaultPrevented;
  event.isPropagationStopped = () => event.cancelBubble;
  event.persist = () => {
  };
  return event;
}
function $8a9cb279dc87e130$export$c2b7abe5d61ec696(event, target) {
  Object.defineProperty(event, "target", {
    value: target
  });
  Object.defineProperty(event, "currentTarget", {
    value: target
  });
}
function $8a9cb279dc87e130$export$715c682d09d639cc(onBlur) {
  let stateRef = reactExports.useRef({
    isFocused: false,
    observer: null
  });
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    const state = stateRef.current;
    return () => {
      if (state.observer) {
        state.observer.disconnect();
        state.observer = null;
      }
    };
  }, []);
  return reactExports.useCallback((e2) => {
    let eventTarget = $d4ee10de306f2510$export$e58f029f0fbfdb29(e2);
    if (eventTarget instanceof HTMLButtonElement || eventTarget instanceof HTMLInputElement || eventTarget instanceof HTMLTextAreaElement || eventTarget instanceof HTMLSelectElement) {
      stateRef.current.isFocused = true;
      let target = eventTarget;
      let onBlurHandler = (e3) => {
        stateRef.current.isFocused = false;
        if (target.disabled) {
          let event = $8a9cb279dc87e130$export$525bc4921d56d4a(e3);
          onBlur === null || onBlur === void 0 ? void 0 : onBlur(event);
        }
        if (stateRef.current.observer) {
          stateRef.current.observer.disconnect();
          stateRef.current.observer = null;
        }
      };
      target.addEventListener("focusout", onBlurHandler, {
        once: true
      });
      stateRef.current.observer = new MutationObserver(() => {
        if (stateRef.current.isFocused && target.disabled) {
          var _stateRef_current_observer;
          (_stateRef_current_observer = stateRef.current.observer) === null || _stateRef_current_observer === void 0 ? void 0 : _stateRef_current_observer.disconnect();
          let relatedTargetEl = target === $d4ee10de306f2510$export$cd4e5573fbe2b576() ? null : $d4ee10de306f2510$export$cd4e5573fbe2b576();
          target.dispatchEvent(new FocusEvent("blur", {
            relatedTarget: relatedTargetEl
          }));
          target.dispatchEvent(new FocusEvent("focusout", {
            bubbles: true,
            relatedTarget: relatedTargetEl
          }));
        }
      });
      stateRef.current.observer.observe(target, {
        attributes: true,
        attributeFilter: [
          "disabled"
        ]
      });
    }
  }, [
    onBlur
  ]);
}
let $8a9cb279dc87e130$export$fda7da73ab5d4c48 = false;
let $507fabe10e71c6fb$var$currentModality = null;
const $507fabe10e71c6fb$export$901e90a13c50a14e = /* @__PURE__ */ new Set();
let $507fabe10e71c6fb$export$d90243b58daecda7 = /* @__PURE__ */ new Map();
let $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
let $507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
const $507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS = {
  Tab: true,
  Escape: true
};
function $507fabe10e71c6fb$var$triggerChangeHandlers(modality, e2) {
  for (let handler of $507fabe10e71c6fb$export$901e90a13c50a14e) handler(modality, e2);
}
function $507fabe10e71c6fb$var$isValidKey(e2) {
  return !(e2.metaKey || !$c87311424ea30a05$export$9ac100e40613ea10() && e2.altKey || e2.ctrlKey || e2.key === "Control" || e2.key === "Shift" || e2.key === "Meta");
}
function $507fabe10e71c6fb$var$handleKeyboardEvent(e2) {
  $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
  if (!$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening && $507fabe10e71c6fb$var$isValidKey(e2)) {
    $507fabe10e71c6fb$var$currentModality = "keyboard";
    $507fabe10e71c6fb$var$triggerChangeHandlers("keyboard", e2);
  }
}
function $507fabe10e71c6fb$var$handlePointerEvent(e2) {
  $507fabe10e71c6fb$var$currentModality = "pointer";
  "pointerType" in e2 ? e2.pointerType : "mouse";
  if (e2.type === "mousedown" || e2.type === "pointerdown") {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    $507fabe10e71c6fb$var$triggerChangeHandlers("pointer", e2);
  }
}
function $507fabe10e71c6fb$var$handleClickEvent(e2) {
  if (!$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening && $6a7db85432448f7f$export$60278871457622de(e2)) {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    $507fabe10e71c6fb$var$currentModality = "virtual";
  }
}
function $507fabe10e71c6fb$var$handleFocusEvent(e2) {
  if ($d4ee10de306f2510$export$e58f029f0fbfdb29(e2) === window || $d4ee10de306f2510$export$e58f029f0fbfdb29(e2) === document || $8a9cb279dc87e130$export$fda7da73ab5d4c48 || !e2.isTrusted) return;
  if (!$507fabe10e71c6fb$var$hasEventBeforeFocus && !$507fabe10e71c6fb$var$hasBlurredWindowRecently) {
    $507fabe10e71c6fb$var$currentModality = "virtual";
    $507fabe10e71c6fb$var$triggerChangeHandlers("virtual", e2);
  }
  $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
  $507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
}
function $507fabe10e71c6fb$var$handleWindowBlur() {
  $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
  $507fabe10e71c6fb$var$hasBlurredWindowRecently = true;
}
function $507fabe10e71c6fb$var$setupGlobalFocusEvents(element) {
  if (typeof window === "undefined" || typeof document === "undefined" || $507fabe10e71c6fb$export$d90243b58daecda7.get($431fbd86ca7dc216$export$f21a1ffae260145a(element))) return;
  const windowObject = $431fbd86ca7dc216$export$f21a1ffae260145a(element);
  const documentObject = $431fbd86ca7dc216$export$b204af158042fbac(element);
  let focus = windowObject.HTMLElement.prototype.focus;
  windowObject.HTMLElement.prototype.focus = function() {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    focus.apply(this, arguments);
  };
  documentObject.addEventListener("keydown", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  documentObject.addEventListener("keyup", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  documentObject.addEventListener("click", $507fabe10e71c6fb$var$handleClickEvent, true);
  windowObject.addEventListener("focus", $507fabe10e71c6fb$var$handleFocusEvent, true);
  windowObject.addEventListener("blur", $507fabe10e71c6fb$var$handleWindowBlur, false);
  if (typeof PointerEvent !== "undefined") {
    documentObject.addEventListener("pointerdown", $507fabe10e71c6fb$var$handlePointerEvent, true);
    documentObject.addEventListener("pointermove", $507fabe10e71c6fb$var$handlePointerEvent, true);
    documentObject.addEventListener("pointerup", $507fabe10e71c6fb$var$handlePointerEvent, true);
  }
  windowObject.addEventListener("beforeunload", () => {
    $507fabe10e71c6fb$var$tearDownWindowFocusTracking(element);
  }, {
    once: true
  });
  $507fabe10e71c6fb$export$d90243b58daecda7.set(windowObject, {
    focus
  });
}
const $507fabe10e71c6fb$var$tearDownWindowFocusTracking = (element, loadListener) => {
  const windowObject = $431fbd86ca7dc216$export$f21a1ffae260145a(element);
  const documentObject = $431fbd86ca7dc216$export$b204af158042fbac(element);
  if (loadListener) documentObject.removeEventListener("DOMContentLoaded", loadListener);
  if (!$507fabe10e71c6fb$export$d90243b58daecda7.has(windowObject)) return;
  windowObject.HTMLElement.prototype.focus = $507fabe10e71c6fb$export$d90243b58daecda7.get(windowObject).focus;
  documentObject.removeEventListener("keydown", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  documentObject.removeEventListener("keyup", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  documentObject.removeEventListener("click", $507fabe10e71c6fb$var$handleClickEvent, true);
  windowObject.removeEventListener("focus", $507fabe10e71c6fb$var$handleFocusEvent, true);
  windowObject.removeEventListener("blur", $507fabe10e71c6fb$var$handleWindowBlur, false);
  if (typeof PointerEvent !== "undefined") {
    documentObject.removeEventListener("pointerdown", $507fabe10e71c6fb$var$handlePointerEvent, true);
    documentObject.removeEventListener("pointermove", $507fabe10e71c6fb$var$handlePointerEvent, true);
    documentObject.removeEventListener("pointerup", $507fabe10e71c6fb$var$handlePointerEvent, true);
  }
  $507fabe10e71c6fb$export$d90243b58daecda7.delete(windowObject);
};
function $507fabe10e71c6fb$export$2f1888112f558a7d(element) {
  const documentObject = $431fbd86ca7dc216$export$b204af158042fbac(element);
  let loadListener;
  if (documentObject.readyState !== "loading") $507fabe10e71c6fb$var$setupGlobalFocusEvents(element);
  else {
    loadListener = () => {
      $507fabe10e71c6fb$var$setupGlobalFocusEvents(element);
    };
    documentObject.addEventListener("DOMContentLoaded", loadListener);
  }
  return () => $507fabe10e71c6fb$var$tearDownWindowFocusTracking(element, loadListener);
}
if (typeof document !== "undefined") $507fabe10e71c6fb$export$2f1888112f558a7d();
function $507fabe10e71c6fb$export$b9b3dfddab17db27() {
  return $507fabe10e71c6fb$var$currentModality !== "pointer";
}
const $507fabe10e71c6fb$var$nonTextInputTypes = /* @__PURE__ */ new Set([
  "checkbox",
  "radio",
  "range",
  "color",
  "file",
  "image",
  "button",
  "submit",
  "reset"
]);
function $507fabe10e71c6fb$var$isKeyboardFocusEvent(isTextInput, modality, e2) {
  let document1 = $431fbd86ca7dc216$export$b204af158042fbac(e2 ? $d4ee10de306f2510$export$e58f029f0fbfdb29(e2) : void 0);
  let eventTarget = e2 ? $d4ee10de306f2510$export$e58f029f0fbfdb29(e2) : void 0;
  const IHTMLInputElement = typeof window !== "undefined" ? $431fbd86ca7dc216$export$f21a1ffae260145a(eventTarget).HTMLInputElement : HTMLInputElement;
  const IHTMLTextAreaElement = typeof window !== "undefined" ? $431fbd86ca7dc216$export$f21a1ffae260145a(eventTarget).HTMLTextAreaElement : HTMLTextAreaElement;
  const IHTMLElement = typeof window !== "undefined" ? $431fbd86ca7dc216$export$f21a1ffae260145a(eventTarget).HTMLElement : HTMLElement;
  const IKeyboardEvent = typeof window !== "undefined" ? $431fbd86ca7dc216$export$f21a1ffae260145a(eventTarget).KeyboardEvent : KeyboardEvent;
  let activeElement = $d4ee10de306f2510$export$cd4e5573fbe2b576(document1);
  isTextInput = isTextInput || activeElement instanceof IHTMLInputElement && !$507fabe10e71c6fb$var$nonTextInputTypes.has(activeElement.type) || activeElement instanceof IHTMLTextAreaElement || activeElement instanceof IHTMLElement && activeElement.isContentEditable;
  return !(isTextInput && modality === "keyboard" && e2 instanceof IKeyboardEvent && !$507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS[e2.key]);
}
function $507fabe10e71c6fb$export$ec71b4b83ac08ec3(fn2, deps, opts) {
  $507fabe10e71c6fb$var$setupGlobalFocusEvents();
  reactExports.useEffect(() => {
    if ((opts === null || opts === void 0 ? void 0 : opts.enabled) === false) return;
    let handler = (modality, e2) => {
      if (!$507fabe10e71c6fb$var$isKeyboardFocusEvent(!!(opts === null || opts === void 0 ? void 0 : opts.isTextInput), modality, e2)) return;
      fn2($507fabe10e71c6fb$export$b9b3dfddab17db27());
    };
    $507fabe10e71c6fb$export$901e90a13c50a14e.add(handler);
    return () => {
      $507fabe10e71c6fb$export$901e90a13c50a14e.delete(handler);
    };
  }, deps);
}
function $a1ea59d68270f0dd$export$f8168d8dd8fd66e6(props) {
  let { isDisabled, onFocus: onFocusProp, onBlur: onBlurProp, onFocusChange } = props;
  const onBlur = reactExports.useCallback((e2) => {
    if ($d4ee10de306f2510$export$e58f029f0fbfdb29(e2) === e2.currentTarget) {
      if (onBlurProp) onBlurProp(e2);
      if (onFocusChange) onFocusChange(false);
      return true;
    }
  }, [
    onBlurProp,
    onFocusChange
  ]);
  const onSyntheticFocus = $8a9cb279dc87e130$export$715c682d09d639cc(onBlur);
  const onFocus = reactExports.useCallback((e2) => {
    let eventTarget = $d4ee10de306f2510$export$e58f029f0fbfdb29(e2);
    const ownerDocument = $431fbd86ca7dc216$export$b204af158042fbac(eventTarget);
    const activeElement = ownerDocument ? $d4ee10de306f2510$export$cd4e5573fbe2b576(ownerDocument) : $d4ee10de306f2510$export$cd4e5573fbe2b576();
    if (eventTarget === e2.currentTarget && eventTarget === activeElement) {
      if (onFocusProp) onFocusProp(e2);
      if (onFocusChange) onFocusChange(true);
      onSyntheticFocus(e2);
    }
  }, [
    onFocusChange,
    onFocusProp,
    onSyntheticFocus
  ]);
  return {
    focusProps: {
      onFocus: !isDisabled && (onFocusProp || onFocusChange || onBlurProp) ? onFocus : void 0,
      onBlur: !isDisabled && (onBlurProp || onFocusChange) ? onBlur : void 0
    }
  };
}
function $9ab94262bd0047c7$export$420e68273165f4ec(props) {
  let { isDisabled, onBlurWithin, onFocusWithin, onFocusWithinChange } = props;
  let state = reactExports.useRef({
    isFocusWithin: false
  });
  let { addGlobalListener, removeAllGlobalListeners } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let onBlur = reactExports.useCallback((e2) => {
    if (!$d4ee10de306f2510$export$4282f70798064fe0(e2.currentTarget, $d4ee10de306f2510$export$e58f029f0fbfdb29(e2))) return;
    if (state.current.isFocusWithin && !$d4ee10de306f2510$export$4282f70798064fe0(e2.currentTarget, e2.relatedTarget)) {
      state.current.isFocusWithin = false;
      removeAllGlobalListeners();
      if (onBlurWithin) onBlurWithin(e2);
      if (onFocusWithinChange) onFocusWithinChange(false);
    }
  }, [
    onBlurWithin,
    onFocusWithinChange,
    state,
    removeAllGlobalListeners
  ]);
  let onSyntheticFocus = $8a9cb279dc87e130$export$715c682d09d639cc(onBlur);
  let onFocus = reactExports.useCallback((e2) => {
    if (!$d4ee10de306f2510$export$4282f70798064fe0(e2.currentTarget, $d4ee10de306f2510$export$e58f029f0fbfdb29(e2))) return;
    let eventTarget = $d4ee10de306f2510$export$e58f029f0fbfdb29(e2);
    const ownerDocument = $431fbd86ca7dc216$export$b204af158042fbac(eventTarget);
    const activeElement = $d4ee10de306f2510$export$cd4e5573fbe2b576(ownerDocument);
    if (!state.current.isFocusWithin && activeElement === eventTarget) {
      if (onFocusWithin) onFocusWithin(e2);
      if (onFocusWithinChange) onFocusWithinChange(true);
      state.current.isFocusWithin = true;
      onSyntheticFocus(e2);
      let currentTarget = e2.currentTarget;
      addGlobalListener(ownerDocument, "focus", (e3) => {
        let eventTarget2 = $d4ee10de306f2510$export$e58f029f0fbfdb29(e3);
        if (state.current.isFocusWithin && !$d4ee10de306f2510$export$4282f70798064fe0(currentTarget, eventTarget2)) {
          let nativeEvent = new ownerDocument.defaultView.FocusEvent("blur", {
            relatedTarget: eventTarget2
          });
          $8a9cb279dc87e130$export$c2b7abe5d61ec696(nativeEvent, currentTarget);
          let event = $8a9cb279dc87e130$export$525bc4921d56d4a(nativeEvent);
          onBlur(event);
        }
      }, {
        capture: true
      });
    }
  }, [
    onFocusWithin,
    onFocusWithinChange,
    onSyntheticFocus,
    addGlobalListener,
    onBlur
  ]);
  if (isDisabled) return {
    focusWithinProps: {
      // These cannot be null, that would conflict in mergeProps
      onFocus: void 0,
      onBlur: void 0
    }
  };
  return {
    focusWithinProps: {
      onFocus,
      onBlur
    }
  };
}
let $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
let $6179b936705e76d3$var$hoverCount = 0;
function $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents() {
  $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = true;
  setTimeout(() => {
    $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
  }, 50);
}
function $6179b936705e76d3$var$handleGlobalPointerEvent(e2) {
  if (e2.pointerType === "touch") $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents();
}
function $6179b936705e76d3$var$setupGlobalTouchEvents() {
  if (typeof document === "undefined") return;
  if ($6179b936705e76d3$var$hoverCount === 0) {
    if (typeof PointerEvent !== "undefined") document.addEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
  }
  $6179b936705e76d3$var$hoverCount++;
  return () => {
    $6179b936705e76d3$var$hoverCount--;
    if ($6179b936705e76d3$var$hoverCount > 0) return;
    if (typeof PointerEvent !== "undefined") document.removeEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
  };
}
function $6179b936705e76d3$export$ae780daf29e6d456(props) {
  let { onHoverStart, onHoverChange, onHoverEnd, isDisabled } = props;
  let [isHovered, setHovered] = reactExports.useState(false);
  let state = reactExports.useRef({
    isHovered: false,
    ignoreEmulatedMouseEvents: false,
    pointerType: "",
    target: null
  }).current;
  reactExports.useEffect($6179b936705e76d3$var$setupGlobalTouchEvents, []);
  let { addGlobalListener, removeAllGlobalListeners } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let { hoverProps, triggerHoverEnd } = reactExports.useMemo(() => {
    let triggerHoverStart = (event, pointerType) => {
      state.pointerType = pointerType;
      if (isDisabled || pointerType === "touch" || state.isHovered || !$d4ee10de306f2510$export$4282f70798064fe0(event.currentTarget, $d4ee10de306f2510$export$e58f029f0fbfdb29(event))) return;
      state.isHovered = true;
      let target = event.currentTarget;
      state.target = target;
      addGlobalListener($431fbd86ca7dc216$export$b204af158042fbac($d4ee10de306f2510$export$e58f029f0fbfdb29(event)), "pointerover", (e2) => {
        if (state.isHovered && state.target && !$d4ee10de306f2510$export$4282f70798064fe0(state.target, $d4ee10de306f2510$export$e58f029f0fbfdb29(e2))) triggerHoverEnd2(e2, e2.pointerType);
      }, {
        capture: true
      });
      if (onHoverStart) onHoverStart({
        type: "hoverstart",
        target,
        pointerType
      });
      if (onHoverChange) onHoverChange(true);
      setHovered(true);
    };
    let triggerHoverEnd2 = (event, pointerType) => {
      let target = state.target;
      state.pointerType = "";
      state.target = null;
      if (pointerType === "touch" || !state.isHovered || !target) return;
      state.isHovered = false;
      removeAllGlobalListeners();
      if (onHoverEnd) onHoverEnd({
        type: "hoverend",
        target,
        pointerType
      });
      if (onHoverChange) onHoverChange(false);
      setHovered(false);
    };
    let hoverProps2 = {};
    if (typeof PointerEvent !== "undefined") {
      hoverProps2.onPointerEnter = (e2) => {
        if ($6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents && e2.pointerType === "mouse") return;
        triggerHoverStart(e2, e2.pointerType);
      };
      hoverProps2.onPointerLeave = (e2) => {
        if (!isDisabled && $d4ee10de306f2510$export$4282f70798064fe0(e2.currentTarget, $d4ee10de306f2510$export$e58f029f0fbfdb29(e2))) triggerHoverEnd2(e2, e2.pointerType);
      };
    }
    return {
      hoverProps: hoverProps2,
      triggerHoverEnd: triggerHoverEnd2
    };
  }, [
    onHoverStart,
    onHoverChange,
    onHoverEnd,
    isDisabled,
    state,
    addGlobalListener,
    removeAllGlobalListeners
  ]);
  reactExports.useEffect(() => {
    if (isDisabled) triggerHoverEnd({
      currentTarget: state.target
    }, state.pointerType);
  }, [
    isDisabled
  ]);
  return {
    hoverProps,
    isHovered
  };
}
function $f7dceffc5ad7768b$export$4e328f61c538687f(props = {}) {
  let { autoFocus = false, isTextInput, within } = props;
  let state = reactExports.useRef({
    isFocused: false,
    isFocusVisible: autoFocus || $507fabe10e71c6fb$export$b9b3dfddab17db27()
  });
  let [isFocused, setFocused] = reactExports.useState(false);
  let [isFocusVisibleState, setFocusVisible] = reactExports.useState(() => state.current.isFocused && state.current.isFocusVisible);
  let updateState = reactExports.useCallback(() => setFocusVisible(state.current.isFocused && state.current.isFocusVisible), []);
  let onFocusChange = reactExports.useCallback((isFocused2) => {
    state.current.isFocused = isFocused2;
    state.current.isFocusVisible = $507fabe10e71c6fb$export$b9b3dfddab17db27();
    setFocused(isFocused2);
    updateState();
  }, [
    updateState
  ]);
  $507fabe10e71c6fb$export$ec71b4b83ac08ec3((isFocusVisible) => {
    state.current.isFocusVisible = isFocusVisible;
    updateState();
  }, [
    isTextInput,
    isFocused
  ], {
    enabled: isFocused,
    isTextInput
  });
  let { focusProps } = $a1ea59d68270f0dd$export$f8168d8dd8fd66e6({
    isDisabled: within,
    onFocusChange
  });
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    isDisabled: !within,
    onFocusWithinChange: onFocusChange
  });
  return {
    isFocused,
    isFocusVisible: isFocusVisibleState,
    focusProps: within ? focusWithinProps : focusProps
  };
}
var i$8 = Object.defineProperty;
var d$3 = (t2, e2, n2) => e2 in t2 ? i$8(t2, e2, { enumerable: true, configurable: true, writable: true, value: n2 }) : t2[e2] = n2;
var r$7 = (t2, e2, n2) => (d$3(t2, typeof e2 != "symbol" ? e2 + "" : e2, n2), n2);
let o$7 = class o {
  constructor() {
    r$7(this, "current", this.detect());
    r$7(this, "handoffState", "pending");
    r$7(this, "currentId", 0);
  }
  set(e2) {
    this.current !== e2 && (this.handoffState = "pending", this.currentId = 0, this.current = e2);
  }
  reset() {
    this.set(this.detect());
  }
  nextId() {
    return ++this.currentId;
  }
  get isServer() {
    return this.current === "server";
  }
  get isClient() {
    return this.current === "client";
  }
  detect() {
    return typeof window == "undefined" || typeof document == "undefined" ? "server" : "client";
  }
  handoff() {
    this.handoffState === "pending" && (this.handoffState = "complete");
  }
  get isHandoffComplete() {
    return this.handoffState === "complete";
  }
};
let s$a = new o$7();
function l$7(n2) {
  var u2;
  return s$a.isServer ? null : n2 == null ? document : (u2 = n2 == null ? void 0 : n2.ownerDocument) != null ? u2 : document;
}
function r$6(n2) {
  var u2, o4;
  return s$a.isServer ? null : n2 == null ? document : (o4 = (u2 = n2 == null ? void 0 : n2.getRootNode) == null ? void 0 : u2.call(n2)) != null ? o4 : document;
}
function e$5(n2) {
  var u2, o4;
  return (o4 = (u2 = r$6(n2)) == null ? void 0 : u2.activeElement) != null ? o4 : null;
}
function d$2(n2) {
  return e$5(n2) === n2;
}
function t$5(e2) {
  typeof queueMicrotask == "function" ? queueMicrotask(e2) : Promise.resolve().then(e2).catch((o4) => setTimeout(() => {
    throw o4;
  }));
}
function o$6() {
  let s2 = [], r2 = { addEventListener(e2, t2, n2, i2) {
    return e2.addEventListener(t2, n2, i2), r2.add(() => e2.removeEventListener(t2, n2, i2));
  }, requestAnimationFrame(...e2) {
    let t2 = requestAnimationFrame(...e2);
    return r2.add(() => cancelAnimationFrame(t2));
  }, nextFrame(...e2) {
    return r2.requestAnimationFrame(() => r2.requestAnimationFrame(...e2));
  }, setTimeout(...e2) {
    let t2 = setTimeout(...e2);
    return r2.add(() => clearTimeout(t2));
  }, microTask(...e2) {
    let t2 = { current: true };
    return t$5(() => {
      t2.current && e2[0]();
    }), r2.add(() => {
      t2.current = false;
    });
  }, style(e2, t2, n2) {
    let i2 = e2.style.getPropertyValue(t2);
    return Object.assign(e2.style, { [t2]: n2 }), this.add(() => {
      Object.assign(e2.style, { [t2]: i2 });
    });
  }, group(e2) {
    let t2 = o$6();
    return e2(t2), this.add(() => t2.dispose());
  }, add(e2) {
    return s2.includes(e2) || s2.push(e2), () => {
      let t2 = s2.indexOf(e2);
      if (t2 >= 0) for (let n2 of s2.splice(t2, 1)) n2();
    };
  }, dispose() {
    for (let e2 of s2.splice(0)) e2();
  } };
  return r2;
}
function p$4() {
  let [e2] = reactExports.useState(o$6);
  return reactExports.useEffect(() => () => e2.dispose(), [e2]), e2;
}
let n$6 = (e2, t2) => {
  s$a.isServer ? reactExports.useEffect(e2, t2) : reactExports.useLayoutEffect(e2, t2);
};
function s$9(e2) {
  let r2 = reactExports.useRef(e2);
  return n$6(() => {
    r2.current = e2;
  }, [e2]), r2;
}
let o$5 = function(t2) {
  let e2 = s$9(t2);
  return React.useCallback((...r2) => e2.current(...r2), [e2]);
};
function E$4(e2) {
  let t2 = e2.width / 2, n2 = e2.height / 2;
  return { top: e2.clientY - n2, right: e2.clientX + t2, bottom: e2.clientY + n2, left: e2.clientX - t2 };
}
function P$2(e2, t2) {
  return !(!e2 || !t2 || e2.right < t2.left || e2.left > t2.right || e2.bottom < t2.top || e2.top > t2.bottom);
}
function w$6({ disabled: e2 = false } = {}) {
  let t2 = reactExports.useRef(null), [n2, l2] = reactExports.useState(false), r2 = p$4(), o4 = o$5(() => {
    t2.current = null, l2(false), r2.dispose();
  }), f2 = o$5((s2) => {
    if (r2.dispose(), t2.current === null) {
      t2.current = s2.currentTarget, l2(true);
      {
        let i2 = l$7(s2.currentTarget);
        r2.addEventListener(i2, "pointerup", o4, false), r2.addEventListener(i2, "pointermove", (c2) => {
          if (t2.current) {
            let p2 = E$4(c2);
            l2(P$2(p2, t2.current.getBoundingClientRect()));
          }
        }, false), r2.addEventListener(i2, "pointercancel", o4, false);
      }
    }
  });
  return { pressed: n2, pressProps: e2 ? {} : { onPointerDown: f2, onPointerUp: o4, onClick: o4 } };
}
function n$5(e2) {
  return reactExports.useMemo(() => e2, Object.values(e2));
}
let e$4 = reactExports.createContext(void 0);
function a$e() {
  return reactExports.useContext(e$4);
}
function t$4(...r2) {
  return Array.from(new Set(r2.flatMap((n2) => typeof n2 == "string" ? n2.split(" ") : []))).filter(Boolean).join(" ");
}
function u$9(r2, n2, ...a3) {
  if (r2 in n2) {
    let e2 = n2[r2];
    return typeof e2 == "function" ? e2(...a3) : e2;
  }
  let t2 = new Error(`Tried to handle "${r2}" but there is no handler defined. Only defined handlers are: ${Object.keys(n2).map((e2) => `"${e2}"`).join(", ")}.`);
  throw Error.captureStackTrace && Error.captureStackTrace(t2, u$9), t2;
}
var A$2 = ((a3) => (a3[a3.None = 0] = "None", a3[a3.RenderStrategy = 1] = "RenderStrategy", a3[a3.Static = 2] = "Static", a3))(A$2 || {}), C$7 = ((e2) => (e2[e2.Unmount = 0] = "Unmount", e2[e2.Hidden = 1] = "Hidden", e2))(C$7 || {});
function K() {
  let n2 = $$1();
  return reactExports.useCallback((r2) => U$1({ mergeRefs: n2, ...r2 }), [n2]);
}
function U$1({ ourProps: n2, theirProps: r2, slot: e2, defaultTag: a3, features: s2, visible: t2 = true, name: l2, mergeRefs: i2 }) {
  i2 = i2 != null ? i2 : I$5;
  let o4 = P$1(r2, n2);
  if (t2) return F$1(o4, e2, a3, l2, i2);
  let y2 = s2 != null ? s2 : 0;
  if (y2 & 2) {
    let { static: f2 = false, ...u2 } = o4;
    if (f2) return F$1(u2, e2, a3, l2, i2);
  }
  if (y2 & 1) {
    let { unmount: f2 = true, ...u2 } = o4;
    return u$9(f2 ? 0 : 1, { [0]() {
      return null;
    }, [1]() {
      return F$1({ ...u2, hidden: true, style: { display: "none" } }, e2, a3, l2, i2);
    } });
  }
  return F$1(o4, e2, a3, l2, i2);
}
function F$1(n2, r2 = {}, e2, a3, s2) {
  let { as: t2 = e2, children: l2, refName: i2 = "ref", ...o4 } = h$4(n2, ["unmount", "static"]), y2 = n2.ref !== void 0 ? { [i2]: n2.ref } : {}, f2 = typeof l2 == "function" ? l2(r2) : l2;
  "className" in o4 && o4.className && typeof o4.className == "function" && (o4.className = o4.className(r2)), o4["aria-labelledby"] && o4["aria-labelledby"] === o4.id && (o4["aria-labelledby"] = void 0);
  let u2 = {};
  if (r2) {
    let d2 = false, p2 = [];
    for (let [c2, T3] of Object.entries(r2)) typeof T3 == "boolean" && (d2 = true), T3 === true && p2.push(c2.replace(/([A-Z])/g, (g2) => `-${g2.toLowerCase()}`));
    if (d2) {
      u2["data-headlessui-state"] = p2.join(" ");
      for (let c2 of p2) u2[`data-${c2}`] = "";
    }
  }
  if (b$3(t2) && (Object.keys(m$4(o4)).length > 0 || Object.keys(m$4(u2)).length > 0)) if (!reactExports.isValidElement(f2) || Array.isArray(f2) && f2.length > 1 || D$3(f2)) {
    if (Object.keys(m$4(o4)).length > 0) throw new Error(['Passing props on "Fragment"!', "", `The current component <${a3} /> is rendering a "Fragment".`, "However we need to passthrough the following props:", Object.keys(m$4(o4)).concat(Object.keys(m$4(u2))).map((d2) => `  - ${d2}`).join(`
`), "", "You can apply a few solutions:", ['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', "Render a single element as the child so that we can forward the props onto that element."].map((d2) => `  - ${d2}`).join(`
`)].join(`
`));
  } else {
    let d2 = f2.props, p2 = d2 == null ? void 0 : d2.className, c2 = typeof p2 == "function" ? (...R2) => t$4(p2(...R2), o4.className) : t$4(p2, o4.className), T3 = c2 ? { className: c2 } : {}, g2 = P$1(f2.props, m$4(h$4(o4, ["ref"])));
    for (let R2 in u2) R2 in g2 && delete u2[R2];
    return reactExports.cloneElement(f2, Object.assign({}, g2, u2, y2, { ref: s2(H$3(f2), y2.ref) }, T3));
  }
  return reactExports.createElement(t2, Object.assign({}, h$4(o4, ["ref"]), !b$3(t2) && y2, !b$3(t2) && u2), f2);
}
function $$1() {
  let n2 = reactExports.useRef([]), r2 = reactExports.useCallback((e2) => {
    for (let a3 of n2.current) a3 != null && (typeof a3 == "function" ? a3(e2) : a3.current = e2);
  }, []);
  return (...e2) => {
    if (!e2.every((a3) => a3 == null)) return n2.current = e2, r2;
  };
}
function I$5(...n2) {
  return n2.every((r2) => r2 == null) ? void 0 : (r2) => {
    for (let e2 of n2) e2 != null && (typeof e2 == "function" ? e2(r2) : e2.current = r2);
  };
}
function P$1(...n2) {
  if (n2.length === 0) return {};
  if (n2.length === 1) return n2[0];
  let r2 = {}, e2 = {};
  for (let s2 of n2) for (let t2 in s2) t2.startsWith("on") && typeof s2[t2] == "function" ? (e2[t2] != null || (e2[t2] = []), e2[t2].push(s2[t2])) : r2[t2] = s2[t2];
  if (r2.disabled || r2["aria-disabled"]) for (let s2 in e2) /^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(s2) && (e2[s2] = [(t2) => {
    var l2;
    return (l2 = t2 == null ? void 0 : t2.preventDefault) == null ? void 0 : l2.call(t2);
  }]);
  for (let s2 in e2) Object.assign(r2, { [s2](t2, ...l2) {
    let i2 = e2[s2];
    for (let o4 of i2) {
      if ((t2 instanceof Event || (t2 == null ? void 0 : t2.nativeEvent) instanceof Event) && t2.defaultPrevented) return;
      o4(t2, ...l2);
    }
  } });
  return r2;
}
function V$4(...n2) {
  if (n2.length === 0) return {};
  if (n2.length === 1) return n2[0];
  let r2 = {}, e2 = {};
  for (let s2 of n2) for (let t2 in s2) t2.startsWith("on") && typeof s2[t2] == "function" ? (e2[t2] != null || (e2[t2] = []), e2[t2].push(s2[t2])) : r2[t2] = s2[t2];
  for (let s2 in e2) Object.assign(r2, { [s2](...t2) {
    let l2 = e2[s2];
    for (let i2 of l2) i2 == null || i2(...t2);
  } });
  return r2;
}
function Y(n2) {
  var r2;
  return Object.assign(reactExports.forwardRef(n2), { displayName: (r2 = n2.displayName) != null ? r2 : n2.name });
}
function m$4(n2) {
  let r2 = Object.assign({}, n2);
  for (let e2 in r2) r2[e2] === void 0 && delete r2[e2];
  return r2;
}
function h$4(n2, r2 = []) {
  let e2 = Object.assign({}, n2);
  for (let a3 of r2) a3 in e2 && delete e2[a3];
  return e2;
}
function H$3(n2) {
  return React.version.split(".")[0] >= "19" ? n2.props.ref : n2.ref;
}
function b$3(n2) {
  return n2 === reactExports.Fragment || n2 === Symbol.for("react.fragment");
}
function D$3(n2) {
  return b$3(n2.type);
}
function b$2(l2, r2, c2) {
  let [i2, s2] = reactExports.useState(c2), e2 = l2 !== void 0, t2 = reactExports.useRef(e2), u2 = reactExports.useRef(false), d2 = reactExports.useRef(false);
  return e2 && !t2.current && !u2.current ? (u2.current = true, t2.current = e2, console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")) : !e2 && t2.current && !d2.current && (d2.current = true, t2.current = e2, console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")), [e2 ? l2 : i2, o$5((n2) => (e2 || reactDomExports.flushSync(() => s2(n2)), r2 == null ? void 0 : r2(n2)))];
}
function l$6(e2) {
  let [t2] = reactExports.useState(e2);
  return t2;
}
function p$3(t2 = {}, i2 = null, n2 = []) {
  for (let [e2, o4] of Object.entries(t2)) s$8(n2, r$5(i2, e2), o4);
  return n2;
}
function r$5(t2, i2) {
  return t2 ? t2 + "[" + i2 + "]" : i2;
}
function s$8(t2, i2, n2) {
  if (Array.isArray(n2)) for (let [e2, o4] of n2.entries()) s$8(t2, r$5(i2, e2.toString()), o4);
  else n2 instanceof Date ? t2.push([i2, n2.toISOString()]) : typeof n2 == "boolean" ? t2.push([i2, n2 ? "1" : "0"]) : typeof n2 == "string" ? t2.push([i2, n2]) : typeof n2 == "number" ? t2.push([i2, `${n2}`]) : n2 == null ? t2.push([i2, ""]) : c$8(n2) && !reactExports.isValidElement(n2) && p$3(n2, i2, t2);
}
function g$3(t2) {
  var n2, e2;
  let i2 = (n2 = t2 == null ? void 0 : t2.form) != null ? n2 : t2.closest("form");
  if (i2) {
    for (let o4 of i2.elements) if (o4 !== t2 && (o4.tagName === "INPUT" && o4.type === "submit" || o4.tagName === "BUTTON" && o4.type === "submit" || o4.nodeName === "INPUT" && o4.type === "image")) {
      o4.click();
      return;
    }
    (e2 = i2.requestSubmit) == null || e2.call(i2);
  }
}
function c$8(t2) {
  if (Object.prototype.toString.call(t2) !== "[object Object]") return false;
  let i2 = Object.getPrototypeOf(t2);
  return i2 === null || Object.getPrototypeOf(i2) === null;
}
let a$d = "span";
var s$7 = ((e2) => (e2[e2.None = 1] = "None", e2[e2.Focusable = 2] = "Focusable", e2[e2.Hidden = 4] = "Hidden", e2))(s$7 || {});
function l$5(t2, r2) {
  var n2;
  let { features: d2 = 1, ...e2 } = t2, o4 = { ref: r2, "aria-hidden": (d2 & 2) === 2 ? true : (n2 = e2["aria-hidden"]) != null ? n2 : void 0, hidden: (d2 & 4) === 4 ? true : void 0, style: { position: "fixed", top: 1, left: 1, width: 1, height: 0, padding: 0, margin: -1, overflow: "hidden", clip: "rect(0, 0, 0, 0)", whiteSpace: "nowrap", borderWidth: "0", ...(d2 & 4) === 4 && (d2 & 2) !== 2 && { display: "none" } } };
  return K()({ ourProps: o4, theirProps: e2, slot: {}, defaultTag: a$d, name: "Hidden" });
}
let f$8 = Y(l$5);
let f$7 = reactExports.createContext(null);
function c$7({ children: t2 }) {
  let e2 = reactExports.useContext(f$7);
  if (!e2) return React.createElement(React.Fragment, null, t2);
  let { target: r2 } = e2;
  return r2 ? reactDomExports.createPortal(React.createElement(React.Fragment, null, t2), r2) : null;
}
function j$6({ data: t2, form: e2, disabled: r2, onReset: n2, overrides: F2 }) {
  let [i2, a3] = reactExports.useState(null), p2 = p$4();
  return reactExports.useEffect(() => {
    if (n2 && i2) return p2.addEventListener(i2, "reset", n2);
  }, [i2, e2, n2]), React.createElement(c$7, null, React.createElement(C$6, { setForm: a3, formId: e2 }), p$3(t2).map(([s2, v5]) => React.createElement(f$8, { features: s$7.Hidden, ...m$4({ key: s2, as: "input", type: "hidden", hidden: true, readOnly: true, form: e2, disabled: r2, name: s2, value: v5, ...F2 }) })));
}
function C$6({ setForm: t2, formId: e2 }) {
  return reactExports.useEffect(() => {
    if (e2) {
      let r2 = document.getElementById(e2);
      r2 && t2(r2);
    }
  }, [t2, e2]), e2 ? null : React.createElement(f$8, { features: s$7.Hidden, as: "input", type: "hidden", hidden: true, readOnly: true, ref: (r2) => {
    if (!r2) return;
    let n2 = r2.closest("form");
    n2 && t2(n2);
  } });
}
let e$3 = reactExports.createContext(void 0);
function u$8() {
  return reactExports.useContext(e$3);
}
function o$4(e2) {
  return typeof e2 != "object" || e2 === null ? false : "nodeType" in e2;
}
function t$3(e2) {
  return o$4(e2) && "tagName" in e2;
}
function n$4(e2) {
  return t$3(e2) && "accessKey" in e2;
}
function i$7(e2) {
  return t$3(e2) && "tabIndex" in e2;
}
function r$4(e2) {
  return t$3(e2) && "style" in e2;
}
function u$7(e2) {
  return n$4(e2) && e2.nodeName === "IFRAME";
}
function l$4(e2) {
  return n$4(e2) && e2.nodeName === "INPUT";
}
function m$3(e2) {
  return n$4(e2) && e2.nodeName === "LABEL";
}
function a$c(e2) {
  return n$4(e2) && e2.nodeName === "FIELDSET";
}
function E$3(e2) {
  return n$4(e2) && e2.nodeName === "LEGEND";
}
function L$1(e2) {
  return t$3(e2) ? e2.matches('a[href],audio[controls],button,details,embed,iframe,img[usemap],input:not([type="hidden"]),label,select,textarea,video[controls]') : false;
}
function s$6(l2) {
  let e2 = l2.parentElement, t2 = null;
  for (; e2 && !a$c(e2); ) E$3(e2) && (t2 = e2), e2 = e2.parentElement;
  let i2 = (e2 == null ? void 0 : e2.getAttribute("disabled")) === "";
  return i2 && r$3(t2) ? false : i2;
}
function r$3(l2) {
  if (!l2) return false;
  let e2 = l2.previousElementSibling;
  for (; e2 !== null; ) {
    if (E$3(e2)) return false;
    e2 = e2.previousElementSibling;
  }
  return true;
}
let u$6 = Symbol();
function T$3(t2, n2 = true) {
  return Object.assign(t2, { [u$6]: n2 });
}
function y$2(...t2) {
  let n2 = reactExports.useRef(t2);
  reactExports.useEffect(() => {
    n2.current = t2;
  }, [t2]);
  let c2 = o$5((e2) => {
    for (let o4 of n2.current) o4 != null && (typeof o4 == "function" ? o4(e2) : o4.current = e2);
  });
  return t2.every((e2) => e2 == null || (e2 == null ? void 0 : e2[u$6])) ? void 0 : c2;
}
let a$b = reactExports.createContext(null);
a$b.displayName = "DescriptionContext";
function f$6() {
  let r2 = reactExports.useContext(a$b);
  if (r2 === null) {
    let e2 = new Error("You used a <Description /> component, but it is not inside a relevant parent.");
    throw Error.captureStackTrace && Error.captureStackTrace(e2, f$6), e2;
  }
  return r2;
}
function w$5() {
  var r2, e2;
  return (e2 = (r2 = reactExports.useContext(a$b)) == null ? void 0 : r2.value) != null ? e2 : void 0;
}
function H$2() {
  let [r2, e2] = reactExports.useState([]);
  return [r2.length > 0 ? r2.join(" ") : void 0, reactExports.useMemo(() => function(t2) {
    let i2 = o$5((n2) => (e2((o4) => [...o4, n2]), () => e2((o4) => {
      let s2 = o4.slice(), p2 = s2.indexOf(n2);
      return p2 !== -1 && s2.splice(p2, 1), s2;
    }))), l2 = reactExports.useMemo(() => ({ register: i2, slot: t2.slot, name: t2.name, props: t2.props, value: t2.value }), [i2, t2.slot, t2.name, t2.props, t2.value]);
    return React.createElement(a$b.Provider, { value: l2 }, t2.children);
  }, [e2])];
}
let I$4 = "p";
function C$5(r2, e2) {
  let c2 = reactExports.useId(), t2 = a$e(), { id: i2 = `headlessui-description-${c2}`, ...l2 } = r2, n2 = f$6(), o4 = y$2(e2);
  n$6(() => n2.register(i2), [i2, n2.register]);
  let s2 = n$5({ ...n2.slot, disabled: t2 || false }), p2 = { ref: o4, ...n2.props, id: i2 };
  return K()({ ourProps: p2, theirProps: l2, slot: s2, defaultTag: I$4, name: n2.name || "Description" });
}
let _$3 = Y(C$5), M$3 = Object.assign(_$3, {});
var o$3 = ((r2) => (r2.Space = " ", r2.Enter = "Enter", r2.Escape = "Escape", r2.Backspace = "Backspace", r2.Delete = "Delete", r2.ArrowLeft = "ArrowLeft", r2.ArrowUp = "ArrowUp", r2.ArrowRight = "ArrowRight", r2.ArrowDown = "ArrowDown", r2.Home = "Home", r2.End = "End", r2.PageUp = "PageUp", r2.PageDown = "PageDown", r2.Tab = "Tab", r2))(o$3 || {});
let L = reactExports.createContext(null);
L.displayName = "LabelContext";
function C$4() {
  let n2 = reactExports.useContext(L);
  if (n2 === null) {
    let l2 = new Error("You used a <Label /> component, but it is not inside a relevant parent.");
    throw Error.captureStackTrace && Error.captureStackTrace(l2, C$4), l2;
  }
  return n2;
}
function N$1(n2) {
  var a3, e2, o4;
  let l2 = (e2 = (a3 = reactExports.useContext(L)) == null ? void 0 : a3.value) != null ? e2 : void 0;
  return ((o4 = void 0) != null ? o4 : 0) > 0 ? [l2, ...n2].filter(Boolean).join(" ") : l2;
}
function V$3({ inherit: n2 = false } = {}) {
  let l2 = N$1(), [a3, e2] = reactExports.useState([]), o4 = n2 ? [l2, ...a3].filter(Boolean) : a3;
  return [o4.length > 0 ? o4.join(" ") : void 0, reactExports.useMemo(() => function(t2) {
    let p2 = o$5((i2) => (e2((u2) => [...u2, i2]), () => e2((u2) => {
      let d2 = u2.slice(), f2 = d2.indexOf(i2);
      return f2 !== -1 && d2.splice(f2, 1), d2;
    }))), b2 = reactExports.useMemo(() => ({ register: p2, slot: t2.slot, name: t2.name, props: t2.props, value: t2.value }), [p2, t2.slot, t2.name, t2.props, t2.value]);
    return React.createElement(L.Provider, { value: b2 }, t2.children);
  }, [e2])];
}
let G$2 = "label";
function U(n2, l2) {
  var y2;
  let a3 = reactExports.useId(), e2 = C$4(), o4 = u$8(), T3 = a$e(), { id: t2 = `headlessui-label-${a3}`, htmlFor: p2 = o4 != null ? o4 : (y2 = e2.props) == null ? void 0 : y2.htmlFor, passive: b2 = false, ...i2 } = n2, u2 = y$2(l2);
  n$6(() => e2.register(t2), [t2, e2.register]);
  let d2 = o$5((s2) => {
    let g2 = s2.currentTarget;
    if (!(s2.target !== s2.currentTarget && L$1(s2.target)) && (m$3(g2) && s2.preventDefault(), e2.props && "onClick" in e2.props && typeof e2.props.onClick == "function" && e2.props.onClick(s2), m$3(g2))) {
      let r2 = document.getElementById(g2.htmlFor);
      if (r2) {
        let E2 = r2.getAttribute("disabled");
        if (E2 === "true" || E2 === "") return;
        let x = r2.getAttribute("aria-disabled");
        if (x === "true" || x === "") return;
        (l$4(r2) && (r2.type === "file" || r2.type === "radio" || r2.type === "checkbox") || r2.role === "radio" || r2.role === "checkbox" || r2.role === "switch") && r2.click(), r2.focus({ preventScroll: true });
      }
    }
  }), f2 = n$5({ ...e2.slot, disabled: T3 || false }), c2 = { ref: u2, ...e2.props, id: t2, htmlFor: p2, onClick: d2 };
  return b2 && ("onClick" in c2 && (delete c2.htmlFor, delete c2.onClick), "onClick" in i2 && delete i2.onClick), K()({ ourProps: c2, theirProps: i2, slot: f2, defaultTag: p2 ? G$2 : "div", name: e2.name || "Label" });
}
let j$5 = Y(U), Z = Object.assign(j$5, {});
let e$2 = reactExports.createContext(() => {
});
function C$3({ value: t2, children: o4 }) {
  return React.createElement(e$2.Provider, { value: t2 }, o4);
}
function l$3(e2, r2) {
  return e2 !== null && r2 !== null && typeof e2 == "object" && typeof r2 == "object" && "id" in e2 && "id" in r2 ? e2.id === r2.id : e2 === r2;
}
function u$5(e2 = l$3) {
  return reactExports.useCallback((r2, t2) => {
    if (typeof e2 == "string") {
      let o4 = e2;
      return (r2 == null ? void 0 : r2[o4]) === (t2 == null ? void 0 : t2[o4]);
    }
    return e2(r2, t2);
  }, [e2]);
}
let a$a = class a extends Map {
  constructor(t2) {
    super();
    this.factory = t2;
  }
  get(t2) {
    let e2 = super.get(t2);
    return e2 === void 0 && (e2 = this.factory(t2), this.set(t2, e2)), e2;
  }
};
var h$3 = Object.defineProperty;
var v$1 = (t2, e2, r2) => e2 in t2 ? h$3(t2, e2, { enumerable: true, configurable: true, writable: true, value: r2 }) : t2[e2] = r2;
var S$5 = (t2, e2, r2) => (v$1(t2, e2 + "", r2), r2), b$1 = (t2, e2, r2) => {
  if (!e2.has(t2)) throw TypeError("Cannot " + r2);
};
var i$6 = (t2, e2, r2) => (b$1(t2, e2, "read from private field"), r2 ? r2.call(t2) : e2.get(t2)), c$6 = (t2, e2, r2) => {
  if (e2.has(t2)) throw TypeError("Cannot add the same private member more than once");
  e2 instanceof WeakSet ? e2.add(t2) : e2.set(t2, r2);
}, u$4 = (t2, e2, r2, s2) => (b$1(t2, e2, "write to private field"), e2.set(t2, r2), r2);
var n$3, a$9, o$2;
let T$2 = class T {
  constructor(e2) {
    c$6(this, n$3, {});
    c$6(this, a$9, new a$a(() => /* @__PURE__ */ new Set()));
    c$6(this, o$2, /* @__PURE__ */ new Set());
    S$5(this, "disposables", o$6());
    u$4(this, n$3, e2), s$a.isServer && this.disposables.microTask(() => {
      this.dispose();
    });
  }
  dispose() {
    this.disposables.dispose();
  }
  get state() {
    return i$6(this, n$3);
  }
  subscribe(e2, r2) {
    if (s$a.isServer) return () => {
    };
    let s2 = { selector: e2, callback: r2, current: e2(i$6(this, n$3)) };
    return i$6(this, o$2).add(s2), this.disposables.add(() => {
      i$6(this, o$2).delete(s2);
    });
  }
  on(e2, r2) {
    return s$a.isServer ? () => {
    } : (i$6(this, a$9).get(e2).add(r2), this.disposables.add(() => {
      i$6(this, a$9).get(e2).delete(r2);
    }));
  }
  send(e2) {
    let r2 = this.reduce(i$6(this, n$3), e2);
    if (r2 !== i$6(this, n$3)) {
      u$4(this, n$3, r2);
      for (let s2 of i$6(this, o$2)) {
        let l2 = s2.selector(i$6(this, n$3));
        j$4(s2.current, l2) || (s2.current = l2, s2.callback(l2));
      }
      for (let s2 of i$6(this, a$9).get(e2.type)) s2(i$6(this, n$3), e2);
    }
  }
};
n$3 = /* @__PURE__ */ new WeakMap(), a$9 = /* @__PURE__ */ new WeakMap(), o$2 = /* @__PURE__ */ new WeakMap();
function j$4(t2, e2) {
  return Object.is(t2, e2) ? true : typeof t2 != "object" || t2 === null || typeof e2 != "object" || e2 === null ? false : Array.isArray(t2) && Array.isArray(e2) ? t2.length !== e2.length ? false : f$5(t2[Symbol.iterator](), e2[Symbol.iterator]()) : t2 instanceof Map && e2 instanceof Map || t2 instanceof Set && e2 instanceof Set ? t2.size !== e2.size ? false : f$5(t2.entries(), e2.entries()) : p$2(t2) && p$2(e2) ? f$5(Object.entries(t2)[Symbol.iterator](), Object.entries(e2)[Symbol.iterator]()) : false;
}
function f$5(t2, e2) {
  do {
    let r2 = t2.next(), s2 = e2.next();
    if (r2.done && s2.done) return true;
    if (r2.done || s2.done || !Object.is(r2.value, s2.value)) return false;
  } while (true);
}
function p$2(t2) {
  if (Object.prototype.toString.call(t2) !== "[object Object]") return false;
  let e2 = Object.getPrototypeOf(t2);
  return e2 === null || Object.getPrototypeOf(e2) === null;
}
var a$8 = Object.defineProperty;
var r$2 = (e2, c2, t2) => c2 in e2 ? a$8(e2, c2, { enumerable: true, configurable: true, writable: true, value: t2 }) : e2[c2] = t2;
var p$1 = (e2, c2, t2) => (r$2(e2, typeof c2 != "symbol" ? c2 + "" : c2, t2), t2);
var k$2 = ((t2) => (t2[t2.Push = 0] = "Push", t2[t2.Pop = 1] = "Pop", t2))(k$2 || {});
let y$1 = { [0](e2, c2) {
  let t2 = c2.id, s2 = e2.stack, i2 = e2.stack.indexOf(t2);
  if (i2 !== -1) {
    let n2 = e2.stack.slice();
    return n2.splice(i2, 1), n2.push(t2), s2 = n2, { ...e2, stack: s2 };
  }
  return { ...e2, stack: [...e2.stack, t2] };
}, [1](e2, c2) {
  let t2 = c2.id, s2 = e2.stack.indexOf(t2);
  if (s2 === -1) return e2;
  let i2 = e2.stack.slice();
  return i2.splice(s2, 1), { ...e2, stack: i2 };
} };
let o$1 = class o2 extends T$2 {
  constructor() {
    super(...arguments);
    p$1(this, "actions", { push: (t2) => this.send({ type: 0, id: t2 }), pop: (t2) => this.send({ type: 1, id: t2 }) });
    p$1(this, "selectors", { isTop: (t2, s2) => t2.stack[t2.stack.length - 1] === s2, inStack: (t2, s2) => t2.stack.includes(s2) });
  }
  static new() {
    return new o2({ stack: [] });
  }
  reduce(t2, s2) {
    return u$9(s2.type, y$1, t2, s2);
  }
};
const x$5 = new a$a(() => o$1.new());
var withSelector = { exports: {} };
var useSyncExternalStoreWithSelector_production = {};
/**
 * @license React
 * use-sync-external-store-with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredUseSyncExternalStoreWithSelector_production;
function requireUseSyncExternalStoreWithSelector_production() {
  if (hasRequiredUseSyncExternalStoreWithSelector_production) return useSyncExternalStoreWithSelector_production;
  hasRequiredUseSyncExternalStoreWithSelector_production = 1;
  var React2 = requireReact();
  function is2(x, y2) {
    return x === y2 && (0 !== x || 1 / x === 1 / y2) || x !== x && y2 !== y2;
  }
  var objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore = React2.useSyncExternalStore, useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue;
  useSyncExternalStoreWithSelector_production.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
    var instRef = useRef(null);
    if (null === instRef.current) {
      var inst = { hasValue: false, value: null };
      instRef.current = inst;
    } else inst = instRef.current;
    instRef = useMemo(
      function() {
        function memoizedSelector(nextSnapshot) {
          if (!hasMemo) {
            hasMemo = true;
            memoizedSnapshot = nextSnapshot;
            nextSnapshot = selector(nextSnapshot);
            if (void 0 !== isEqual && inst.hasValue) {
              var currentSelection = inst.value;
              if (isEqual(currentSelection, nextSnapshot))
                return memoizedSelection = currentSelection;
            }
            return memoizedSelection = nextSnapshot;
          }
          currentSelection = memoizedSelection;
          if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
          var nextSelection = selector(nextSnapshot);
          if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
            return memoizedSnapshot = nextSnapshot, currentSelection;
          memoizedSnapshot = nextSnapshot;
          return memoizedSelection = nextSelection;
        }
        var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
        return [
          function() {
            return memoizedSelector(getSnapshot());
          },
          null === maybeGetServerSnapshot ? void 0 : function() {
            return memoizedSelector(maybeGetServerSnapshot());
          }
        ];
      },
      [getSnapshot, getServerSnapshot, selector, isEqual]
    );
    var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
    useEffect(
      function() {
        inst.hasValue = true;
        inst.value = value;
      },
      [value]
    );
    useDebugValue(value);
    return value;
  };
  return useSyncExternalStoreWithSelector_production;
}
var hasRequiredWithSelector;
function requireWithSelector() {
  if (hasRequiredWithSelector) return withSelector.exports;
  hasRequiredWithSelector = 1;
  {
    withSelector.exports = requireUseSyncExternalStoreWithSelector_production();
  }
  return withSelector.exports;
}
var withSelectorExports = requireWithSelector();
function S$4(e2, n2, r2 = j$4) {
  return withSelectorExports.useSyncExternalStoreWithSelector(o$5((i2) => e2.subscribe(s$5, i2)), o$5(() => e2.state), o$5(() => e2.state), o$5(n2), r2);
}
function s$5(e2) {
  return e2;
}
function I$3(o4, s2) {
  let t2 = reactExports.useId(), r2 = x$5.get(s2), [i2, c2] = S$4(r2, reactExports.useCallback((e2) => [r2.selectors.isTop(e2, t2), r2.selectors.inStack(e2, t2)], [r2, t2]));
  return n$6(() => {
    if (o4) return r2.actions.push(t2), () => r2.actions.pop(t2);
  }, [r2, o4, t2]), o4 ? c2 ? i2 : true : false;
}
let f$4 = /* @__PURE__ */ new Map(), u$3 = /* @__PURE__ */ new Map();
function h$2(t2) {
  var e2;
  let r2 = (e2 = u$3.get(t2)) != null ? e2 : 0;
  return u$3.set(t2, r2 + 1), r2 !== 0 ? () => m$2(t2) : (f$4.set(t2, { "aria-hidden": t2.getAttribute("aria-hidden"), inert: t2.inert }), t2.setAttribute("aria-hidden", "true"), t2.inert = true, () => m$2(t2));
}
function m$2(t2) {
  var i2;
  let r2 = (i2 = u$3.get(t2)) != null ? i2 : 1;
  if (r2 === 1 ? u$3.delete(t2) : u$3.set(t2, r2 - 1), r2 !== 1) return;
  let e2 = f$4.get(t2);
  e2 && (e2["aria-hidden"] === null ? t2.removeAttribute("aria-hidden") : t2.setAttribute("aria-hidden", e2["aria-hidden"]), t2.inert = e2.inert, f$4.delete(t2));
}
function y(t2, { allowed: r2, disallowed: e2 } = {}) {
  let i2 = I$3(t2, "inert-others");
  n$6(() => {
    var d2, c2;
    if (!i2) return;
    let a3 = o$6();
    for (let n2 of (d2 = e2 == null ? void 0 : e2()) != null ? d2 : []) n2 && a3.add(h$2(n2));
    let s2 = (c2 = r2 == null ? void 0 : r2()) != null ? c2 : [];
    for (let n2 of s2) {
      if (!n2) continue;
      let l2 = l$7(n2);
      if (!l2) continue;
      let o4 = n2.parentElement;
      for (; o4 && o4 !== l2.body; ) {
        for (let p2 of o4.children) s2.some((E2) => p2.contains(E2)) || a3.add(h$2(p2));
        o4 = o4.parentElement;
      }
    }
    return a3.dispose;
  }, [i2, r2, e2]);
}
function p(s2, n2, o4) {
  let i2 = s$9((t2) => {
    let e2 = t2.getBoundingClientRect();
    e2.x === 0 && e2.y === 0 && e2.width === 0 && e2.height === 0 && o4();
  });
  reactExports.useEffect(() => {
    if (!s2) return;
    let t2 = n2 === null ? null : n$4(n2) ? n2 : n2.current;
    if (!t2) return;
    let e2 = o$6();
    if (typeof ResizeObserver != "undefined") {
      let r2 = new ResizeObserver(() => i2.current(t2));
      r2.observe(t2), e2.add(() => r2.disconnect());
    }
    if (typeof IntersectionObserver != "undefined") {
      let r2 = new IntersectionObserver(() => i2.current(t2));
      r2.observe(t2), e2.add(() => r2.disconnect());
    }
    return () => e2.dispose();
  }, [n2, i2, s2]);
}
let E$2 = ["[contentEditable=true]", "[tabindex]", "a[href]", "area[href]", "button:not([disabled])", "iframe", "input:not([disabled])", "select:not([disabled])", "details>summary", "textarea:not([disabled])"].map((e2) => `${e2}:not([tabindex='-1'])`).join(","), S$3 = ["[data-autofocus]"].map((e2) => `${e2}:not([tabindex='-1'])`).join(",");
var T$1 = ((o4) => (o4[o4.First = 1] = "First", o4[o4.Previous = 2] = "Previous", o4[o4.Next = 4] = "Next", o4[o4.Last = 8] = "Last", o4[o4.WrapAround = 16] = "WrapAround", o4[o4.NoScroll = 32] = "NoScroll", o4[o4.AutoFocus = 64] = "AutoFocus", o4))(T$1 || {}), A$1 = ((n2) => (n2[n2.Error = 0] = "Error", n2[n2.Overflow = 1] = "Overflow", n2[n2.Success = 2] = "Success", n2[n2.Underflow = 3] = "Underflow", n2))(A$1 || {}), O$1 = ((t2) => (t2[t2.Previous = -1] = "Previous", t2[t2.Next = 1] = "Next", t2))(O$1 || {});
function x$4(e2 = document.body) {
  return e2 == null ? [] : Array.from(e2.querySelectorAll(E$2)).sort((r2, t2) => Math.sign((r2.tabIndex || Number.MAX_SAFE_INTEGER) - (t2.tabIndex || Number.MAX_SAFE_INTEGER)));
}
function h$1(e2 = document.body) {
  return e2 == null ? [] : Array.from(e2.querySelectorAll(S$3)).sort((r2, t2) => Math.sign((r2.tabIndex || Number.MAX_SAFE_INTEGER) - (t2.tabIndex || Number.MAX_SAFE_INTEGER)));
}
var I$2 = ((t2) => (t2[t2.Strict = 0] = "Strict", t2[t2.Loose = 1] = "Loose", t2))(I$2 || {});
function H$1(e2, r2 = 0) {
  var t2;
  return e2 === ((t2 = l$7(e2)) == null ? void 0 : t2.body) ? false : u$9(r2, { [0]() {
    return e2.matches(E$2);
  }, [1]() {
    let l2 = e2;
    for (; l2 !== null; ) {
      if (l2.matches(E$2)) return true;
      l2 = l2.parentElement;
    }
    return false;
  } });
}
var g$2 = ((t2) => (t2[t2.Keyboard = 0] = "Keyboard", t2[t2.Mouse = 1] = "Mouse", t2))(g$2 || {});
typeof window != "undefined" && typeof document != "undefined" && (document.addEventListener("keydown", (e2) => {
  e2.metaKey || e2.altKey || e2.ctrlKey || (document.documentElement.dataset.headlessuiFocusVisible = "");
}, true), document.addEventListener("click", (e2) => {
  e2.detail === 1 ? delete document.documentElement.dataset.headlessuiFocusVisible : e2.detail === 0 && (document.documentElement.dataset.headlessuiFocusVisible = "");
}, true));
function w$4(e2) {
  e2 == null || e2.focus({ preventScroll: true });
}
let _$2 = ["textarea", "input"].join(",");
function P(e2) {
  var r2, t2;
  return (t2 = (r2 = e2 == null ? void 0 : e2.matches) == null ? void 0 : r2.call(e2, _$2)) != null ? t2 : false;
}
function G$1(e2, r2 = (t2) => t2) {
  return e2.slice().sort((t2, l2) => {
    let n2 = r2(t2), a3 = r2(l2);
    if (n2 === null || a3 === null) return 0;
    let u2 = n2.compareDocumentPosition(a3);
    return u2 & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : u2 & Node.DOCUMENT_POSITION_PRECEDING ? 1 : 0;
  });
}
function v(e2, r2, { sorted: t2 = true, relativeTo: l2 = null, skipElements: n2 = [] } = {}) {
  let a3 = Array.isArray(e2) ? e2.length > 0 ? r$6(e2[0]) : document : r$6(e2), u2 = Array.isArray(e2) ? t2 ? G$1(e2) : e2 : r2 & 64 ? h$1(e2) : x$4(e2);
  n2.length > 0 && u2.length > 1 && (u2 = u2.filter((i2) => !n2.some((d2) => d2 != null && "current" in d2 ? (d2 == null ? void 0 : d2.current) === i2 : d2 === i2))), l2 = l2 != null ? l2 : a3 == null ? void 0 : a3.activeElement;
  let o4 = (() => {
    if (r2 & 5) return 1;
    if (r2 & 10) return -1;
    throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last");
  })(), M2 = (() => {
    if (r2 & 1) return 0;
    if (r2 & 2) return Math.max(0, u2.indexOf(l2)) - 1;
    if (r2 & 4) return Math.max(0, u2.indexOf(l2)) + 1;
    if (r2 & 8) return u2.length - 1;
    throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last");
  })(), N2 = r2 & 32 ? { preventScroll: true } : {}, m2 = 0, c2 = u2.length, s2;
  do {
    if (m2 >= c2 || m2 + c2 <= 0) return 0;
    let i2 = M2 + m2;
    if (r2 & 16) i2 = (i2 + c2) % c2;
    else {
      if (i2 < 0) return 3;
      if (i2 >= c2) return 1;
    }
    s2 = u2[i2], s2 == null || s2.focus(N2), m2 += o4;
  } while (s2 !== e$5(s2));
  return r2 & 6 && P(s2) && s2.select(), 2;
}
function t$2() {
  return /iPhone/gi.test(window.navigator.platform) || /Mac/gi.test(window.navigator.platform) && window.navigator.maxTouchPoints > 0;
}
function i$5() {
  return /Android/gi.test(window.navigator.userAgent);
}
function n$2() {
  return t$2() || i$5();
}
function i$4(t2, e2, o4, n2) {
  let u2 = s$9(o4);
  reactExports.useEffect(() => {
    if (!t2) return;
    function r2(m2) {
      u2.current(m2);
    }
    return document.addEventListener(e2, r2, n2), () => document.removeEventListener(e2, r2, n2);
  }, [t2, e2, n2]);
}
function s$4(t2, e2, o4, n2) {
  let i2 = s$9(o4);
  reactExports.useEffect(() => {
    if (!t2) return;
    function r2(d2) {
      i2.current(d2);
    }
    return window.addEventListener(e2, r2, n2), () => window.removeEventListener(e2, r2, n2);
  }, [t2, e2, n2]);
}
const C$2 = 30;
function k$1(o4, f2, h2) {
  let m2 = s$9(h2), s2 = reactExports.useCallback(function(e2, c2) {
    if (e2.defaultPrevented) return;
    let r2 = c2(e2);
    if (r2 === null || !r2.getRootNode().contains(r2) || !r2.isConnected) return;
    let M2 = (function u2(n2) {
      return typeof n2 == "function" ? u2(n2()) : Array.isArray(n2) || n2 instanceof Set ? n2 : [n2];
    })(f2);
    for (let u2 of M2) if (u2 !== null && (u2.contains(r2) || e2.composed && e2.composedPath().includes(u2))) return;
    return !H$1(r2, I$2.Loose) && r2.tabIndex !== -1 && e2.preventDefault(), m2.current(e2, r2);
  }, [m2, f2]), i2 = reactExports.useRef(null);
  i$4(o4, "pointerdown", (t2) => {
    var e2, c2;
    n$2() || (i2.current = ((c2 = (e2 = t2.composedPath) == null ? void 0 : e2.call(t2)) == null ? void 0 : c2[0]) || t2.target);
  }, true), i$4(o4, "pointerup", (t2) => {
    if (n$2() || !i2.current) return;
    let e2 = i2.current;
    return i2.current = null, s2(t2, () => e2);
  }, true);
  let l2 = reactExports.useRef({ x: 0, y: 0 });
  i$4(o4, "touchstart", (t2) => {
    l2.current.x = t2.touches[0].clientX, l2.current.y = t2.touches[0].clientY;
  }, true), i$4(o4, "touchend", (t2) => {
    let e2 = { x: t2.changedTouches[0].clientX, y: t2.changedTouches[0].clientY };
    if (!(Math.abs(e2.x - l2.current.x) >= C$2 || Math.abs(e2.y - l2.current.y) >= C$2)) return s2(t2, () => i$7(t2.target) ? t2.target : null);
  }, true), s$4(o4, "blur", (t2) => s2(t2, () => u$7(window.document.activeElement) ? window.document.activeElement : null), true);
}
function u$2(...e2) {
  return reactExports.useMemo(() => l$7(...e2), [...e2]);
}
function E$1(n2, e2, a3, t2) {
  let i2 = s$9(a3);
  reactExports.useEffect(() => {
    n2 = n2 != null ? n2 : window;
    function r2(o4) {
      i2.current(o4);
    }
    return n2.addEventListener(e2, r2, t2), () => n2.removeEventListener(e2, r2, t2);
  }, [n2, e2, t2]);
}
function e$1(t2, u2) {
  return reactExports.useMemo(() => {
    var n2;
    if (t2.type) return t2.type;
    let r2 = (n2 = t2.as) != null ? n2 : "button";
    if (typeof r2 == "string" && r2.toLowerCase() === "button" || (u2 == null ? void 0 : u2.tagName) === "BUTTON" && !u2.hasAttribute("type")) return "button";
  }, [t2.type, t2.as, u2]);
}
function o3(t2) {
  return reactExports.useSyncExternalStore(t2.subscribe, t2.getSnapshot, t2.getSnapshot);
}
function a$7(o4, r2) {
  let t2 = o4(), n2 = /* @__PURE__ */ new Set();
  return { getSnapshot() {
    return t2;
  }, subscribe(e2) {
    return n2.add(e2), () => n2.delete(e2);
  }, dispatch(e2, ...s2) {
    let i2 = r2[e2].call(t2, ...s2);
    i2 && (t2 = i2, n2.forEach((c2) => c2()));
  } };
}
function d$1() {
  let r2;
  return { before({ doc: e2 }) {
    var l2;
    let o4 = e2.documentElement, t2 = (l2 = e2.defaultView) != null ? l2 : window;
    r2 = Math.max(0, t2.innerWidth - o4.clientWidth);
  }, after({ doc: e2, d: o4 }) {
    let t2 = e2.documentElement, l2 = Math.max(0, t2.clientWidth - t2.offsetWidth), n2 = Math.max(0, r2 - l2);
    o4.style(t2, "paddingRight", `${n2}px`);
  } };
}
function w$3() {
  return t$2() ? { before({ doc: o4, d: r2, meta: m2 }) {
    function a3(s2) {
      for (let l2 of m2().containers) for (let c2 of l2()) if (c2.contains(s2)) return true;
      return false;
    }
    r2.microTask(() => {
      var c2;
      if (window.getComputedStyle(o4.documentElement).scrollBehavior !== "auto") {
        let t2 = o$6();
        t2.style(o4.documentElement, "scrollBehavior", "auto"), r2.add(() => r2.microTask(() => t2.dispose()));
      }
      let s2 = (c2 = window.scrollY) != null ? c2 : window.pageYOffset, l2 = null;
      r2.addEventListener(o4, "click", (t2) => {
        if (i$7(t2.target)) try {
          let e2 = t2.target.closest("a");
          if (!e2) return;
          let { hash: n2 } = new URL(e2.href), f2 = o4.querySelector(n2);
          i$7(f2) && !a3(f2) && (l2 = f2);
        } catch {
        }
      }, true), r2.group((t2) => {
        r2.addEventListener(o4, "touchstart", (e2) => {
          if (t2.dispose(), i$7(e2.target) && r$4(e2.target)) if (a3(e2.target)) {
            let n2 = e2.target;
            for (; n2.parentElement && a3(n2.parentElement); ) n2 = n2.parentElement;
            t2.style(n2, "overscrollBehavior", "contain");
          } else t2.style(e2.target, "touchAction", "none");
        });
      }), r2.addEventListener(o4, "touchmove", (t2) => {
        if (i$7(t2.target)) {
          if (l$4(t2.target)) return;
          if (a3(t2.target)) {
            let e2 = t2.target;
            for (; e2.parentElement && e2.dataset.headlessuiPortal !== "" && !(e2.scrollHeight > e2.clientHeight || e2.scrollWidth > e2.clientWidth); ) e2 = e2.parentElement;
            e2.dataset.headlessuiPortal === "" && t2.preventDefault();
          } else t2.preventDefault();
        }
      }, { passive: false }), r2.add(() => {
        var e2;
        let t2 = (e2 = window.scrollY) != null ? e2 : window.pageYOffset;
        s2 !== t2 && window.scrollTo(0, s2), l2 && l2.isConnected && (l2.scrollIntoView({ block: "nearest" }), l2 = null);
      });
    });
  } } : {};
}
function r$1() {
  return { before({ doc: e2, d: o4 }) {
    o4.style(e2.documentElement, "overflow", "hidden");
  } };
}
function r(e2) {
  let o4 = {};
  for (let t2 of e2) Object.assign(o4, t2(o4));
  return o4;
}
let c$5 = a$7(() => /* @__PURE__ */ new Map(), { PUSH(e2, o4) {
  var n2;
  let t2 = (n2 = this.get(e2)) != null ? n2 : { doc: e2, count: 0, d: o$6(), meta: /* @__PURE__ */ new Set(), computedMeta: {} };
  return t2.count++, t2.meta.add(o4), t2.computedMeta = r(t2.meta), this.set(e2, t2), this;
}, POP(e2, o4) {
  let t2 = this.get(e2);
  return t2 && (t2.count--, t2.meta.delete(o4), t2.computedMeta = r(t2.meta)), this;
}, SCROLL_PREVENT(e2) {
  let o4 = { doc: e2.doc, d: e2.d, meta() {
    return e2.computedMeta;
  } }, t2 = [w$3(), d$1(), r$1()];
  t2.forEach(({ before: n2 }) => n2 == null ? void 0 : n2(o4)), t2.forEach(({ after: n2 }) => n2 == null ? void 0 : n2(o4));
}, SCROLL_ALLOW({ d: e2 }) {
  e2.dispose();
}, TEARDOWN({ doc: e2 }) {
  this.delete(e2);
} });
c$5.subscribe(() => {
  let e2 = c$5.getSnapshot(), o4 = /* @__PURE__ */ new Map();
  for (let [t2] of e2) o4.set(t2, t2.documentElement.style.overflow);
  for (let t2 of e2.values()) {
    let n2 = o4.get(t2.doc) === "hidden", a3 = t2.count !== 0;
    (a3 && !n2 || !a3 && n2) && c$5.dispatch(t2.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", t2), t2.count === 0 && c$5.dispatch("TEARDOWN", t2);
  }
});
function a$6(r2, e2, n2 = () => ({ containers: [] })) {
  let f2 = o3(c$5), o$12 = e2 ? f2.get(e2) : void 0, i2 = o$12 ? o$12.count > 0 : false;
  return n$6(() => {
    if (!(!e2 || !r2)) return c$5.dispatch("PUSH", e2, n2), () => c$5.dispatch("POP", e2, n2);
  }, [r2, e2]), i2;
}
function f$3(e2, c2, n2 = () => [document.body]) {
  let r2 = I$3(e2, "scroll-lock");
  a$6(r2, c2, (t2) => {
    var o4;
    return { containers: [...(o4 = t2.containers) != null ? o4 : [], n2] };
  });
}
function c$4(u2 = 0) {
  let [r2, a3] = reactExports.useState(u2), g2 = reactExports.useCallback((e2) => a3(e2), []), s2 = reactExports.useCallback((e2) => a3((l2) => l2 | e2), []), m2 = reactExports.useCallback((e2) => (r2 & e2) === e2, [r2]), n2 = reactExports.useCallback((e2) => a3((l2) => l2 & ~e2), []), F2 = reactExports.useCallback((e2) => a3((l2) => l2 ^ e2), []);
  return { flags: r2, setFlag: g2, addFlag: s2, hasFlag: m2, removeFlag: n2, toggleFlag: F2 };
}
var define_process_env_default$1 = {};
var T2, S$2;
typeof process != "undefined" && typeof globalThis != "undefined" && typeof Element != "undefined" && ((T2 = process == null ? void 0 : define_process_env_default$1) == null ? void 0 : T2["NODE_ENV"]) === "test" && typeof ((S$2 = Element == null ? void 0 : Element.prototype) == null ? void 0 : S$2.getAnimations) == "undefined" && (Element.prototype.getAnimations = function() {
  return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.", "Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.", "", "Example usage:", "```js", "import { mockAnimationsApi } from 'jsdom-testing-mocks'", "mockAnimationsApi()", "```"].join(`
`)), [];
});
var A = ((i2) => (i2[i2.None = 0] = "None", i2[i2.Closed = 1] = "Closed", i2[i2.Enter = 2] = "Enter", i2[i2.Leave = 4] = "Leave", i2))(A || {});
function x$3(e2) {
  let r2 = {};
  for (let t2 in e2) e2[t2] === true && (r2[`data-${t2}`] = "");
  return r2;
}
function N(e2, r2, t2, n2) {
  let [i2, a3] = reactExports.useState(t2), { hasFlag: s2, addFlag: o4, removeFlag: l2 } = c$4(e2 && i2 ? 3 : 0), u2 = reactExports.useRef(false), f2 = reactExports.useRef(false), E2 = p$4();
  return n$6(() => {
    var d2;
    if (e2) {
      if (t2 && a3(true), !r2) {
        t2 && o4(3);
        return;
      }
      return (d2 = n2 == null ? void 0 : n2.start) == null || d2.call(n2, t2), C$1(r2, { inFlight: u2, prepare() {
        f2.current ? f2.current = false : f2.current = u2.current, u2.current = true, !f2.current && (t2 ? (o4(3), l2(4)) : (o4(4), l2(2)));
      }, run() {
        f2.current ? t2 ? (l2(3), o4(4)) : (l2(4), o4(3)) : t2 ? l2(1) : o4(1);
      }, done() {
        var p2;
        f2.current && D$2(r2) || (u2.current = false, l2(7), t2 || a3(false), (p2 = n2 == null ? void 0 : n2.end) == null || p2.call(n2, t2));
      } });
    }
  }, [e2, t2, r2, E2]), e2 ? [i2, { closed: s2(1), enter: s2(2), leave: s2(4), transition: s2(2) || s2(4) }] : [t2, { closed: void 0, enter: void 0, leave: void 0, transition: void 0 }];
}
function C$1(e2, { prepare: r2, run: t2, done: n2, inFlight: i2 }) {
  let a3 = o$6();
  return j$3(e2, { prepare: r2, inFlight: i2 }), a3.nextFrame(() => {
    t2(), a3.requestAnimationFrame(() => {
      a3.add(M$2(e2, n2));
    });
  }), a3.dispose;
}
function M$2(e2, r2) {
  var a3, s2;
  let t2 = o$6();
  if (!e2) return t2.dispose;
  let n2 = false;
  t2.add(() => {
    n2 = true;
  });
  let i2 = (s2 = (a3 = e2.getAnimations) == null ? void 0 : a3.call(e2).filter((o4) => o4 instanceof CSSTransition)) != null ? s2 : [];
  return i2.length === 0 ? (r2(), t2.dispose) : (Promise.allSettled(i2.map((o4) => o4.finished)).then(() => {
    n2 || r2();
  }), t2.dispose);
}
function j$3(e2, { inFlight: r2, prepare: t2 }) {
  if (r2 != null && r2.current) {
    t2();
    return;
  }
  let n2 = e2.style.transition;
  e2.style.transition = "none", t2(), e2.offsetHeight, e2.style.transition = n2;
}
function D$2(e2) {
  var t2, n2;
  return ((n2 = (t2 = e2.getAnimations) == null ? void 0 : t2.call(e2)) != null ? n2 : []).some((i2) => i2 instanceof CSSTransition && i2.playState !== "finished");
}
function m$1(u2, t2) {
  let e2 = reactExports.useRef([]), r2 = o$5(u2);
  reactExports.useEffect(() => {
    let o4 = [...e2.current];
    for (let [a3, l2] of t2.entries()) if (e2.current[a3] !== l2) {
      let n2 = r2(t2, o4);
      return e2.current = t2, n2;
    }
  }, [r2, ...t2]);
}
let n$1 = reactExports.createContext(null);
n$1.displayName = "OpenClosedContext";
var i$3 = ((e2) => (e2[e2.Open = 1] = "Open", e2[e2.Closed = 2] = "Closed", e2[e2.Closing = 4] = "Closing", e2[e2.Opening = 8] = "Opening", e2))(i$3 || {});
function u$1() {
  return reactExports.useContext(n$1);
}
function c$3({ value: o4, children: t2 }) {
  return React.createElement(n$1.Provider, { value: o4 }, t2);
}
function s$3({ children: o4 }) {
  return React.createElement(n$1.Provider, { value: null }, o4);
}
function t$1(n2) {
  function e2() {
    document.readyState !== "loading" && (n2(), document.removeEventListener("DOMContentLoaded", e2));
  }
  typeof window != "undefined" && typeof document != "undefined" && (document.addEventListener("DOMContentLoaded", e2), e2());
}
let n = [];
t$1(() => {
  function e2(t2) {
    if (!i$7(t2.target) || t2.target === document.body || n[0] === t2.target) return;
    let r2 = t2.target;
    r2 = r2.closest(E$2), n.unshift(r2 != null ? r2 : t2.target), n = n.filter((o4) => o4 != null && o4.isConnected), n.splice(10);
  }
  window.addEventListener("click", e2, { capture: true }), window.addEventListener("mousedown", e2, { capture: true }), window.addEventListener("focus", e2, { capture: true }), document.body.addEventListener("click", e2, { capture: true }), document.body.addEventListener("mousedown", e2, { capture: true }), document.body.addEventListener("focus", e2, { capture: true });
});
function c$2(t2) {
  let r2 = o$5(t2), e2 = reactExports.useRef(false);
  reactExports.useEffect(() => (e2.current = false, () => {
    e2.current = true, t$5(() => {
      e2.current && r2();
    });
  }), [r2]);
}
let e = reactExports.createContext(false);
function a$5() {
  return reactExports.useContext(e);
}
function l$2(o4) {
  return React.createElement(e.Provider, { value: o4.force }, o4.children);
}
function W$1(e2) {
  let o4 = a$5(), l2 = reactExports.useContext(c$1), [r2, p2] = reactExports.useState(() => {
    var s2;
    if (!o4 && l2 !== null) return (s2 = l2.current) != null ? s2 : null;
    if (s$a.isServer) return null;
    let t2 = e2 == null ? void 0 : e2.getElementById("headlessui-portal-root");
    if (t2) return t2;
    if (e2 === null) return null;
    let n2 = e2.createElement("div");
    return n2.setAttribute("id", "headlessui-portal-root"), e2.body.appendChild(n2);
  });
  return reactExports.useEffect(() => {
    r2 !== null && (e2 != null && e2.body.contains(r2) || e2 == null || e2.body.appendChild(r2));
  }, [r2, e2]), reactExports.useEffect(() => {
    o4 || l2 !== null && p2(l2.current);
  }, [l2, p2, o4]), r2;
}
let _$1 = reactExports.Fragment, j$2 = Y(function(o4, l2) {
  let { ownerDocument: r2 = null, ...p2 } = o4, t2 = reactExports.useRef(null), n2 = y$2(T$3((a3) => {
    t2.current = a3;
  }), l2), s2 = u$2(t2.current), C2 = r2 != null ? r2 : s2, u2 = W$1(C2), y2 = reactExports.useContext(m), g2 = p$4(), v5 = K();
  return c$2(() => {
    var a3;
    u2 && u2.childNodes.length <= 0 && ((a3 = u2.parentElement) == null || a3.removeChild(u2));
  }), u2 ? reactDomExports.createPortal(React.createElement("div", { "data-headlessui-portal": "", ref: (a3) => {
    g2.dispose(), y2 && a3 && g2.add(y2.register(a3));
  } }, v5({ ourProps: { ref: n2 }, theirProps: p2, slot: {}, defaultTag: _$1, name: "Portal" })), u2) : null;
});
function S$1(e2, o4) {
  let l2 = y$2(o4), { enabled: r2 = true, ownerDocument: p2, ...t2 } = e2, n2 = K();
  return r2 ? React.createElement(j$2, { ...t2, ownerDocument: p2, ref: l2 }) : n2({ ourProps: { ref: l2 }, theirProps: t2, slot: {}, defaultTag: _$1, name: "Portal" });
}
let I$1 = reactExports.Fragment, c$1 = reactExports.createContext(null);
function D$1(e2, o4) {
  let { target: l2, ...r2 } = e2, t2 = { ref: y$2(o4) }, n2 = K();
  return React.createElement(c$1.Provider, { value: l2 }, n2({ ourProps: t2, theirProps: r2, defaultTag: I$1, name: "Popover.Group" }));
}
let m = reactExports.createContext(null);
function ee$1() {
  let e2 = reactExports.useContext(m), o4 = reactExports.useRef([]), l2 = o$5((t2) => (o4.current.push(t2), e2 && e2.register(t2), () => r2(t2))), r2 = o$5((t2) => {
    let n2 = o4.current.indexOf(t2);
    n2 !== -1 && o4.current.splice(n2, 1), e2 && e2.unregister(t2);
  }), p2 = reactExports.useMemo(() => ({ register: l2, unregister: r2, portals: o4 }), [l2, r2, o4]);
  return [o4, reactExports.useMemo(() => function({ children: n2 }) {
    return React.createElement(m.Provider, { value: p2 }, n2);
  }, [p2])];
}
let J = Y(S$1), X$3 = Y(D$1), te$1 = Object.assign(J, { Group: X$3 });
function a$4(o4, r2 = typeof document != "undefined" ? document.defaultView : null, t2) {
  let n2 = I$3(o4, "escape");
  E$1(r2, "keydown", (e2) => {
    n2 && (e2.defaultPrevented || e2.key === o$3.Escape && t2(e2));
  });
}
function f$2() {
  var t2;
  let [e2] = reactExports.useState(() => typeof window != "undefined" && typeof window.matchMedia == "function" ? window.matchMedia("(pointer: coarse)") : null), [o4, c2] = reactExports.useState((t2 = e2 == null ? void 0 : e2.matches) != null ? t2 : false);
  return n$6(() => {
    if (!e2) return;
    function n2(r2) {
      c2(r2.matches);
    }
    return e2.addEventListener("change", n2), () => e2.removeEventListener("change", n2);
  }, [e2]), o4;
}
function S({ defaultContainers: l2 = [], portals: n2, mainTreeNode: o4 } = {}) {
  let c2 = o$5(() => {
    var r2, u2;
    let i2 = l$7(o4), t2 = [];
    for (let e2 of l2) e2 !== null && (t$3(e2) ? t2.push(e2) : "current" in e2 && t$3(e2.current) && t2.push(e2.current));
    if (n2 != null && n2.current) for (let e2 of n2.current) t2.push(e2);
    for (let e2 of (r2 = i2 == null ? void 0 : i2.querySelectorAll("html > *, body > *")) != null ? r2 : []) e2 !== document.body && e2 !== document.head && t$3(e2) && e2.id !== "headlessui-portal-root" && (o4 && (e2.contains(o4) || e2.contains((u2 = o4 == null ? void 0 : o4.getRootNode()) == null ? void 0 : u2.host)) || t2.some((E2) => e2.contains(E2)) || t2.push(e2));
    return t2;
  });
  return { resolveContainers: c2, contains: o$5((i2) => c2().some((t2) => t2.contains(i2))) };
}
let d = reactExports.createContext(null);
function j$1({ children: l2, node: n2 }) {
  let [o4, c2] = reactExports.useState(null), i2 = x$2(n2 != null ? n2 : o4);
  return React.createElement(d.Provider, { value: i2 }, l2, i2 === null && React.createElement(f$8, { features: s$7.Hidden, ref: (t2) => {
    var r2, u2;
    if (t2) {
      for (let e2 of (u2 = (r2 = l$7(t2)) == null ? void 0 : r2.querySelectorAll("html > *, body > *")) != null ? u2 : []) if (e2 !== document.body && e2 !== document.head && t$3(e2) && e2 != null && e2.contains(t2)) {
        c2(e2);
        break;
      }
    }
  } }));
}
function x$2(l2 = null) {
  var n2;
  return (n2 = reactExports.useContext(d)) != null ? n2 : l2;
}
function s$2() {
  let r2 = typeof document == "undefined";
  return "useSyncExternalStore" in t$6 ? ((o4) => o4.useSyncExternalStore)(t$6)(() => () => {
  }, () => false, () => !r2) : false;
}
function l$1() {
  let r2 = s$2(), [e2, n2] = reactExports.useState(s$a.isHandoffComplete);
  return e2 && s$a.isHandoffComplete === false && n2(false), reactExports.useEffect(() => {
    e2 !== true && n2(true);
  }, [e2]), reactExports.useEffect(() => s$a.handoff(), []), r2 ? false : e2;
}
function f$1() {
  let e2 = reactExports.useRef(false);
  return n$6(() => (e2.current = true, () => {
    e2.current = false;
  }), []), e2;
}
var a$3 = ((r2) => (r2[r2.Forwards = 0] = "Forwards", r2[r2.Backwards = 1] = "Backwards", r2))(a$3 || {});
function u() {
  let e2 = reactExports.useRef(0);
  return s$4(true, "keydown", (r2) => {
    r2.key === "Tab" && (e2.current = r2.shiftKey ? 1 : 0);
  }, true), e2;
}
function x$1(o4) {
  if (!o4) return /* @__PURE__ */ new Set();
  if (typeof o4 == "function") return new Set(o4());
  let t2 = /* @__PURE__ */ new Set();
  for (let e2 of o4.current) t$3(e2.current) && t2.add(e2.current);
  return t2;
}
let $ = "div";
var G = ((n2) => (n2[n2.None = 0] = "None", n2[n2.InitialFocus = 1] = "InitialFocus", n2[n2.TabLock = 2] = "TabLock", n2[n2.FocusLock = 4] = "FocusLock", n2[n2.RestoreFocus = 8] = "RestoreFocus", n2[n2.AutoFocus = 16] = "AutoFocus", n2))(G || {});
function w$2(o4, t2) {
  let e2 = reactExports.useRef(null), r2 = y$2(e2, t2), { initialFocus: u$12, initialFocusFallback: a3, containers: n2, features: s2 = 15, ...f2 } = o4;
  l$1() || (s2 = 0);
  let l2 = u$2(e2.current);
  re(s2, { ownerDocument: l2 });
  let T3 = ne(s2, { ownerDocument: l2, container: e2, initialFocus: u$12, initialFocusFallback: a3 });
  oe(s2, { ownerDocument: l2, container: e2, containers: n2, previousActiveElement: T3 });
  let g2 = u(), A2 = o$5((c2) => {
    if (!n$4(e2.current)) return;
    let E2 = e2.current;
    ((V2) => V2())(() => {
      u$9(g2.current, { [a$3.Forwards]: () => {
        v(E2, T$1.First, { skipElements: [c2.relatedTarget, a3] });
      }, [a$3.Backwards]: () => {
        v(E2, T$1.Last, { skipElements: [c2.relatedTarget, a3] });
      } });
    });
  }), v$12 = I$3(!!(s2 & 2), "focus-trap#tab-lock"), N2 = p$4(), b2 = reactExports.useRef(false), k2 = { ref: r2, onKeyDown(c2) {
    c2.key == "Tab" && (b2.current = true, N2.requestAnimationFrame(() => {
      b2.current = false;
    }));
  }, onBlur(c2) {
    if (!(s2 & 4)) return;
    let E2 = x$1(n2);
    n$4(e2.current) && E2.add(e2.current);
    let L2 = c2.relatedTarget;
    i$7(L2) && L2.dataset.headlessuiFocusGuard !== "true" && (I(E2, L2) || (b2.current ? v(e2.current, u$9(g2.current, { [a$3.Forwards]: () => T$1.Next, [a$3.Backwards]: () => T$1.Previous }) | T$1.WrapAround, { relativeTo: c2.target }) : i$7(c2.target) && w$4(c2.target)));
  } }, B = K();
  return React.createElement(React.Fragment, null, v$12 && React.createElement(f$8, { as: "button", type: "button", "data-headlessui-focus-guard": true, onFocus: A2, features: s$7.Focusable }), B({ ourProps: k2, theirProps: f2, defaultTag: $, name: "FocusTrap" }), v$12 && React.createElement(f$8, { as: "button", type: "button", "data-headlessui-focus-guard": true, onFocus: A2, features: s$7.Focusable }));
}
let ee = Y(w$2), ge$1 = Object.assign(ee, { features: G });
function te(o4 = true) {
  let t2 = reactExports.useRef(n.slice());
  return m$1(([e2], [r2]) => {
    r2 === true && e2 === false && t$5(() => {
      t2.current.splice(0);
    }), r2 === false && e2 === true && (t2.current = n.slice());
  }, [o4, n, t2]), o$5(() => {
    var e2;
    return (e2 = t2.current.find((r2) => r2 != null && r2.isConnected)) != null ? e2 : null;
  });
}
function re(o4, { ownerDocument: t2 }) {
  let e2 = !!(o4 & 8), r2 = te(e2);
  m$1(() => {
    e2 || d$2(t2 == null ? void 0 : t2.body) && w$4(r2());
  }, [e2]), c$2(() => {
    e2 && w$4(r2());
  });
}
function ne(o4, { ownerDocument: t2, container: e2, initialFocus: r2, initialFocusFallback: u2 }) {
  let a3 = reactExports.useRef(null), n2 = I$3(!!(o4 & 1), "focus-trap#initial-focus"), s2 = f$1();
  return m$1(() => {
    if (o4 === 0) return;
    if (!n2) {
      u2 != null && u2.current && w$4(u2.current);
      return;
    }
    let f2 = e2.current;
    f2 && t$5(() => {
      if (!s2.current) return;
      let l2 = t2 == null ? void 0 : t2.activeElement;
      if (r2 != null && r2.current) {
        if ((r2 == null ? void 0 : r2.current) === l2) {
          a3.current = l2;
          return;
        }
      } else if (f2.contains(l2)) {
        a3.current = l2;
        return;
      }
      if (r2 != null && r2.current) w$4(r2.current);
      else {
        if (o4 & 16) {
          if (v(f2, T$1.First | T$1.AutoFocus) !== A$1.Error) return;
        } else if (v(f2, T$1.First) !== A$1.Error) return;
        if (u2 != null && u2.current && (w$4(u2.current), (t2 == null ? void 0 : t2.activeElement) === u2.current)) return;
        console.warn("There are no focusable elements inside the <FocusTrap />");
      }
      a3.current = t2 == null ? void 0 : t2.activeElement;
    });
  }, [u2, n2, o4]), a3;
}
function oe(o4, { ownerDocument: t2, container: e2, containers: r2, previousActiveElement: u2 }) {
  let a3 = f$1(), n2 = !!(o4 & 4);
  E$1(t2 == null ? void 0 : t2.defaultView, "focus", (s2) => {
    if (!n2 || !a3.current) return;
    let f2 = x$1(r2);
    n$4(e2.current) && f2.add(e2.current);
    let l2 = u2.current;
    if (!l2) return;
    let T3 = s2.target;
    n$4(T3) ? I(f2, T3) ? (u2.current = T3, w$4(T3)) : (s2.preventDefault(), s2.stopPropagation(), w$4(l2)) : w$4(u2.current);
  }, true);
}
function I(o4, t2) {
  for (let e2 of o4) if (e2.contains(t2)) return true;
  return false;
}
function ue2(e2) {
  var t2;
  return !!(e2.enter || e2.enterFrom || e2.enterTo || e2.leave || e2.leaveFrom || e2.leaveTo) || !b$3((t2 = e2.as) != null ? t2 : de) || React.Children.count(e2.children) === 1;
}
let V$2 = reactExports.createContext(null);
V$2.displayName = "TransitionContext";
var De$2 = ((n2) => (n2.Visible = "visible", n2.Hidden = "hidden", n2))(De$2 || {});
function He$3() {
  let e2 = reactExports.useContext(V$2);
  if (e2 === null) throw new Error("A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.");
  return e2;
}
function Ae$1() {
  let e2 = reactExports.useContext(w$1);
  if (e2 === null) throw new Error("A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.");
  return e2;
}
let w$1 = reactExports.createContext(null);
w$1.displayName = "NestingContext";
function M$1(e2) {
  return "children" in e2 ? M$1(e2.children) : e2.current.filter(({ el: t2 }) => t2.current !== null).filter(({ state: t2 }) => t2 === "visible").length > 0;
}
function Te(e2, t2) {
  let n2 = s$9(e2), l2 = reactExports.useRef([]), S2 = f$1(), R2 = p$4(), d2 = o$5((o4, i2 = C$7.Hidden) => {
    let a3 = l2.current.findIndex(({ el: s2 }) => s2 === o4);
    a3 !== -1 && (u$9(i2, { [C$7.Unmount]() {
      l2.current.splice(a3, 1);
    }, [C$7.Hidden]() {
      l2.current[a3].state = "hidden";
    } }), R2.microTask(() => {
      var s2;
      !M$1(l2) && S2.current && ((s2 = n2.current) == null || s2.call(n2));
    }));
  }), y2 = o$5((o4) => {
    let i2 = l2.current.find(({ el: a3 }) => a3 === o4);
    return i2 ? i2.state !== "visible" && (i2.state = "visible") : l2.current.push({ el: o4, state: "visible" }), () => d2(o4, C$7.Unmount);
  }), C2 = reactExports.useRef([]), p2 = reactExports.useRef(Promise.resolve()), h2 = reactExports.useRef({ enter: [], leave: [] }), g2 = o$5((o4, i2, a3) => {
    C2.current.splice(0), t2 && (t2.chains.current[i2] = t2.chains.current[i2].filter(([s2]) => s2 !== o4)), t2 == null || t2.chains.current[i2].push([o4, new Promise((s2) => {
      C2.current.push(s2);
    })]), t2 == null || t2.chains.current[i2].push([o4, new Promise((s2) => {
      Promise.all(h2.current[i2].map(([r2, f2]) => f2)).then(() => s2());
    })]), i2 === "enter" ? p2.current = p2.current.then(() => t2 == null ? void 0 : t2.wait.current).then(() => a3(i2)) : a3(i2);
  }), v5 = o$5((o4, i2, a3) => {
    Promise.all(h2.current[i2].splice(0).map(([s2, r2]) => r2)).then(() => {
      var s2;
      (s2 = C2.current.shift()) == null || s2();
    }).then(() => a3(i2));
  });
  return reactExports.useMemo(() => ({ children: l2, register: y2, unregister: d2, onStart: g2, onStop: v5, wait: p2, chains: h2 }), [y2, d2, l2, g2, v5, h2, p2]);
}
let de = reactExports.Fragment, fe$1 = A$2.RenderStrategy;
function Fe$2(e2, t2) {
  var ee2, te2;
  let { transition: n2 = true, beforeEnter: l2, afterEnter: S2, beforeLeave: R2, afterLeave: d2, enter: y2, enterFrom: C2, enterTo: p2, entered: h2, leave: g2, leaveFrom: v5, leaveTo: o4, ...i2 } = e2, [a3, s2] = reactExports.useState(null), r2 = reactExports.useRef(null), f2 = ue2(e2), U2 = y$2(...f2 ? [r2, t2, s2] : t2 === null ? [] : [t2]), H2 = (ee2 = i2.unmount) == null || ee2 ? C$7.Unmount : C$7.Hidden, { show: u2, appear: z2, initial: K$12 } = He$3(), [m2, j2] = reactExports.useState(u2 ? "visible" : "hidden"), Q2 = Ae$1(), { register: A2, unregister: F2 } = Q2;
  n$6(() => A2(r2), [A2, r2]), n$6(() => {
    if (H2 === C$7.Hidden && r2.current) {
      if (u2 && m2 !== "visible") {
        j2("visible");
        return;
      }
      return u$9(m2, { ["hidden"]: () => F2(r2), ["visible"]: () => A2(r2) });
    }
  }, [m2, r2, A2, F2, u2, H2]);
  let G2 = l$1();
  n$6(() => {
    if (f2 && G2 && m2 === "visible" && r2.current === null) throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?");
  }, [r2, m2, G2, f2]);
  let ce2 = K$12 && !z2, Y2 = z2 && u2 && K$12, B = reactExports.useRef(false), I2 = Te(() => {
    B.current || (j2("hidden"), F2(r2));
  }, Q2), Z2 = o$5((W2) => {
    B.current = true;
    let L2 = W2 ? "enter" : "leave";
    I2.onStart(r2, L2, (_2) => {
      _2 === "enter" ? l2 == null || l2() : _2 === "leave" && (R2 == null || R2());
    });
  }), $2 = o$5((W2) => {
    let L2 = W2 ? "enter" : "leave";
    B.current = false, I2.onStop(r2, L2, (_2) => {
      _2 === "enter" ? S2 == null || S2() : _2 === "leave" && (d2 == null || d2());
    }), L2 === "leave" && !M$1(I2) && (j2("hidden"), F2(r2));
  });
  reactExports.useEffect(() => {
    f2 && n2 || (Z2(u2), $2(u2));
  }, [u2, f2, n2]);
  let pe = /* @__PURE__ */ (() => !(!n2 || !f2 || !G2 || ce2))(), [, T3] = N(pe, a3, u2, { start: Z2, end: $2 }), Ce2 = m$4({ ref: U2, className: ((te2 = t$4(i2.className, Y2 && y2, Y2 && C2, T3.enter && y2, T3.enter && T3.closed && C2, T3.enter && !T3.closed && p2, T3.leave && g2, T3.leave && !T3.closed && v5, T3.leave && T3.closed && o4, !T3.transition && u2 && h2)) == null ? void 0 : te2.trim()) || void 0, ...x$3(T3) }), N$12 = 0;
  m2 === "visible" && (N$12 |= i$3.Open), m2 === "hidden" && (N$12 |= i$3.Closed), u2 && m2 === "hidden" && (N$12 |= i$3.Opening), !u2 && m2 === "visible" && (N$12 |= i$3.Closing);
  let he2 = K();
  return React.createElement(w$1.Provider, { value: I2 }, React.createElement(c$3, { value: N$12 }, he2({ ourProps: Ce2, theirProps: i2, defaultTag: de, features: fe$1, visible: m2 === "visible", name: "Transition.Child" })));
}
function Ie$3(e2, t2) {
  let { show: n2, appear: l2 = false, unmount: S2 = true, ...R2 } = e2, d2 = reactExports.useRef(null), y2 = ue2(e2), C2 = y$2(...y2 ? [d2, t2] : t2 === null ? [] : [t2]);
  l$1();
  let p2 = u$1();
  if (n2 === void 0 && p2 !== null && (n2 = (p2 & i$3.Open) === i$3.Open), n2 === void 0) throw new Error("A <Transition /> is used but it is missing a `show={true | false}` prop.");
  let [h2, g2] = reactExports.useState(n2 ? "visible" : "hidden"), v5 = Te(() => {
    n2 || g2("hidden");
  }), [o4, i2] = reactExports.useState(true), a3 = reactExports.useRef([n2]);
  n$6(() => {
    o4 !== false && a3.current[a3.current.length - 1] !== n2 && (a3.current.push(n2), i2(false));
  }, [a3, n2]);
  let s2 = reactExports.useMemo(() => ({ show: n2, appear: l2, initial: o4 }), [n2, l2, o4]);
  n$6(() => {
    n2 ? g2("visible") : !M$1(v5) && d2.current !== null && g2("hidden");
  }, [n2, v5]);
  let r2 = { unmount: S2 }, f2 = o$5(() => {
    var u2;
    o4 && i2(false), (u2 = e2.beforeEnter) == null || u2.call(e2);
  }), U2 = o$5(() => {
    var u2;
    o4 && i2(false), (u2 = e2.beforeLeave) == null || u2.call(e2);
  }), H2 = K();
  return React.createElement(w$1.Provider, { value: v5 }, React.createElement(V$2.Provider, { value: s2 }, H2({ ourProps: { ...r2, as: reactExports.Fragment, children: React.createElement(me$1, { ref: C2, ...r2, ...R2, beforeEnter: f2, beforeLeave: U2 }) }, theirProps: {}, defaultTag: reactExports.Fragment, features: fe$1, visible: h2 === "visible", name: "Transition" })));
}
function Le$2(e2, t2) {
  let n2 = reactExports.useContext(V$2) !== null, l2 = u$1() !== null;
  return React.createElement(React.Fragment, null, !n2 && l2 ? React.createElement(X$2, { ref: t2, ...e2 }) : React.createElement(me$1, { ref: t2, ...e2 }));
}
let X$2 = Y(Ie$3), me$1 = Y(Fe$2), Oe$1 = Y(Le$2), Ke$3 = Object.assign(X$2, { Child: Oe$1, Root: X$2 });
var we$2 = ((o4) => (o4[o4.Open = 0] = "Open", o4[o4.Closed = 1] = "Closed", o4))(we$2 || {}), Be$2 = ((t2) => (t2[t2.SetTitleId = 0] = "SetTitleId", t2))(Be$2 || {});
let Ue$2 = { [0](e2, t2) {
  return e2.titleId === t2.id ? e2 : { ...e2, titleId: t2.id };
} }, w = reactExports.createContext(null);
w.displayName = "DialogContext";
function O(e2) {
  let t2 = reactExports.useContext(w);
  if (t2 === null) {
    let o4 = new Error(`<${e2} /> is missing a parent <Dialog /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(o4, O), o4;
  }
  return t2;
}
function He$2(e2, t2) {
  return u$9(t2.type, Ue$2, e2, t2);
}
let z$2 = Y(function(t2, o4) {
  let a3 = reactExports.useId(), { id: n2 = `headlessui-dialog-${a3}`, open: i2, onClose: p$12, initialFocus: d2, role: s2 = "dialog", autoFocus: f2 = true, __demoMode: u2 = false, unmount: y$12 = false, ...S$12 } = t2, R2 = reactExports.useRef(false);
  s2 = (function() {
    return s2 === "dialog" || s2 === "alertdialog" ? s2 : (R2.current || (R2.current = true, console.warn(`Invalid role [${s2}] passed to <Dialog />. Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)), "dialog");
  })();
  let g2 = u$1();
  i2 === void 0 && g2 !== null && (i2 = (g2 & i$3.Open) === i$3.Open);
  let T3 = reactExports.useRef(null), I2 = y$2(T3, o4), F2 = u$2(T3.current), c2 = i2 ? 0 : 1, [b2, Q2] = reactExports.useReducer(He$2, { titleId: null, descriptionId: null, panelRef: reactExports.createRef() }), m2 = o$5(() => p$12(false)), B = o$5((r2) => Q2({ type: 0, id: r2 })), D2 = l$1() ? c2 === 0 : false, [Z2, ee2] = ee$1(), te2 = { get current() {
    var r2;
    return (r2 = b2.panelRef.current) != null ? r2 : T3.current;
  } }, v5 = x$2(), { resolveContainers: M2 } = S({ mainTreeNode: v5, portals: Z2, defaultContainers: [te2] }), U2 = g2 !== null ? (g2 & i$3.Closing) === i$3.Closing : false;
  y(u2 || U2 ? false : D2, { allowed: o$5(() => {
    var r2, W2;
    return [(W2 = (r2 = T3.current) == null ? void 0 : r2.closest("[data-headlessui-portal]")) != null ? W2 : null];
  }), disallowed: o$5(() => {
    var r2;
    return [(r2 = v5 == null ? void 0 : v5.closest("body > *:not(#headlessui-portal-root)")) != null ? r2 : null];
  }) });
  let P2 = x$5.get(null);
  n$6(() => {
    if (D2) return P2.actions.push(n2), () => P2.actions.pop(n2);
  }, [P2, n2, D2]);
  let H2 = S$4(P2, reactExports.useCallback((r2) => P2.selectors.isTop(r2, n2), [P2, n2]));
  k$1(H2, M2, (r2) => {
    r2.preventDefault(), m2();
  }), a$4(H2, F2 == null ? void 0 : F2.defaultView, (r2) => {
    r2.preventDefault(), r2.stopPropagation(), document.activeElement && "blur" in document.activeElement && typeof document.activeElement.blur == "function" && document.activeElement.blur(), m2();
  }), f$3(u2 || U2 ? false : D2, F2, M2), p(D2, T3, m2);
  let [oe2, ne2] = H$2(), re2 = reactExports.useMemo(() => [{ dialogState: c2, close: m2, setTitleId: B, unmount: y$12 }, b2], [c2, m2, B, y$12, b2]), N2 = n$5({ open: c2 === 0 }), le2 = { ref: I2, id: n2, role: s2, tabIndex: -1, "aria-modal": u2 ? void 0 : c2 === 0 ? true : void 0, "aria-labelledby": b2.titleId, "aria-describedby": oe2, unmount: y$12 }, ae = !f$2(), E2 = G.None;
  D2 && !u2 && (E2 |= G.RestoreFocus, E2 |= G.TabLock, f2 && (E2 |= G.AutoFocus), ae && (E2 |= G.InitialFocus));
  let ie = K();
  return React.createElement(s$3, null, React.createElement(l$2, { force: true }, React.createElement(te$1, null, React.createElement(w.Provider, { value: re2 }, React.createElement(X$3, { target: T3 }, React.createElement(l$2, { force: false }, React.createElement(ne2, { slot: N2 }, React.createElement(ee2, null, React.createElement(ge$1, { initialFocus: d2, initialFocusFallback: T3, containers: M2, features: E2 }, React.createElement(C$3, { value: m2 }, ie({ ourProps: le2, theirProps: S$12, slot: N2, defaultTag: Ne$2, features: We$2, visible: c2 === 0, name: "Dialog" })))))))))));
}), Ne$2 = "div", We$2 = A$2.RenderStrategy | A$2.Static;
function $e$1(e2, t2) {
  let { transition: o4 = false, open: a3, ...n2 } = e2, i2 = u$1(), p2 = e2.hasOwnProperty("open") || i2 !== null, d2 = e2.hasOwnProperty("onClose");
  if (!p2 && !d2) throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");
  if (!p2) throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");
  if (!d2) throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");
  if (!i2 && typeof e2.open != "boolean") throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${e2.open}`);
  if (typeof e2.onClose != "function") throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${e2.onClose}`);
  return (a3 !== void 0 || o4) && !n2.static ? React.createElement(j$1, null, React.createElement(Ke$3, { show: a3, transition: o4, unmount: n2.unmount }, React.createElement(z$2, { ref: t2, ...n2 }))) : React.createElement(j$1, null, React.createElement(z$2, { ref: t2, open: a3, ...n2 }));
}
let je$2 = "div";
function Ye(e2, t2) {
  let o4 = reactExports.useId(), { id: a3 = `headlessui-dialog-panel-${o4}`, transition: n2 = false, ...i2 } = e2, [{ dialogState: p2, unmount: d2 }, s2] = O("Dialog.Panel"), f2 = y$2(t2, s2.panelRef), u2 = n$5({ open: p2 === 0 }), y2 = o$5((I2) => {
    I2.stopPropagation();
  }), S2 = { ref: f2, id: a3, onClick: y2 }, R2 = n2 ? Oe$1 : reactExports.Fragment, g2 = n2 ? { unmount: d2 } : {}, T3 = K();
  return React.createElement(R2, { ...g2 }, T3({ ourProps: S2, theirProps: i2, slot: u2, defaultTag: je$2, name: "Dialog.Panel" }));
}
let Je = "div";
function Ke$2(e2, t2) {
  let { transition: o4 = false, ...a3 } = e2, [{ dialogState: n2, unmount: i2 }] = O("Dialog.Backdrop"), p2 = n$5({ open: n2 === 0 }), d2 = { ref: t2, "aria-hidden": true }, s2 = o4 ? Oe$1 : reactExports.Fragment, f2 = o4 ? { unmount: i2 } : {}, u2 = K();
  return React.createElement(s2, { ...f2 }, u2({ ourProps: d2, theirProps: a3, slot: p2, defaultTag: Je, name: "Dialog.Backdrop" }));
}
let Xe$1 = "h2";
function Ve$1(e2, t2) {
  let o4 = reactExports.useId(), { id: a3 = `headlessui-dialog-title-${o4}`, ...n2 } = e2, [{ dialogState: i2, setTitleId: p2 }] = O("Dialog.Title"), d2 = y$2(t2);
  reactExports.useEffect(() => (p2(a3), () => p2(null)), [a3, p2]);
  let s2 = n$5({ open: i2 === 0 }), f2 = { ref: d2, id: a3 };
  return K()({ ourProps: f2, theirProps: n2, slot: s2, defaultTag: Xe$1, name: "Dialog.Title" });
}
let qe = Y($e$1), ze = Y(Ye), Lt = Y(Ke$2), Qe = Y(Ve$1), ht = Object.assign(qe, { Panel: ze, Title: Qe, Description: M$3 });
var t;
let a$2 = (t = React.startTransition) != null ? t : function(i2) {
  i2();
};
var me = ((l2) => (l2[l2.Open = 0] = "Open", l2[l2.Closed = 1] = "Closed", l2))(me || {}), fe = ((n2) => (n2[n2.ToggleDisclosure = 0] = "ToggleDisclosure", n2[n2.CloseDisclosure = 1] = "CloseDisclosure", n2[n2.SetButtonId = 2] = "SetButtonId", n2[n2.SetPanelId = 3] = "SetPanelId", n2[n2.SetButtonElement = 4] = "SetButtonElement", n2[n2.SetPanelElement = 5] = "SetPanelElement", n2))(fe || {});
let De$1 = { [0]: (e2) => ({ ...e2, disclosureState: u$9(e2.disclosureState, { [0]: 1, [1]: 0 }) }), [1]: (e2) => e2.disclosureState === 1 ? e2 : { ...e2, disclosureState: 1 }, [2](e2, t2) {
  return e2.buttonId === t2.buttonId ? e2 : { ...e2, buttonId: t2.buttonId };
}, [3](e2, t2) {
  return e2.panelId === t2.panelId ? e2 : { ...e2, panelId: t2.panelId };
}, [4](e2, t2) {
  return e2.buttonElement === t2.element ? e2 : { ...e2, buttonElement: t2.element };
}, [5](e2, t2) {
  return e2.panelElement === t2.element ? e2 : { ...e2, panelElement: t2.element };
} }, _ = reactExports.createContext(null);
_.displayName = "DisclosureContext";
function M(e2) {
  let t2 = reactExports.useContext(_);
  if (t2 === null) {
    let l2 = new Error(`<${e2} /> is missing a parent <Disclosure /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(l2, M), l2;
  }
  return t2;
}
let F = reactExports.createContext(null);
F.displayName = "DisclosureAPIContext";
function V$1(e2) {
  let t2 = reactExports.useContext(F);
  if (t2 === null) {
    let l2 = new Error(`<${e2} /> is missing a parent <Disclosure /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(l2, V$1), l2;
  }
  return t2;
}
let H = reactExports.createContext(null);
H.displayName = "DisclosurePanelContext";
function ye() {
  return reactExports.useContext(H);
}
function Pe(e2, t2) {
  return u$9(t2.type, De$1, e2, t2);
}
let Ee = reactExports.Fragment;
function Se$2(e2, t2) {
  let { defaultOpen: l2 = false, ...p2 } = e2, a3 = reactExports.useRef(null), c2 = y$2(t2, T$3((u2) => {
    a3.current = u2;
  }, e2.as === void 0 || b$3(e2.as))), n2 = reactExports.useReducer(Pe, { disclosureState: l2 ? 0 : 1, buttonElement: null, panelElement: null, buttonId: null, panelId: null }), [{ disclosureState: o4, buttonId: r2 }, f2] = n2, s2 = o$5((u2) => {
    f2({ type: 1 });
    let m2 = l$7(a3.current);
    if (!m2 || !r2) return;
    let d2 = (() => u2 ? i$7(u2) ? u2 : "current" in u2 && i$7(u2.current) ? u2.current : m2.getElementById(r2) : m2.getElementById(r2))();
    d2 == null || d2.focus();
  }), E2 = reactExports.useMemo(() => ({ close: s2 }), [s2]), T3 = n$5({ open: o4 === 0, close: s2 }), D2 = { ref: c2 }, S2 = K();
  return React.createElement(_.Provider, { value: n2 }, React.createElement(F.Provider, { value: E2 }, React.createElement(C$3, { value: s2 }, React.createElement(c$3, { value: u$9(o4, { [0]: i$3.Open, [1]: i$3.Closed }) }, S2({ ourProps: D2, theirProps: p2, slot: T3, defaultTag: Ee, name: "Disclosure" })))));
}
let ge = "button";
function Ae(e2, t2) {
  let l2 = reactExports.useId(), { id: p2 = `headlessui-disclosure-button-${l2}`, disabled: a3 = false, autoFocus: c2 = false, ...n2 } = e2, [o4, r2] = M("Disclosure.Button"), f2 = ye(), s2 = f2 === null ? false : f2 === o4.panelId, E2 = reactExports.useRef(null), T3 = y$2(E2, t2, o$5((i2) => {
    if (!s2) return r2({ type: 4, element: i2 });
  }));
  reactExports.useEffect(() => {
    if (!s2) return r2({ type: 2, buttonId: p2 }), () => {
      r2({ type: 2, buttonId: null });
    };
  }, [p2, r2, s2]);
  let D2 = o$5((i2) => {
    var g2;
    if (s2) {
      if (o4.disclosureState === 1) return;
      switch (i2.key) {
        case o$3.Space:
        case o$3.Enter:
          i2.preventDefault(), i2.stopPropagation(), r2({ type: 0 }), (g2 = o4.buttonElement) == null || g2.focus();
          break;
      }
    } else switch (i2.key) {
      case o$3.Space:
      case o$3.Enter:
        i2.preventDefault(), i2.stopPropagation(), r2({ type: 0 });
        break;
    }
  }), S2 = o$5((i2) => {
    switch (i2.key) {
      case o$3.Space:
        i2.preventDefault();
        break;
    }
  }), u2 = o$5((i2) => {
    var g2;
    s$6(i2.currentTarget) || a3 || (s2 ? (r2({ type: 0 }), (g2 = o4.buttonElement) == null || g2.focus()) : r2({ type: 0 }));
  }), { isFocusVisible: m2, focusProps: d2 } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus: c2 }), { isHovered: C2, hoverProps: h2 } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: a3 }), { pressed: $2, pressProps: U2 } = w$6({ disabled: a3 }), J2 = n$5({ open: o4.disclosureState === 0, hover: C2, active: $2, disabled: a3, focus: m2, autofocus: c2 }), G2 = e$1(e2, o4.buttonElement), X2 = s2 ? V$4({ ref: T3, type: G2, disabled: a3 || void 0, autoFocus: c2, onKeyDown: D2, onClick: u2 }, d2, h2, U2) : V$4({ ref: T3, id: p2, type: G2, "aria-expanded": o4.disclosureState === 0, "aria-controls": o4.panelElement ? o4.panelId : void 0, disabled: a3 || void 0, autoFocus: c2, onKeyDown: D2, onKeyUp: S2, onClick: u2 }, d2, h2, U2);
  return K()({ ourProps: X2, theirProps: n2, slot: J2, defaultTag: ge, name: "Disclosure.Button" });
}
let be = "div", Ce$1 = A$2.RenderStrategy | A$2.Static;
function Re(e2, t2) {
  let l2 = reactExports.useId(), { id: p2 = `headlessui-disclosure-panel-${l2}`, transition: a3 = false, ...c2 } = e2, [n2, o4] = M("Disclosure.Panel"), { close: r2 } = V$1("Disclosure.Panel"), [f2, s2] = reactExports.useState(null), E2 = y$2(t2, o$5((C2) => {
    a$2(() => o4({ type: 5, element: C2 }));
  }), s2);
  reactExports.useEffect(() => (o4({ type: 3, panelId: p2 }), () => {
    o4({ type: 3, panelId: null });
  }), [p2, o4]);
  let T3 = u$1(), [D2, S2] = N(a3, f2, T3 !== null ? (T3 & i$3.Open) === i$3.Open : n2.disclosureState === 0), u2 = n$5({ open: n2.disclosureState === 0, close: r2 }), m2 = { ref: E2, id: p2, ...x$3(S2) }, d2 = K();
  return React.createElement(s$3, null, React.createElement(H.Provider, { value: n2.panelId }, d2({ ourProps: m2, theirProps: c2, slot: u2, defaultTag: be, features: Ce$1, visible: D2, name: "Disclosure.Panel" })));
}
let Ie$2 = Y(Se$2), xe = Y(Ae), Le$1 = Y(Re), Xe = Object.assign(Ie$2, { Button: xe, Panel: Le$1 });
var Ie$1 = ((e2) => (e2[e2.RegisterOption = 0] = "RegisterOption", e2[e2.UnregisterOption = 1] = "UnregisterOption", e2))(Ie$1 || {});
let Fe$1 = { [0](o4, t2) {
  let e2 = [...o4.options, { id: t2.id, element: t2.element, propsRef: t2.propsRef }];
  return { ...o4, options: G$1(e2, (n2) => n2.element.current) };
}, [1](o4, t2) {
  let e2 = o4.options.slice(), n2 = o4.options.findIndex((P2) => P2.id === t2.id);
  return n2 === -1 ? o4 : (e2.splice(n2, 1), { ...o4, options: e2 });
} }, X$1 = reactExports.createContext(null);
X$1.displayName = "RadioGroupDataContext";
function z$1(o4) {
  let t2 = reactExports.useContext(X$1);
  if (t2 === null) {
    let e2 = new Error(`<${o4} /> is missing a parent <RadioGroup /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(e2, z$1), e2;
  }
  return t2;
}
let q2 = reactExports.createContext(null);
q2.displayName = "RadioGroupActionsContext";
function Q$1(o4) {
  let t2 = reactExports.useContext(q2);
  if (t2 === null) {
    let e2 = new Error(`<${o4} /> is missing a parent <RadioGroup /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(e2, Q$1), e2;
  }
  return t2;
}
function Ue$1(o4, t2) {
  return u$9(t2.type, Fe$1, o4, t2);
}
let we$1 = "div";
function Se$1(o4, t2) {
  let e2 = reactExports.useId(), n2 = a$e(), { id: P2 = `headlessui-radiogroup-${e2}`, value: R2, form: D2, name: i2, onChange: c2, by: d2, disabled: a3 = n2 || false, defaultValue: h2, tabIndex: f2 = 0, ...L2 } = o4, T3 = u$5(d2), [v$12, y2] = reactExports.useReducer(Ue$1, { options: [] }), p2 = v$12.options, [k2, G2] = V$3(), [I2, F2] = H$2(), E2 = reactExports.useRef(null), m2 = y$2(E2, t2), b2 = l$6(h2), [s2, x] = b$2(R2, c2, b2), g2 = reactExports.useMemo(() => p2.find((r2) => !r2.propsRef.current.disabled), [p2]), O2 = reactExports.useMemo(() => p2.some((r2) => T3(r2.propsRef.current.value, s2)), [p2, s2]), l2 = o$5((r2) => {
    var U2;
    if (a3 || T3(r2, s2)) return false;
    let S2 = (U2 = p2.find((u2) => T3(u2.propsRef.current.value, r2))) == null ? void 0 : U2.propsRef.current;
    return S2 != null && S2.disabled ? false : (x == null || x(r2), true);
  }), ce2 = o$5((r2) => {
    if (!E2.current) return;
    let U2 = p2.filter((u2) => u2.propsRef.current.disabled === false).map((u2) => u2.element.current);
    switch (r2.key) {
      case o$3.Enter:
        g$3(r2.currentTarget);
        break;
      case o$3.ArrowLeft:
      case o$3.ArrowUp:
        if (r2.preventDefault(), r2.stopPropagation(), v(U2, T$1.Previous | T$1.WrapAround) === A$1.Success) {
          let A2 = p2.find((N2) => d$2(N2.element.current));
          A2 && l2(A2.propsRef.current.value);
        }
        break;
      case o$3.ArrowRight:
      case o$3.ArrowDown:
        if (r2.preventDefault(), r2.stopPropagation(), v(U2, T$1.Next | T$1.WrapAround) === A$1.Success) {
          let A2 = p2.find((N2) => d$2(N2.element.current));
          A2 && l2(A2.propsRef.current.value);
        }
        break;
      case o$3.Space:
        {
          r2.preventDefault(), r2.stopPropagation();
          let u2 = p2.find((A2) => d$2(A2.element.current));
          u2 && l2(u2.propsRef.current.value);
        }
        break;
    }
  }), Y2 = o$5((r2) => (y2({ type: 0, ...r2 }), () => y2({ type: 1, id: r2.id }))), fe2 = reactExports.useMemo(() => ({ value: s2, firstOption: g2, containsCheckedOption: O2, disabled: a3, compare: T3, tabIndex: f2, ...v$12 }), [s2, g2, O2, a3, T3, f2, v$12]), Te2 = reactExports.useMemo(() => ({ registerOption: Y2, change: l2 }), [Y2, l2]), me2 = { ref: m2, id: P2, role: "radiogroup", "aria-labelledby": k2, "aria-describedby": I2, onKeyDown: ce2 }, Re2 = n$5({ value: s2 }), ye2 = reactExports.useCallback(() => {
    if (b2 !== void 0) return l2(b2);
  }, [l2, b2]), be2 = K();
  return React.createElement(F2, { name: "RadioGroup.Description" }, React.createElement(G2, { name: "RadioGroup.Label" }, React.createElement(q2.Provider, { value: Te2 }, React.createElement(X$1.Provider, { value: fe2 }, i2 != null && React.createElement(j$6, { disabled: a3, data: { [i2]: s2 || "on" }, overrides: { type: "radio", checked: s2 != null }, form: D2, onReset: ye2 }), be2({ ourProps: me2, theirProps: L2, slot: Re2, defaultTag: we$1, name: "RadioGroup" })))));
}
let Me$1 = "div";
function He$1(o4, t2) {
  var g2;
  let e2 = z$1("RadioGroup.Option"), n2 = Q$1("RadioGroup.Option"), P2 = reactExports.useId(), { id: R2 = `headlessui-radiogroup-option-${P2}`, value: D2, disabled: i2 = e2.disabled || false, autoFocus: c2 = false, ...d2 } = o4, a3 = reactExports.useRef(null), h2 = y$2(a3, t2), [f2, L2] = V$3(), [T3, v5] = H$2(), y2 = s$9({ value: D2, disabled: i2 });
  n$6(() => n2.registerOption({ id: R2, element: a3, propsRef: y2 }), [R2, n2, a3, y2]);
  let p2 = o$5((O2) => {
    var l2;
    if (s$6(O2.currentTarget)) return O2.preventDefault();
    n2.change(D2) && ((l2 = a3.current) == null || l2.focus());
  }), k2 = ((g2 = e2.firstOption) == null ? void 0 : g2.id) === R2, { isFocusVisible: G2, focusProps: I2 } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus: c2 }), { isHovered: F2, hoverProps: E2 } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: i2 }), m2 = e2.compare(e2.value, D2), b2 = V$4({ ref: h2, id: R2, role: "radio", "aria-checked": m2 ? "true" : "false", "aria-labelledby": f2, "aria-describedby": T3, "aria-disabled": i2 ? true : void 0, tabIndex: (() => i2 ? -1 : m2 || !e2.containsCheckedOption && k2 ? e2.tabIndex : -1)(), onClick: i2 ? void 0 : p2, autoFocus: c2 }, I2, E2), s2 = n$5({ checked: m2, disabled: i2, active: G2, hover: F2, focus: G2, autofocus: c2 }), x = K();
  return React.createElement(v5, { name: "RadioGroup.Description" }, React.createElement(L2, { name: "RadioGroup.Label" }, x({ ourProps: b2, theirProps: d2, slot: s2, defaultTag: Me$1, name: "RadioGroup.Option" })));
}
let Ne$1 = "span";
function We$1(o4, t2) {
  var g2;
  let e2 = z$1("Radio"), n2 = Q$1("Radio"), P2 = reactExports.useId(), R2 = u$8(), D2 = a$e(), { id: i2 = R2 || `headlessui-radio-${P2}`, value: c2, disabled: d2 = e2.disabled || D2 || false, autoFocus: a3 = false, ...h2 } = o4, f2 = reactExports.useRef(null), L2 = y$2(f2, t2), T3 = N$1(), v5 = w$5(), y2 = s$9({ value: c2, disabled: d2 });
  n$6(() => n2.registerOption({ id: i2, element: f2, propsRef: y2 }), [i2, n2, f2, y2]);
  let p2 = o$5((O2) => {
    var l2;
    if (s$6(O2.currentTarget)) return O2.preventDefault();
    n2.change(c2) && ((l2 = f2.current) == null || l2.focus());
  }), { isFocusVisible: k2, focusProps: G2 } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus: a3 }), { isHovered: I2, hoverProps: F2 } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: d2 }), E2 = ((g2 = e2.firstOption) == null ? void 0 : g2.id) === i2, m2 = e2.compare(e2.value, c2), b2 = V$4({ ref: L2, id: i2, role: "radio", "aria-checked": m2 ? "true" : "false", "aria-labelledby": T3, "aria-describedby": v5, "aria-disabled": d2 ? true : void 0, tabIndex: (() => d2 ? -1 : m2 || !e2.containsCheckedOption && E2 ? e2.tabIndex : -1)(), autoFocus: a3, onClick: d2 ? void 0 : p2 }, G2, F2), s2 = n$5({ checked: m2, disabled: d2, hover: I2, focus: k2, autofocus: a3 });
  return K()({ ourProps: b2, theirProps: h2, slot: s2, defaultTag: Ne$1, name: "Radio" });
}
let Be$1 = Y(Se$1), Ve = Y(He$1), Ke$1 = Y(We$1), $e = Z, je$1 = M$3, yt = Object.assign(Be$1, { Option: Ve, Radio: Ke$1, Label: $e, Description: je$1 });
function b({ onFocus: n2 }) {
  let [r2, o4] = reactExports.useState(true), u2 = f$1();
  return r2 ? React.createElement(f$8, { as: "button", type: "button", features: s$7.Focusable, onFocus: (a3) => {
    a3.preventDefault();
    let e2, i2 = 50;
    function t2() {
      if (i2-- <= 0) {
        e2 && cancelAnimationFrame(e2);
        return;
      }
      if (n2()) {
        if (cancelAnimationFrame(e2), !u2.current) return;
        o4(false);
        return;
      }
      e2 = requestAnimationFrame(t2);
    }
    e2 = requestAnimationFrame(t2);
  } }) : null;
}
const s$1 = reactExports.createContext(null);
function a$1() {
  return { groups: /* @__PURE__ */ new Map(), get(o4, e2) {
    var i2;
    let t2 = this.groups.get(o4);
    t2 || (t2 = /* @__PURE__ */ new Map(), this.groups.set(o4, t2));
    let n2 = (i2 = t2.get(e2)) != null ? i2 : 0;
    t2.set(e2, n2 + 1);
    let r2 = Array.from(t2.keys()).indexOf(e2);
    function u2() {
      let c2 = t2.get(e2);
      c2 > 1 ? t2.set(e2, c2 - 1) : t2.delete(e2);
    }
    return [r2, u2];
  } };
}
function f({ children: o4 }) {
  let e2 = reactExports.useRef(a$1());
  return reactExports.createElement(s$1.Provider, { value: e2 }, o4);
}
function C(o4) {
  let e2 = reactExports.useContext(s$1);
  if (!e2) throw new Error("You must wrap your component in a <StableCollection>");
  let t2 = reactExports.useId(), [n2, r2] = e2.current.get(o4, t2);
  return reactExports.useEffect(() => r2, []), n2;
}
var Le = ((t2) => (t2[t2.Forwards = 0] = "Forwards", t2[t2.Backwards = 1] = "Backwards", t2))(Le || {}), _e = ((l2) => (l2[l2.Less = -1] = "Less", l2[l2.Equal = 0] = "Equal", l2[l2.Greater = 1] = "Greater", l2))(_e || {}), Se = ((n2) => (n2[n2.SetSelectedIndex = 0] = "SetSelectedIndex", n2[n2.RegisterTab = 1] = "RegisterTab", n2[n2.UnregisterTab = 2] = "UnregisterTab", n2[n2.RegisterPanel = 3] = "RegisterPanel", n2[n2.UnregisterPanel = 4] = "UnregisterPanel", n2))(Se || {});
let De = { [0](e2, r2) {
  var d2;
  let t2 = G$1(e2.tabs, (u2) => u2.current), l2 = G$1(e2.panels, (u2) => u2.current), a3 = t2.filter((u2) => {
    var T3;
    return !((T3 = u2.current) != null && T3.hasAttribute("disabled"));
  }), n2 = { ...e2, tabs: t2, panels: l2 };
  if (r2.index < 0 || r2.index > t2.length - 1) {
    let u2 = u$9(Math.sign(r2.index - e2.selectedIndex), { [-1]: () => 1, [0]: () => u$9(Math.sign(r2.index), { [-1]: () => 0, [0]: () => 0, [1]: () => 1 }), [1]: () => 0 });
    if (a3.length === 0) return n2;
    let T3 = u$9(u2, { [0]: () => t2.indexOf(a3[0]), [1]: () => t2.indexOf(a3[a3.length - 1]) });
    return { ...n2, selectedIndex: T3 === -1 ? e2.selectedIndex : T3 };
  }
  let s2 = t2.slice(0, r2.index), f2 = [...t2.slice(r2.index), ...s2].find((u2) => a3.includes(u2));
  if (!f2) return n2;
  let b2 = (d2 = t2.indexOf(f2)) != null ? d2 : e2.selectedIndex;
  return b2 === -1 && (b2 = e2.selectedIndex), { ...n2, selectedIndex: b2 };
}, [1](e2, r2) {
  if (e2.tabs.includes(r2.tab)) return e2;
  let t2 = e2.tabs[e2.selectedIndex], l2 = G$1([...e2.tabs, r2.tab], (n2) => n2.current), a3 = e2.selectedIndex;
  return e2.info.current.isControlled || (a3 = l2.indexOf(t2), a3 === -1 && (a3 = e2.selectedIndex)), { ...e2, tabs: l2, selectedIndex: a3 };
}, [2](e2, r2) {
  return { ...e2, tabs: e2.tabs.filter((t2) => t2 !== r2.tab) };
}, [3](e2, r2) {
  return e2.panels.includes(r2.panel) ? e2 : { ...e2, panels: G$1([...e2.panels, r2.panel], (t2) => t2.current) };
}, [4](e2, r2) {
  return { ...e2, panels: e2.panels.filter((t2) => t2 !== r2.panel) };
} }, z = reactExports.createContext(null);
z.displayName = "TabsDataContext";
function h(e2) {
  let r2 = reactExports.useContext(z);
  if (r2 === null) {
    let t2 = new Error(`<${e2} /> is missing a parent <Tab.Group /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(t2, h), t2;
  }
  return r2;
}
let V = reactExports.createContext(null);
V.displayName = "TabsActionsContext";
function Q(e2) {
  let r2 = reactExports.useContext(V);
  if (r2 === null) {
    let t2 = new Error(`<${e2} /> is missing a parent <Tab.Group /> component.`);
    throw Error.captureStackTrace && Error.captureStackTrace(t2, Q), t2;
  }
  return r2;
}
function Fe(e2, r2) {
  return u$9(r2.type, De, e2, r2);
}
let Ie = "div";
function he(e2, r2) {
  let { defaultIndex: t2 = 0, vertical: l2 = false, manual: a3 = false, onChange: n2, selectedIndex: s2 = null, ...g2 } = e2;
  const f$12 = l2 ? "vertical" : "horizontal", b$12 = a3 ? "manual" : "auto";
  let d2 = s2 !== null, u2 = s$9({ isControlled: d2 }), T3 = y$2(r2), [p2, c2] = reactExports.useReducer(Fe, { info: u2, selectedIndex: s2 != null ? s2 : t2, tabs: [], panels: [] }), v5 = n$5({ selectedIndex: p2.selectedIndex }), m2 = s$9(n2 || (() => {
  })), C2 = s$9(p2.tabs), D2 = reactExports.useMemo(() => ({ orientation: f$12, activation: b$12, ...p2 }), [f$12, b$12, p2]), P2 = o$5((i2) => (c2({ type: 1, tab: i2 }), () => c2({ type: 2, tab: i2 }))), R2 = o$5((i2) => (c2({ type: 3, panel: i2 }), () => c2({ type: 4, panel: i2 }))), A2 = o$5((i2) => {
    L2.current !== i2 && m2.current(i2), d2 || c2({ type: 0, index: i2 });
  }), L2 = s$9(d2 ? e2.selectedIndex : p2.selectedIndex), _2 = reactExports.useMemo(() => ({ registerTab: P2, registerPanel: R2, change: A2 }), []);
  n$6(() => {
    c2({ type: 0, index: s2 != null ? s2 : t2 });
  }, [s2]), n$6(() => {
    if (L2.current === void 0 || p2.tabs.length <= 0) return;
    let i2 = G$1(p2.tabs, (S2) => S2.current);
    i2.some((S2, $2) => p2.tabs[$2] !== S2) && A2(i2.indexOf(p2.tabs[L2.current]));
  });
  let J2 = { ref: T3 }, X2 = K();
  return React.createElement(f, null, React.createElement(V.Provider, { value: _2 }, React.createElement(z.Provider, { value: D2 }, D2.tabs.length <= 0 && React.createElement(b, { onFocus: () => {
    var i2, M2;
    for (let S2 of C2.current) if (((i2 = S2.current) == null ? void 0 : i2.tabIndex) === 0) return (M2 = S2.current) == null || M2.focus(), true;
    return false;
  } }), X2({ ourProps: J2, theirProps: g2, slot: v5, defaultTag: Ie, name: "Tabs" }))));
}
let ve = "div";
function Ce(e2, r2) {
  let { orientation: t2, selectedIndex: l2 } = h("Tab.List"), a3 = y$2(r2), n2 = n$5({ selectedIndex: l2 }), s2 = e2, g2 = { ref: a3, role: "tablist", "aria-orientation": t2 };
  return K()({ ourProps: g2, theirProps: s2, slot: n2, defaultTag: ve, name: "Tabs.List" });
}
let Me = "button";
function Ge(e2, r2) {
  var Y2, Z2;
  let t2 = reactExports.useId(), { id: l2 = `headlessui-tabs-tab-${t2}`, disabled: a3 = false, autoFocus: n2 = false, ...s2 } = e2, { orientation: g2, activation: f2, selectedIndex: b2, tabs: d2, panels: u2 } = h("Tab"), T3 = Q("Tab"), p2 = h("Tab"), [c2, v$12] = reactExports.useState(null), m2 = reactExports.useRef(null), C$12 = y$2(m2, r2, v$12);
  n$6(() => T3.registerTab(m2), [T3, m2]);
  let D2 = C("tabs"), P2 = d2.indexOf(m2);
  P2 === -1 && (P2 = D2);
  let R2 = P2 === b2, A2 = o$5((o4) => {
    let E2 = o4();
    if (E2 === A$1.Success && f2 === "auto") {
      let ee2 = e$5(m2.current), B = p2.tabs.findIndex((ce2) => ce2.current === ee2);
      B !== -1 && T3.change(B);
    }
    return E2;
  }), L2 = o$5((o4) => {
    let E2 = d2.map((B) => B.current).filter(Boolean);
    if (o4.key === o$3.Space || o4.key === o$3.Enter) {
      o4.preventDefault(), o4.stopPropagation(), T3.change(P2);
      return;
    }
    switch (o4.key) {
      case o$3.Home:
      case o$3.PageUp:
        return o4.preventDefault(), o4.stopPropagation(), A2(() => v(E2, T$1.First));
      case o$3.End:
      case o$3.PageDown:
        return o4.preventDefault(), o4.stopPropagation(), A2(() => v(E2, T$1.Last));
    }
    if (A2(() => u$9(g2, { vertical() {
      return o4.key === o$3.ArrowUp ? v(E2, T$1.Previous | T$1.WrapAround) : o4.key === o$3.ArrowDown ? v(E2, T$1.Next | T$1.WrapAround) : A$1.Error;
    }, horizontal() {
      return o4.key === o$3.ArrowLeft ? v(E2, T$1.Previous | T$1.WrapAround) : o4.key === o$3.ArrowRight ? v(E2, T$1.Next | T$1.WrapAround) : A$1.Error;
    } })) === A$1.Success) return o4.preventDefault();
  }), _2 = reactExports.useRef(false), J2 = o$5(() => {
    var o4;
    _2.current || (_2.current = true, (o4 = m2.current) == null || o4.focus({ preventScroll: true }), T3.change(P2), t$5(() => {
      _2.current = false;
    }));
  }), X2 = o$5((o4) => {
    o4.preventDefault();
  }), { isFocusVisible: i2, focusProps: M2 } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus: n2 }), { isHovered: S2, hoverProps: $2 } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: a3 }), { pressed: pe, pressProps: ue3 } = w$6({ disabled: a3 }), Te2 = n$5({ selected: R2, hover: S2, active: pe, focus: i2, autofocus: n2, disabled: a3 }), de2 = V$4({ ref: C$12, onKeyDown: L2, onMouseDown: X2, onClick: J2, id: l2, role: "tab", type: e$1(e2, c2), "aria-controls": (Z2 = (Y2 = u2[P2]) == null ? void 0 : Y2.current) == null ? void 0 : Z2.id, "aria-selected": R2, tabIndex: R2 ? 0 : -1, disabled: a3 || void 0, autoFocus: n2 }, M2, $2, ue3);
  return K()({ ourProps: de2, theirProps: s2, slot: Te2, defaultTag: Me, name: "Tabs.Tab" });
}
let Ue = "div";
function He(e2, r2) {
  let { selectedIndex: t2 } = h("Tab.Panels"), l2 = y$2(r2), a3 = n$5({ selectedIndex: t2 }), n2 = e2, s2 = { ref: l2 };
  return K()({ ourProps: s2, theirProps: n2, slot: a3, defaultTag: Ue, name: "Tabs.Panels" });
}
let we = "div", Oe = A$2.RenderStrategy | A$2.Static;
function Ne(e2, r2) {
  var R2, A2, L2, _2;
  let t2 = reactExports.useId(), { id: l2 = `headlessui-tabs-panel-${t2}`, tabIndex: a3 = 0, ...n2 } = e2, { selectedIndex: s2, tabs: g2, panels: f2 } = h("Tab.Panel"), b2 = Q("Tab.Panel"), d2 = reactExports.useRef(null), u2 = y$2(d2, r2);
  n$6(() => b2.registerPanel(d2), [b2, d2]);
  let T3 = C("panels"), p2 = f2.indexOf(d2);
  p2 === -1 && (p2 = T3);
  let c2 = p2 === s2, { isFocusVisible: v5, focusProps: m2 } = $f7dceffc5ad7768b$export$4e328f61c538687f(), C$12 = n$5({ selected: c2, focus: v5 }), D2 = V$4({ ref: u2, id: l2, role: "tabpanel", "aria-labelledby": (A2 = (R2 = g2[p2]) == null ? void 0 : R2.current) == null ? void 0 : A2.id, tabIndex: c2 ? a3 : -1 }, m2), P2 = K();
  return !c2 && ((L2 = n2.unmount) == null || L2) && !((_2 = n2.static) != null && _2) ? React.createElement(f$8, { "aria-hidden": "true", ...D2 }) : P2({ ourProps: D2, theirProps: n2, slot: C$12, defaultTag: we, features: Oe, visible: c2, name: "Tabs.Panel" });
}
let ke = Y(Ge), Be = Y(he), We = Y(Ce), je = Y(He), Ke = Y(Ne), dt = Object.assign(ke, { Group: Be, List: We, Panels: je, Panel: Ke });
function Dialog({
  queryParam,
  title,
  children,
  bottomSection
}) {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [open, setOpen] = reactExports.useState(searchParams.get(queryParam) || "false");
  const closeDialog = () => {
    setOpen("false");
    navigate(`?${queryParam}=false`);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    ht,
    {
      open: open === "true",
      onClose: closeDialog,
      className: "relative z-[200]",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Lt,
          {
            transition: true,
            className: "fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity duration-500 ease-in-out data-[closed]:opacity-0"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed inset-0 overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ze,
          {
            transition: true,
            className: "pointer-events-auto w-screen max-w-md transform transition duration-500 ease-in-out data-[closed]:translate-x-full sm:duration-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-full flex-col overflow-y-scroll bg-white shadow-xl", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto px-4 py-6 sm:px-6", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Qe, { className: "text-lg font-medium text-gray-900", children: title }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-3 flex h-7 items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "button",
                    {
                      type: "button",
                      onClick: () => {
                        setOpen("false");
                        navigate(`?cartOpen=false`);
                      },
                      className: "relative -m-2 p-2 text-gray-400 hover:text-gray-500",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute -inset-0.5" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "sr-only", children: "Close panel" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$8, { "aria-hidden": "true", className: "h-6 w-6" })
                      ]
                    }
                  ) })
                ] }),
                children
              ] }),
              typeof bottomSection === "function" ? bottomSection({ closeDialog }) : bottomSection
            ] })
          }
        ) }) }) })
      ]
    }
  );
}
function Layout({
  cart,
  children = null,
  footer,
  header,
  isLoggedIn
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col min-h-screen px-4 sm:px-6 lg:px-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CartAside, { cart }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(MobileMenuAside, { menu: header == null ? void 0 : header.menu, shop: header == null ? void 0 : header.shop }),
    header && /* @__PURE__ */ jsxRuntimeExports.jsx(Header, { header, cart, isLoggedIn }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("main", { className: "flex-grow", children }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: footer, children: (footer2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      NewFooter,
      {
        shopMenu: header == null ? void 0 : header.menu,
        legalMenu: footer2 == null ? void 0 : footer2.menu,
        shop: header == null ? void 0 : header.shop
      }
    ) }) })
  ] });
}
function CartItem({ line }) {
  const lineItemUrl = useVariantUrl(
    line.merchandise.product.handle,
    line.merchandise.selectedOptions
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex py-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 w-24 flex-shrink-0 overflow-hidden rounded-md border border-gray-200", children: line.merchandise.image ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      Image,
      {
        alt: line.merchandise.title,
        data: line.merchandise.image,
        loading: "lazy",
        aspectRatio: "1/1",
        height: 100,
        width: 100,
        className: "h-full w-full object-cover object-center"
      }
    ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        src: placeholderImg,
        alt: line.merchandise.title,
        className: "h-full w-full object-cover object-center opacity-50 bg-gray-50 flex items-center justify-center p-2"
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ml-4 flex flex-1 flex-col", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between text-base font-medium text-gray-900", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: lineItemUrl, children: line.merchandise.title }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "ml-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CartLinePrice, { line, as: "span" }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1 flex text-xs text-gray-500", children: line.merchandise.selectedOptions.map(
          (opt, ind) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "p",
            {
              className: ind > 0 ? "text-xs ml-2 border-l border-gray-200 pl-2" : "text-xs",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "", children: [
                  opt.name,
                  ": "
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold", children: opt.value })
              ]
            },
            `${opt.value}-${ind}`
          )
        ) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-1 items-end justify-between text-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CartLineQuantity, { line }) })
    ] })
  ] }, line.id);
}
function CartAside({ cart }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Dialog,
    {
      queryParam: "cartOpen",
      title: "Shopping Cart",
      bottomSection: (props) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: cart, children: (cart2) => {
          var _a2, _b2;
          if (!cart2 || (cart2 == null ? void 0 : cart2.lines.nodes.length) === 0) return null;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "border-t border-gray-200 px-4 py-6 sm:px-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between text-base font-medium text-gray-900", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Subtotal" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: ((_a2 = cart2 == null ? void 0 : cart2.cost) == null ? void 0 : _a2.subtotalAmount) ? /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: (_b2 = cart2 == null ? void 0 : cart2.cost) == null ? void 0 : _b2.subtotalAmount }) : "-" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-0.5 text-sm text-gray-500", children: "Shipping and taxes calculated at checkout." }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Link,
              {
                prefetch: "intent",
                to: "/cart",
                onClick: () => {
                  props.closeDialog();
                },
                className: "flex items-center justify-center rounded-md border border-transparent bg-blue-600 px-6 py-3 text-base font-medium text-white shadow-sm hover:bg-blue-700",
                children: "Checkout"
              }
            ) })
          ] });
        } }) });
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flow-root", children: /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Loading cart ..." }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: cart, children: (cart2) => {
        if (!cart2 || (cart2 == null ? void 0 : cart2.lines.nodes.length) === 0)
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyCart, {});
        return /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "-my-6 divide-y divide-gray-200", children: cart2 == null ? void 0 : cart2.lines.nodes.map((line) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(CartItem, { line }, line.id);
        }) });
      } }) }) }) })
    }
  );
}
function MobileMenuAside({
  menu,
  shop
}) {
  var _a2;
  return menu && ((_a2 = shop == null ? void 0 : shop.primaryDomain) == null ? void 0 : _a2.url) && /* @__PURE__ */ jsxRuntimeExports.jsx(Aside, { id: "mobile-menu-aside", heading: "MENU", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    HeaderMenu,
    {
      menu,
      viewport: "mobile",
      primaryDomainUrl: shop.primaryDomain.url
    }
  ) });
}
function PageLoader() {
  const navigation2 = useNavigation();
  const fetchers = useFetchers();
  const [active, setActive] = reactExports.useState(false);
  const [progress, setProgress] = reactExports.useState(0);
  const isLoading = reactExports.useMemo(() => {
    const isNavigating = navigation2.state !== "idle";
    const isFetching = fetchers.some((f2) => f2.state !== "idle");
    return isNavigating || isFetching;
  }, [navigation2.state, fetchers]);
  reactExports.useEffect(() => {
    let interval;
    if (isLoading) {
      setActive(true);
      if (progress < 10) setProgress(10);
      interval = setInterval(() => {
        setProgress((prev) => {
          if (prev >= 90) return prev;
          return prev + Math.random() * 5;
        });
      }, 200);
    } else {
      setProgress(100);
      const timeout = setTimeout(() => {
        setActive(false);
        setProgress(0);
      }, 300);
      return () => {
        clearTimeout(timeout);
        if (interval) clearInterval(interval);
      };
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isLoading]);
  if (!active && !isLoading) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `fixed top-0 left-0 right-0 z-[100] h-1 bg-transparent transition-opacity duration-300 ${active ? "opacity-100" : "opacity-0"}`,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "h-full bg-blue-600 transition-all duration-300 ease-out shadow-[0_0_10px_rgba(37,99,235,0.5)]",
            style: { width: `${progress}%` }
          }
        )
      }
    ),
    progress > 30 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed inset-0 bg-white/40 backdrop-blur-[4px] pointer-events-none z-[90] flex items-center justify-center animate-fade-in transition-all duration-500", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-6 scale-up", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-16 h-16 border-4 border-blue-600/10 border-t-blue-600 rounded-full animate-spin shadow-[0_0_20px_rgba(37,99,235,0.2)]" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 w-16 h-16 border-4 border-transparent border-b-blue-400/30 rounded-full animate-spin-slow" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs font-bold text-blue-600 uppercase tracking-[0.3em] animate-pulse", children: "Durafoam" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-[10px] font-medium text-slate-400 uppercase tracking-widest", children: "Loading..." })
      ] })
    ] }) })
  ] });
}
const shouldRevalidate$1 = ({
  formMethod,
  currentUrl,
  nextUrl
}) => {
  if (formMethod && formMethod !== "GET") {
    return true;
  }
  if (currentUrl.toString() === nextUrl.toString()) {
    return true;
  }
  return false;
};
function links() {
  return [
    { rel: "stylesheet", href: resetStyles },
    { rel: "stylesheet", href: appStyles },
    { rel: "stylesheet", href: tailwindStyles },
    {
      rel: "preconnect",
      href: "https://fonts.googleapis.com"
    },
    {
      rel: "preconnect",
      href: "https://fonts.gstatic.com",
      crossOrigin: "anonymous"
    },
    {
      rel: "stylesheet",
      href: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@400;500;600;700;800&display=swap"
    },
    {
      rel: "preconnect",
      href: "https://cdn.shopify.com"
    },
    {
      rel: "preconnect",
      href: "https://shop.app"
    },
    { rel: "icon", type: "image/png", href: favicon }
  ];
}
function useRootLoaderData() {
  const [root] = useMatches();
  return root == null ? void 0 : root.data;
}
async function loader$u({ context: context2 }) {
  const { storefront, customerAccount, cart } = context2;
  const publicStoreDomain = context2.env.PUBLIC_STORE_DOMAIN;
  const isLoggedInPromise = customerAccount.isLoggedIn();
  const cartPromise = cart.get();
  const footerPromise = storefront.query(FOOTER_QUERY, {
    cache: storefront.CacheLong(),
    variables: {
      footerMenuHandle: "footer"
      // Adjust to your footer menu handle
    }
  });
  const headerPromise = storefront.query(HEADER_QUERY, {
    cache: storefront.CacheLong(),
    variables: {
      headerMenuHandle: "main-menu"
      // Adjust to your header menu handle
    }
  });
  return defer2(
    {
      cart: cartPromise,
      footer: footerPromise,
      header: await headerPromise,
      isLoggedIn: isLoggedInPromise,
      publicStoreDomain
    },
    {
      headers: {
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
function App() {
  const nonce = er();
  const data = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("html", { lang: "en", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("head", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("meta", { charSet: "utf-8" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("meta", { name: "viewport", content: "width=device-width,initial-scale=1" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Meta, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Links, {})
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("body", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(PageLoader, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Layout, { ...data, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Outlet, {}) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ScrollRestoration, { nonce }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Scripts, { nonce })
    ] })
  ] });
}
function ErrorBoundary$1() {
  var _a2;
  const error2 = useRouteError();
  const rootData = useRootLoaderData();
  const nonce = er();
  let errorMessage = "Unknown error";
  let errorStatus = 500;
  if (isRouteErrorResponse(error2)) {
    errorMessage = ((_a2 = error2 == null ? void 0 : error2.data) == null ? void 0 : _a2.message) ?? error2.data;
    errorStatus = error2.status;
  } else if (error2 instanceof Error) {
    errorMessage = error2.message;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("html", { lang: "en", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("head", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("meta", { charSet: "utf-8" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("meta", { name: "viewport", content: "width=device-width,initial-scale=1" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Meta, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Links, {})
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("body", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(PageLoader, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Layout, { ...rootData, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "route-error", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: "Oops" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: errorStatus }),
        errorMessage && /* @__PURE__ */ jsxRuntimeExports.jsx("fieldset", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { children: errorMessage }) })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ScrollRestoration, { nonce }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Scripts, { nonce })
    ] })
  ] });
}
const MENU_FRAGMENT = `#graphql
  fragment MenuItem on MenuItem {
    id
    resourceId
    tags
    title
    type
    url
  }
  fragment ChildMenuItem on MenuItem {
    ...MenuItem
  }
  fragment ParentMenuItem on MenuItem {
    ...MenuItem
    items {
      ...ChildMenuItem
    }
  }
  fragment Menu on Menu {
    id
    items {
      ...ParentMenuItem
    }
  }
`;
const HEADER_QUERY = `#graphql
  fragment Shop on Shop {
    id
    name
    description
    primaryDomain {
      url
    }
    brand {
      logo {
        image {
          url
        }
      }
    }
  }
  query Header(
    $country: CountryCode
    $headerMenuHandle: String!
    $language: LanguageCode
  ) @inContext(language: $language, country: $country) {
    shop {
      ...Shop
    }
    menu(handle: $headerMenuHandle) {
      ...Menu
    }
  }
  ${MENU_FRAGMENT}
`;
const FOOTER_QUERY = `#graphql
  query Footer(
    $country: CountryCode
    $footerMenuHandle: String!
    $language: LanguageCode
  ) @inContext(language: $language, country: $country) {
    menu(handle: $footerMenuHandle) {
      ...Menu
    }
  }
  ${MENU_FRAGMENT}
`;
const route0 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  ErrorBoundary: ErrorBoundary$1,
  default: App,
  links,
  loader: loader$u,
  shouldRevalidate: shouldRevalidate$1,
  useRootLoaderData
}, Symbol.toStringTag, { value: "Module" }));
const meta$d = ({ data }) => {
  return [{ title: `Hydrogen | ${(data == null ? void 0 : data.article.title) ?? ""} article` }];
};
async function loader$t({ params, context: context2 }) {
  const { blogHandle, articleHandle } = params;
  if (!articleHandle || !blogHandle) {
    throw new Response("Not found", { status: 404 });
  }
  const { blog } = await context2.storefront.query(ARTICLE_QUERY, {
    variables: { blogHandle, articleHandle }
  });
  if (!(blog == null ? void 0 : blog.articleByHandle)) {
    throw new Response(null, { status: 404 });
  }
  const article = blog.articleByHandle;
  return json2({ article });
}
function Article() {
  const { article } = useLoaderData();
  const { title, image, contentHtml, author } = article;
  const publishedDate = new Intl.DateTimeFormat("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric"
  }).format(new Date(article.publishedAt));
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "article", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { children: [
      title,
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
        publishedDate,
        " · ",
        author == null ? void 0 : author.name
      ] })
    ] }),
    image && /* @__PURE__ */ jsxRuntimeExports.jsx(Image, { data: image, sizes: "90vw", loading: "eager" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        dangerouslySetInnerHTML: { __html: contentHtml },
        className: "article"
      }
    )
  ] });
}
const ARTICLE_QUERY = `#graphql
  query Article(
    $articleHandle: String!
    $blogHandle: String!
    $country: CountryCode
    $language: LanguageCode
  ) @inContext(language: $language, country: $country) {
    blog(handle: $blogHandle) {
      articleByHandle(handle: $articleHandle) {
        title
        contentHtml
        publishedAt
        author: authorV2 {
          name
        }
        image {
          id
          altText
          url
          width
          height
        }
        seo {
          description
          title
        }
      }
    }
  }
`;
const route1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Article,
  loader: loader$t,
  meta: meta$d
}, Symbol.toStringTag, { value: "Module" }));
const meta$c = ({ data }) => {
  return [{ title: `Hydrogen | ${(data == null ? void 0 : data.blog.title) ?? ""} blog` }];
};
const loader$s = async ({
  request,
  params,
  context: { storefront }
}) => {
  const paginationVariables = fn(request, {
    pageBy: 4
  });
  if (!params.blogHandle) {
    throw new Response(`blog not found`, { status: 404 });
  }
  const { blog } = await storefront.query(BLOGS_QUERY$1, {
    variables: {
      blogHandle: params.blogHandle,
      ...paginationVariables
    }
  });
  if (!(blog == null ? void 0 : blog.articles)) {
    throw new Response("Not found", { status: 404 });
  }
  return json2({ blog });
};
function Blog() {
  const { blog } = useLoaderData();
  const { articles } = blog;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "blog", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: blog.title }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "blog-grid", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ln, { connection: articles, children: ({ nodes, isLoading, PreviousLink, NextLink }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(PreviousLink, { children: isLoading ? "Loading..." : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "↑ Load previous" }) }),
        nodes.map((article, index) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ArticleItem,
            {
              article,
              loading: index < 2 ? "eager" : "lazy"
            },
            article.id
          );
        }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(NextLink, { children: isLoading ? "Loading..." : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Load more ↓" }) })
      ] });
    } }) })
  ] });
}
function ArticleItem({
  article,
  loading: loading2
}) {
  const publishedAt = new Intl.DateTimeFormat("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric"
  }).format(new Date(article.publishedAt));
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "blog-article", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Link, { to: `/blogs/${article.blog.handle}/${article.handle}`, children: [
    article.image && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "blog-article-image", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Image,
      {
        alt: article.image.altText || article.title,
        aspectRatio: "3/2",
        data: article.image,
        loading: loading2,
        sizes: "(min-width: 768px) 50vw, 100vw"
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { children: article.title }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("small", { children: publishedAt })
  ] }) }, article.id);
}
const BLOGS_QUERY$1 = `#graphql
  query Blog(
    $language: LanguageCode
    $blogHandle: String!
    $first: Int
    $last: Int
    $startCursor: String
    $endCursor: String
  ) @inContext(language: $language) {
    blog(handle: $blogHandle) {
      title
      seo {
        title
        description
      }
      articles(
        first: $first,
        last: $last,
        before: $startCursor,
        after: $endCursor
      ) {
        nodes {
          ...ArticleItem
        }
        pageInfo {
          hasPreviousPage
          hasNextPage
          hasNextPage
          endCursor
          startCursor
        }

      }
    }
  }
  fragment ArticleItem on Article {
    author: authorV2 {
      name
    }
    contentHtml
    handle
    id
    image {
      id
      altText
      url
      width
      height
    }
    publishedAt
    title
    blog {
      handle
    }
  }
`;
const route2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Blog,
  loader: loader$s,
  meta: meta$c
}, Symbol.toStringTag, { value: "Module" }));
/**
 * @license
 * Copyright 2010-2024 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const REVISION = "171";
const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
const CullFaceNone = 0;
const CullFaceBack = 1;
const CullFaceFront = 2;
const CullFaceFrontBack = 3;
const BasicShadowMap = 0;
const PCFShadowMap = 1;
const PCFSoftShadowMap = 2;
const VSMShadowMap = 3;
const FrontSide = 0;
const BackSide = 1;
const DoubleSide = 2;
const NoBlending = 0;
const NormalBlending = 1;
const AdditiveBlending = 2;
const SubtractiveBlending = 3;
const MultiplyBlending = 4;
const CustomBlending = 5;
const AddEquation = 100;
const SubtractEquation = 101;
const ReverseSubtractEquation = 102;
const MinEquation = 103;
const MaxEquation = 104;
const ZeroFactor = 200;
const OneFactor = 201;
const SrcColorFactor = 202;
const OneMinusSrcColorFactor = 203;
const SrcAlphaFactor = 204;
const OneMinusSrcAlphaFactor = 205;
const DstAlphaFactor = 206;
const OneMinusDstAlphaFactor = 207;
const DstColorFactor = 208;
const OneMinusDstColorFactor = 209;
const SrcAlphaSaturateFactor = 210;
const ConstantColorFactor = 211;
const OneMinusConstantColorFactor = 212;
const ConstantAlphaFactor = 213;
const OneMinusConstantAlphaFactor = 214;
const NeverDepth = 0;
const AlwaysDepth = 1;
const LessDepth = 2;
const LessEqualDepth = 3;
const EqualDepth = 4;
const GreaterEqualDepth = 5;
const GreaterDepth = 6;
const NotEqualDepth = 7;
const MultiplyOperation = 0;
const MixOperation = 1;
const AddOperation = 2;
const NoToneMapping = 0;
const LinearToneMapping = 1;
const ReinhardToneMapping = 2;
const CineonToneMapping = 3;
const ACESFilmicToneMapping = 4;
const CustomToneMapping = 5;
const AgXToneMapping = 6;
const NeutralToneMapping = 7;
const AttachedBindMode = "attached";
const DetachedBindMode = "detached";
const UVMapping = 300;
const CubeReflectionMapping = 301;
const CubeRefractionMapping = 302;
const EquirectangularReflectionMapping = 303;
const EquirectangularRefractionMapping = 304;
const CubeUVReflectionMapping = 306;
const RepeatWrapping = 1e3;
const ClampToEdgeWrapping = 1001;
const MirroredRepeatWrapping = 1002;
const NearestFilter = 1003;
const NearestMipmapNearestFilter = 1004;
const NearestMipMapNearestFilter = 1004;
const NearestMipmapLinearFilter = 1005;
const NearestMipMapLinearFilter = 1005;
const LinearFilter = 1006;
const LinearMipmapNearestFilter = 1007;
const LinearMipMapNearestFilter = 1007;
const LinearMipmapLinearFilter = 1008;
const LinearMipMapLinearFilter = 1008;
const UnsignedByteType = 1009;
const ByteType = 1010;
const ShortType = 1011;
const UnsignedShortType = 1012;
const IntType = 1013;
const UnsignedIntType = 1014;
const FloatType = 1015;
const HalfFloatType = 1016;
const UnsignedShort4444Type = 1017;
const UnsignedShort5551Type = 1018;
const UnsignedInt248Type = 1020;
const UnsignedInt5999Type = 35902;
const AlphaFormat = 1021;
const RGBFormat = 1022;
const RGBAFormat = 1023;
const LuminanceFormat = 1024;
const LuminanceAlphaFormat = 1025;
const DepthFormat = 1026;
const DepthStencilFormat = 1027;
const RedFormat = 1028;
const RedIntegerFormat = 1029;
const RGFormat = 1030;
const RGIntegerFormat = 1031;
const RGBIntegerFormat = 1032;
const RGBAIntegerFormat = 1033;
const RGB_S3TC_DXT1_Format = 33776;
const RGBA_S3TC_DXT1_Format = 33777;
const RGBA_S3TC_DXT3_Format = 33778;
const RGBA_S3TC_DXT5_Format = 33779;
const RGB_PVRTC_4BPPV1_Format = 35840;
const RGB_PVRTC_2BPPV1_Format = 35841;
const RGBA_PVRTC_4BPPV1_Format = 35842;
const RGBA_PVRTC_2BPPV1_Format = 35843;
const RGB_ETC1_Format = 36196;
const RGB_ETC2_Format = 37492;
const RGBA_ETC2_EAC_Format = 37496;
const RGBA_ASTC_4x4_Format = 37808;
const RGBA_ASTC_5x4_Format = 37809;
const RGBA_ASTC_5x5_Format = 37810;
const RGBA_ASTC_6x5_Format = 37811;
const RGBA_ASTC_6x6_Format = 37812;
const RGBA_ASTC_8x5_Format = 37813;
const RGBA_ASTC_8x6_Format = 37814;
const RGBA_ASTC_8x8_Format = 37815;
const RGBA_ASTC_10x5_Format = 37816;
const RGBA_ASTC_10x6_Format = 37817;
const RGBA_ASTC_10x8_Format = 37818;
const RGBA_ASTC_10x10_Format = 37819;
const RGBA_ASTC_12x10_Format = 37820;
const RGBA_ASTC_12x12_Format = 37821;
const RGBA_BPTC_Format = 36492;
const RGB_BPTC_SIGNED_Format = 36494;
const RGB_BPTC_UNSIGNED_Format = 36495;
const RED_RGTC1_Format = 36283;
const SIGNED_RED_RGTC1_Format = 36284;
const RED_GREEN_RGTC2_Format = 36285;
const SIGNED_RED_GREEN_RGTC2_Format = 36286;
const LoopOnce = 2200;
const LoopRepeat = 2201;
const LoopPingPong = 2202;
const InterpolateDiscrete = 2300;
const InterpolateLinear = 2301;
const InterpolateSmooth = 2302;
const ZeroCurvatureEnding = 2400;
const ZeroSlopeEnding = 2401;
const WrapAroundEnding = 2402;
const NormalAnimationBlendMode = 2500;
const AdditiveAnimationBlendMode = 2501;
const TrianglesDrawMode = 0;
const TriangleStripDrawMode = 1;
const TriangleFanDrawMode = 2;
const BasicDepthPacking = 3200;
const RGBADepthPacking = 3201;
const RGBDepthPacking = 3202;
const RGDepthPacking = 3203;
const TangentSpaceNormalMap = 0;
const ObjectSpaceNormalMap = 1;
const NoColorSpace = "";
const SRGBColorSpace = "srgb";
const LinearSRGBColorSpace = "srgb-linear";
const LinearTransfer = "linear";
const SRGBTransfer = "srgb";
const ZeroStencilOp = 0;
const KeepStencilOp = 7680;
const ReplaceStencilOp = 7681;
const IncrementStencilOp = 7682;
const DecrementStencilOp = 7683;
const IncrementWrapStencilOp = 34055;
const DecrementWrapStencilOp = 34056;
const InvertStencilOp = 5386;
const NeverStencilFunc = 512;
const LessStencilFunc = 513;
const EqualStencilFunc = 514;
const LessEqualStencilFunc = 515;
const GreaterStencilFunc = 516;
const NotEqualStencilFunc = 517;
const GreaterEqualStencilFunc = 518;
const AlwaysStencilFunc = 519;
const NeverCompare = 512;
const LessCompare = 513;
const EqualCompare = 514;
const LessEqualCompare = 515;
const GreaterCompare = 516;
const NotEqualCompare = 517;
const GreaterEqualCompare = 518;
const AlwaysCompare = 519;
const StaticDrawUsage = 35044;
const DynamicDrawUsage = 35048;
const StreamDrawUsage = 35040;
const StaticReadUsage = 35045;
const DynamicReadUsage = 35049;
const StreamReadUsage = 35041;
const StaticCopyUsage = 35046;
const DynamicCopyUsage = 35050;
const StreamCopyUsage = 35042;
const GLSL1 = "100";
const GLSL3 = "300 es";
const WebGLCoordinateSystem = 2e3;
const WebGPUCoordinateSystem = 2001;
let EventDispatcher$1 = class EventDispatcher {
  addEventListener(type, listener) {
    if (this._listeners === void 0) this._listeners = {};
    const listeners = this._listeners;
    if (listeners[type] === void 0) {
      listeners[type] = [];
    }
    if (listeners[type].indexOf(listener) === -1) {
      listeners[type].push(listener);
    }
  }
  hasEventListener(type, listener) {
    if (this._listeners === void 0) return false;
    const listeners = this._listeners;
    return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1;
  }
  removeEventListener(type, listener) {
    if (this._listeners === void 0) return;
    const listeners = this._listeners;
    const listenerArray = listeners[type];
    if (listenerArray !== void 0) {
      const index = listenerArray.indexOf(listener);
      if (index !== -1) {
        listenerArray.splice(index, 1);
      }
    }
  }
  dispatchEvent(event) {
    if (this._listeners === void 0) return;
    const listeners = this._listeners;
    const listenerArray = listeners[event.type];
    if (listenerArray !== void 0) {
      event.target = this;
      const array = listenerArray.slice(0);
      for (let i2 = 0, l2 = array.length; i2 < l2; i2++) {
        array[i2].call(this, event);
      }
      event.target = null;
    }
  }
};
const _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
let _seed = 1234567;
const DEG2RAD = Math.PI / 180;
const RAD2DEG = 180 / Math.PI;
function generateUUID() {
  const d0 = Math.random() * 4294967295 | 0;
  const d1 = Math.random() * 4294967295 | 0;
  const d2 = Math.random() * 4294967295 | 0;
  const d3 = Math.random() * 4294967295 | 0;
  const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255];
  return uuid.toLowerCase();
}
function clamp(value, min, max2) {
  return Math.max(min, Math.min(max2, value));
}
function euclideanModulo(n2, m2) {
  return (n2 % m2 + m2) % m2;
}
function mapLinear(x, a1, a22, b1, b2) {
  return b1 + (x - a1) * (b2 - b1) / (a22 - a1);
}
function inverseLerp(x, y2, value) {
  if (x !== y2) {
    return (value - x) / (y2 - x);
  } else {
    return 0;
  }
}
function lerp(x, y2, t2) {
  return (1 - t2) * x + t2 * y2;
}
function damp(x, y2, lambda, dt2) {
  return lerp(x, y2, 1 - Math.exp(-lambda * dt2));
}
function pingpong(x, length = 1) {
  return length - Math.abs(euclideanModulo(x, length * 2) - length);
}
function smoothstep(x, min, max2) {
  if (x <= min) return 0;
  if (x >= max2) return 1;
  x = (x - min) / (max2 - min);
  return x * x * (3 - 2 * x);
}
function smootherstep(x, min, max2) {
  if (x <= min) return 0;
  if (x >= max2) return 1;
  x = (x - min) / (max2 - min);
  return x * x * x * (x * (x * 6 - 15) + 10);
}
function randInt(low, high) {
  return low + Math.floor(Math.random() * (high - low + 1));
}
function randFloat(low, high) {
  return low + Math.random() * (high - low);
}
function randFloatSpread(range) {
  return range * (0.5 - Math.random());
}
function seededRandom(s2) {
  if (s2 !== void 0) _seed = s2;
  let t2 = _seed += 1831565813;
  t2 = Math.imul(t2 ^ t2 >>> 15, t2 | 1);
  t2 ^= t2 + Math.imul(t2 ^ t2 >>> 7, t2 | 61);
  return ((t2 ^ t2 >>> 14) >>> 0) / 4294967296;
}
function degToRad(degrees) {
  return degrees * DEG2RAD;
}
function radToDeg(radians) {
  return radians * RAD2DEG;
}
function isPowerOfTwo(value) {
  return (value & value - 1) === 0 && value !== 0;
}
function ceilPowerOfTwo(value) {
  return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
}
function floorPowerOfTwo(value) {
  return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
}
function setQuaternionFromProperEuler(q3, a3, b2, c2, order) {
  const cos = Math.cos;
  const sin = Math.sin;
  const c22 = cos(b2 / 2);
  const s2 = sin(b2 / 2);
  const c13 = cos((a3 + c2) / 2);
  const s13 = sin((a3 + c2) / 2);
  const c1_3 = cos((a3 - c2) / 2);
  const s1_3 = sin((a3 - c2) / 2);
  const c3_1 = cos((c2 - a3) / 2);
  const s3_1 = sin((c2 - a3) / 2);
  switch (order) {
    case "XYX":
      q3.set(c22 * s13, s2 * c1_3, s2 * s1_3, c22 * c13);
      break;
    case "YZY":
      q3.set(s2 * s1_3, c22 * s13, s2 * c1_3, c22 * c13);
      break;
    case "ZXZ":
      q3.set(s2 * c1_3, s2 * s1_3, c22 * s13, c22 * c13);
      break;
    case "XZX":
      q3.set(c22 * s13, s2 * s3_1, s2 * c3_1, c22 * c13);
      break;
    case "YXY":
      q3.set(s2 * c3_1, c22 * s13, s2 * s3_1, c22 * c13);
      break;
    case "ZYZ":
      q3.set(s2 * s3_1, s2 * c3_1, c22 * s13, c22 * c13);
      break;
    default:
      console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order);
  }
}
function denormalize(value, array) {
  switch (array.constructor) {
    case Float32Array:
      return value;
    case Uint32Array:
      return value / 4294967295;
    case Uint16Array:
      return value / 65535;
    case Uint8Array:
      return value / 255;
    case Int32Array:
      return Math.max(value / 2147483647, -1);
    case Int16Array:
      return Math.max(value / 32767, -1);
    case Int8Array:
      return Math.max(value / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function normalize(value, array) {
  switch (array.constructor) {
    case Float32Array:
      return value;
    case Uint32Array:
      return Math.round(value * 4294967295);
    case Uint16Array:
      return Math.round(value * 65535);
    case Uint8Array:
      return Math.round(value * 255);
    case Int32Array:
      return Math.round(value * 2147483647);
    case Int16Array:
      return Math.round(value * 32767);
    case Int8Array:
      return Math.round(value * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
const MathUtils = {
  DEG2RAD,
  RAD2DEG,
  generateUUID,
  clamp,
  euclideanModulo,
  mapLinear,
  inverseLerp,
  lerp,
  damp,
  pingpong,
  smoothstep,
  smootherstep,
  randInt,
  randFloat,
  randFloatSpread,
  seededRandom,
  degToRad,
  radToDeg,
  isPowerOfTwo,
  ceilPowerOfTwo,
  floorPowerOfTwo,
  setQuaternionFromProperEuler,
  normalize,
  denormalize
};
class Vector2 {
  constructor(x = 0, y2 = 0) {
    Vector2.prototype.isVector2 = true;
    this.x = x;
    this.y = y2;
  }
  get width() {
    return this.x;
  }
  set width(value) {
    this.x = value;
  }
  get height() {
    return this.y;
  }
  set height(value) {
    this.y = value;
  }
  set(x, y2) {
    this.x = x;
    this.y = y2;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    return this;
  }
  setX(x) {
    this.x = x;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y);
  }
  copy(v5) {
    this.x = v5.x;
    this.y = v5.y;
    return this;
  }
  add(v5) {
    this.x += v5.x;
    this.y += v5.y;
    return this;
  }
  addScalar(s2) {
    this.x += s2;
    this.y += s2;
    return this;
  }
  addVectors(a3, b2) {
    this.x = a3.x + b2.x;
    this.y = a3.y + b2.y;
    return this;
  }
  addScaledVector(v5, s2) {
    this.x += v5.x * s2;
    this.y += v5.y * s2;
    return this;
  }
  sub(v5) {
    this.x -= v5.x;
    this.y -= v5.y;
    return this;
  }
  subScalar(s2) {
    this.x -= s2;
    this.y -= s2;
    return this;
  }
  subVectors(a3, b2) {
    this.x = a3.x - b2.x;
    this.y = a3.y - b2.y;
    return this;
  }
  multiply(v5) {
    this.x *= v5.x;
    this.y *= v5.y;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    return this;
  }
  divide(v5) {
    this.x /= v5.x;
    this.y /= v5.y;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  applyMatrix3(m2) {
    const x = this.x, y2 = this.y;
    const e2 = m2.elements;
    this.x = e2[0] * x + e2[3] * y2 + e2[6];
    this.y = e2[1] * x + e2[4] * y2 + e2[7];
    return this;
  }
  min(v5) {
    this.x = Math.min(this.x, v5.x);
    this.y = Math.min(this.y, v5.y);
    return this;
  }
  max(v5) {
    this.x = Math.max(this.x, v5.x);
    this.y = Math.max(this.y, v5.y);
    return this;
  }
  clamp(min, max2) {
    this.x = clamp(this.x, min.x, max2.x);
    this.y = clamp(this.y, min.y, max2.y);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp(this.x, minVal, maxVal);
    this.y = clamp(this.y, minVal, maxVal);
    return this;
  }
  clampLength(min, max2) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max2));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    return this;
  }
  dot(v5) {
    return this.x * v5.x + this.y * v5.y;
  }
  cross(v5) {
    return this.x * v5.y - this.y * v5.x;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  angle() {
    const angle = Math.atan2(-this.y, -this.x) + Math.PI;
    return angle;
  }
  angleTo(v5) {
    const denominator = Math.sqrt(this.lengthSq() * v5.lengthSq());
    if (denominator === 0) return Math.PI / 2;
    const theta = this.dot(v5) / denominator;
    return Math.acos(clamp(theta, -1, 1));
  }
  distanceTo(v5) {
    return Math.sqrt(this.distanceToSquared(v5));
  }
  distanceToSquared(v5) {
    const dx = this.x - v5.x, dy = this.y - v5.y;
    return dx * dx + dy * dy;
  }
  manhattanDistanceTo(v5) {
    return Math.abs(this.x - v5.x) + Math.abs(this.y - v5.y);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v5, alpha) {
    this.x += (v5.x - this.x) * alpha;
    this.y += (v5.y - this.y) * alpha;
    return this;
  }
  lerpVectors(v12, v22, alpha) {
    this.x = v12.x + (v22.x - v12.x) * alpha;
    this.y = v12.y + (v22.y - v12.y) * alpha;
    return this;
  }
  equals(v5) {
    return v5.x === this.x && v5.y === this.y;
  }
  fromArray(array, offset = 0) {
    this.x = array[offset];
    this.y = array[offset + 1];
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this.x;
    array[offset + 1] = this.y;
    return array;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    return this;
  }
  rotateAround(center, angle) {
    const c2 = Math.cos(angle), s2 = Math.sin(angle);
    const x = this.x - center.x;
    const y2 = this.y - center.y;
    this.x = x * c2 - y2 * s2 + center.x;
    this.y = x * s2 + y2 * c2 + center.y;
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
  }
}
class Matrix3 {
  constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
    Matrix3.prototype.isMatrix3 = true;
    this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ];
    if (n11 !== void 0) {
      this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33);
    }
  }
  set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
    const te2 = this.elements;
    te2[0] = n11;
    te2[1] = n21;
    te2[2] = n31;
    te2[3] = n12;
    te2[4] = n22;
    te2[5] = n32;
    te2[6] = n13;
    te2[7] = n23;
    te2[8] = n33;
    return this;
  }
  identity() {
    this.set(
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    );
    return this;
  }
  copy(m2) {
    const te2 = this.elements;
    const me2 = m2.elements;
    te2[0] = me2[0];
    te2[1] = me2[1];
    te2[2] = me2[2];
    te2[3] = me2[3];
    te2[4] = me2[4];
    te2[5] = me2[5];
    te2[6] = me2[6];
    te2[7] = me2[7];
    te2[8] = me2[8];
    return this;
  }
  extractBasis(xAxis, yAxis, zAxis) {
    xAxis.setFromMatrix3Column(this, 0);
    yAxis.setFromMatrix3Column(this, 1);
    zAxis.setFromMatrix3Column(this, 2);
    return this;
  }
  setFromMatrix4(m2) {
    const me2 = m2.elements;
    this.set(
      me2[0],
      me2[4],
      me2[8],
      me2[1],
      me2[5],
      me2[9],
      me2[2],
      me2[6],
      me2[10]
    );
    return this;
  }
  multiply(m2) {
    return this.multiplyMatrices(this, m2);
  }
  premultiply(m2) {
    return this.multiplyMatrices(m2, this);
  }
  multiplyMatrices(a3, b2) {
    const ae = a3.elements;
    const be2 = b2.elements;
    const te2 = this.elements;
    const a11 = ae[0], a12 = ae[3], a13 = ae[6];
    const a21 = ae[1], a22 = ae[4], a23 = ae[7];
    const a31 = ae[2], a32 = ae[5], a33 = ae[8];
    const b11 = be2[0], b12 = be2[3], b13 = be2[6];
    const b21 = be2[1], b22 = be2[4], b23 = be2[7];
    const b31 = be2[2], b32 = be2[5], b33 = be2[8];
    te2[0] = a11 * b11 + a12 * b21 + a13 * b31;
    te2[3] = a11 * b12 + a12 * b22 + a13 * b32;
    te2[6] = a11 * b13 + a12 * b23 + a13 * b33;
    te2[1] = a21 * b11 + a22 * b21 + a23 * b31;
    te2[4] = a21 * b12 + a22 * b22 + a23 * b32;
    te2[7] = a21 * b13 + a22 * b23 + a23 * b33;
    te2[2] = a31 * b11 + a32 * b21 + a33 * b31;
    te2[5] = a31 * b12 + a32 * b22 + a33 * b32;
    te2[8] = a31 * b13 + a32 * b23 + a33 * b33;
    return this;
  }
  multiplyScalar(s2) {
    const te2 = this.elements;
    te2[0] *= s2;
    te2[3] *= s2;
    te2[6] *= s2;
    te2[1] *= s2;
    te2[4] *= s2;
    te2[7] *= s2;
    te2[2] *= s2;
    te2[5] *= s2;
    te2[8] *= s2;
    return this;
  }
  determinant() {
    const te2 = this.elements;
    const a3 = te2[0], b2 = te2[1], c2 = te2[2], d2 = te2[3], e2 = te2[4], f2 = te2[5], g2 = te2[6], h2 = te2[7], i2 = te2[8];
    return a3 * e2 * i2 - a3 * f2 * h2 - b2 * d2 * i2 + b2 * f2 * g2 + c2 * d2 * h2 - c2 * e2 * g2;
  }
  invert() {
    const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n12 = te2[3], n22 = te2[4], n32 = te2[5], n13 = te2[6], n23 = te2[7], n33 = te2[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13;
    if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const detInv = 1 / det;
    te2[0] = t11 * detInv;
    te2[1] = (n31 * n23 - n33 * n21) * detInv;
    te2[2] = (n32 * n21 - n31 * n22) * detInv;
    te2[3] = t12 * detInv;
    te2[4] = (n33 * n11 - n31 * n13) * detInv;
    te2[5] = (n31 * n12 - n32 * n11) * detInv;
    te2[6] = t13 * detInv;
    te2[7] = (n21 * n13 - n23 * n11) * detInv;
    te2[8] = (n22 * n11 - n21 * n12) * detInv;
    return this;
  }
  transpose() {
    let tmp2;
    const m2 = this.elements;
    tmp2 = m2[1];
    m2[1] = m2[3];
    m2[3] = tmp2;
    tmp2 = m2[2];
    m2[2] = m2[6];
    m2[6] = tmp2;
    tmp2 = m2[5];
    m2[5] = m2[7];
    m2[7] = tmp2;
    return this;
  }
  getNormalMatrix(matrix4) {
    return this.setFromMatrix4(matrix4).invert().transpose();
  }
  transposeIntoArray(r2) {
    const m2 = this.elements;
    r2[0] = m2[0];
    r2[1] = m2[3];
    r2[2] = m2[6];
    r2[3] = m2[1];
    r2[4] = m2[4];
    r2[5] = m2[7];
    r2[6] = m2[2];
    r2[7] = m2[5];
    r2[8] = m2[8];
    return this;
  }
  setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
    const c2 = Math.cos(rotation);
    const s2 = Math.sin(rotation);
    this.set(
      sx * c2,
      sx * s2,
      -sx * (c2 * cx + s2 * cy) + cx + tx,
      -sy * s2,
      sy * c2,
      -sy * (-s2 * cx + c2 * cy) + cy + ty,
      0,
      0,
      1
    );
    return this;
  }
  //
  scale(sx, sy) {
    this.premultiply(_m3.makeScale(sx, sy));
    return this;
  }
  rotate(theta) {
    this.premultiply(_m3.makeRotation(-theta));
    return this;
  }
  translate(tx, ty) {
    this.premultiply(_m3.makeTranslation(tx, ty));
    return this;
  }
  // for 2D Transforms
  makeTranslation(x, y2) {
    if (x.isVector2) {
      this.set(
        1,
        0,
        x.x,
        0,
        1,
        x.y,
        0,
        0,
        1
      );
    } else {
      this.set(
        1,
        0,
        x,
        0,
        1,
        y2,
        0,
        0,
        1
      );
    }
    return this;
  }
  makeRotation(theta) {
    const c2 = Math.cos(theta);
    const s2 = Math.sin(theta);
    this.set(
      c2,
      -s2,
      0,
      s2,
      c2,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeScale(x, y2) {
    this.set(
      x,
      0,
      0,
      0,
      y2,
      0,
      0,
      0,
      1
    );
    return this;
  }
  //
  equals(matrix) {
    const te2 = this.elements;
    const me2 = matrix.elements;
    for (let i2 = 0; i2 < 9; i2++) {
      if (te2[i2] !== me2[i2]) return false;
    }
    return true;
  }
  fromArray(array, offset = 0) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.elements[i2] = array[i2 + offset];
    }
    return this;
  }
  toArray(array = [], offset = 0) {
    const te2 = this.elements;
    array[offset] = te2[0];
    array[offset + 1] = te2[1];
    array[offset + 2] = te2[2];
    array[offset + 3] = te2[3];
    array[offset + 4] = te2[4];
    array[offset + 5] = te2[5];
    array[offset + 6] = te2[6];
    array[offset + 7] = te2[7];
    array[offset + 8] = te2[8];
    return array;
  }
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
}
const _m3 = /* @__PURE__ */ new Matrix3();
function arrayNeedsUint32(array) {
  for (let i2 = array.length - 1; i2 >= 0; --i2) {
    if (array[i2] >= 65535) return true;
  }
  return false;
}
const TYPED_ARRAYS = {
  Int8Array,
  Uint8Array,
  Uint8ClampedArray,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array
};
function getTypedArray(type, buffer) {
  return new TYPED_ARRAYS[type](buffer);
}
function createElementNS(name) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", name);
}
function createCanvasElement() {
  const canvas = createElementNS("canvas");
  canvas.style.display = "block";
  return canvas;
}
const _cache = {};
function warnOnce(message) {
  if (message in _cache) return;
  _cache[message] = true;
  console.warn(message);
}
function probeAsync(gl, sync, interval) {
  return new Promise(function(resolve2, reject) {
    function probe() {
      switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) {
        case gl.WAIT_FAILED:
          reject();
          break;
        case gl.TIMEOUT_EXPIRED:
          setTimeout(probe, interval);
          break;
        default:
          resolve2();
      }
    }
    setTimeout(probe, interval);
  });
}
function toNormalizedProjectionMatrix(projectionMatrix) {
  const m2 = projectionMatrix.elements;
  m2[2] = 0.5 * m2[2] + 0.5 * m2[3];
  m2[6] = 0.5 * m2[6] + 0.5 * m2[7];
  m2[10] = 0.5 * m2[10] + 0.5 * m2[11];
  m2[14] = 0.5 * m2[14] + 0.5 * m2[15];
}
function toReversedProjectionMatrix(projectionMatrix) {
  const m2 = projectionMatrix.elements;
  const isPerspectiveMatrix = m2[11] === -1;
  if (isPerspectiveMatrix) {
    m2[10] = -m2[10] - 1;
    m2[14] = -m2[14];
  } else {
    m2[10] = -m2[10];
    m2[14] = -m2[14] + 1;
  }
}
const LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
);
const XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
function createColorManagement() {
  const ColorManagement2 = {
    enabled: true,
    workingColorSpace: LinearSRGBColorSpace,
    /**
     * Implementations of supported color spaces.
     *
     * Required:
     *	- primaries: chromaticity coordinates [ rx ry gx gy bx by ]
     *	- whitePoint: reference white [ x y ]
     *	- transfer: transfer function (pre-defined)
     *	- toXYZ: Matrix3 RGB to XYZ transform
     *	- fromXYZ: Matrix3 XYZ to RGB transform
     *	- luminanceCoefficients: RGB luminance coefficients
     *
     * Optional:
     *  - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
     *  - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
     *
     * Reference:
     * - https://www.russellcottrell.com/photo/matrixCalculator.htm
     */
    spaces: {},
    convert: function(color, sourceColorSpace, targetColorSpace) {
      if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
        return color;
      }
      if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) {
        color.r = SRGBToLinear(color.r);
        color.g = SRGBToLinear(color.g);
        color.b = SRGBToLinear(color.b);
      }
      if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) {
        color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ);
        color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ);
      }
      if (this.spaces[targetColorSpace].transfer === SRGBTransfer) {
        color.r = LinearToSRGB(color.r);
        color.g = LinearToSRGB(color.g);
        color.b = LinearToSRGB(color.b);
      }
      return color;
    },
    fromWorkingColorSpace: function(color, targetColorSpace) {
      return this.convert(color, this.workingColorSpace, targetColorSpace);
    },
    toWorkingColorSpace: function(color, sourceColorSpace) {
      return this.convert(color, sourceColorSpace, this.workingColorSpace);
    },
    getPrimaries: function(colorSpace) {
      return this.spaces[colorSpace].primaries;
    },
    getTransfer: function(colorSpace) {
      if (colorSpace === NoColorSpace) return LinearTransfer;
      return this.spaces[colorSpace].transfer;
    },
    getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) {
      return target.fromArray(this.spaces[colorSpace].luminanceCoefficients);
    },
    define: function(colorSpaces) {
      Object.assign(this.spaces, colorSpaces);
    },
    // Internal APIs
    _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) {
      return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(colorSpace) {
      return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) {
      return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace;
    }
  };
  const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06];
  const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722];
  const D65 = [0.3127, 0.329];
  ColorManagement2.define({
    [LinearSRGBColorSpace]: {
      primaries: REC709_PRIMARIES,
      whitePoint: D65,
      transfer: LinearTransfer,
      toXYZ: LINEAR_REC709_TO_XYZ,
      fromXYZ: XYZ_TO_LINEAR_REC709,
      luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
      workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
      outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
    },
    [SRGBColorSpace]: {
      primaries: REC709_PRIMARIES,
      whitePoint: D65,
      transfer: SRGBTransfer,
      toXYZ: LINEAR_REC709_TO_XYZ,
      fromXYZ: XYZ_TO_LINEAR_REC709,
      luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
      outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
    }
  });
  return ColorManagement2;
}
const ColorManagement = /* @__PURE__ */ createColorManagement();
function SRGBToLinear(c2) {
  return c2 < 0.04045 ? c2 * 0.0773993808 : Math.pow(c2 * 0.9478672986 + 0.0521327014, 2.4);
}
function LinearToSRGB(c2) {
  return c2 < 31308e-7 ? c2 * 12.92 : 1.055 * Math.pow(c2, 0.41666) - 0.055;
}
let _canvas;
class ImageUtils {
  static getDataURL(image) {
    if (/^data:/i.test(image.src)) {
      return image.src;
    }
    if (typeof HTMLCanvasElement === "undefined") {
      return image.src;
    }
    let canvas;
    if (image instanceof HTMLCanvasElement) {
      canvas = image;
    } else {
      if (_canvas === void 0) _canvas = createElementNS("canvas");
      _canvas.width = image.width;
      _canvas.height = image.height;
      const context2 = _canvas.getContext("2d");
      if (image instanceof ImageData) {
        context2.putImageData(image, 0, 0);
      } else {
        context2.drawImage(image, 0, 0, image.width, image.height);
      }
      canvas = _canvas;
    }
    if (canvas.width > 2048 || canvas.height > 2048) {
      console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons", image);
      return canvas.toDataURL("image/jpeg", 0.6);
    } else {
      return canvas.toDataURL("image/png");
    }
  }
  static sRGBToLinear(image) {
    if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
      const canvas = createElementNS("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      const context2 = canvas.getContext("2d");
      context2.drawImage(image, 0, 0, image.width, image.height);
      const imageData = context2.getImageData(0, 0, image.width, image.height);
      const data = imageData.data;
      for (let i2 = 0; i2 < data.length; i2++) {
        data[i2] = SRGBToLinear(data[i2] / 255) * 255;
      }
      context2.putImageData(imageData, 0, 0);
      return canvas;
    } else if (image.data) {
      const data = image.data.slice(0);
      for (let i2 = 0; i2 < data.length; i2++) {
        if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
          data[i2] = Math.floor(SRGBToLinear(data[i2] / 255) * 255);
        } else {
          data[i2] = SRGBToLinear(data[i2]);
        }
      }
      return {
        data,
        width: image.width,
        height: image.height
      };
    } else {
      console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.");
      return image;
    }
  }
}
let _sourceId = 0;
class Source {
  constructor(data = null) {
    this.isSource = true;
    Object.defineProperty(this, "id", { value: _sourceId++ });
    this.uuid = generateUUID();
    this.data = data;
    this.dataReady = true;
    this.version = 0;
  }
  set needsUpdate(value) {
    if (value === true) this.version++;
  }
  toJSON(meta2) {
    const isRootObject = meta2 === void 0 || typeof meta2 === "string";
    if (!isRootObject && meta2.images[this.uuid] !== void 0) {
      return meta2.images[this.uuid];
    }
    const output = {
      uuid: this.uuid,
      url: ""
    };
    const data = this.data;
    if (data !== null) {
      let url;
      if (Array.isArray(data)) {
        url = [];
        for (let i2 = 0, l2 = data.length; i2 < l2; i2++) {
          if (data[i2].isDataTexture) {
            url.push(serializeImage(data[i2].image));
          } else {
            url.push(serializeImage(data[i2]));
          }
        }
      } else {
        url = serializeImage(data);
      }
      output.url = url;
    }
    if (!isRootObject) {
      meta2.images[this.uuid] = output;
    }
    return output;
  }
}
function serializeImage(image) {
  if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
    return ImageUtils.getDataURL(image);
  } else {
    if (image.data) {
      return {
        data: Array.from(image.data),
        width: image.width,
        height: image.height,
        type: image.data.constructor.name
      };
    } else {
      console.warn("THREE.Texture: Unable to serialize Texture.");
      return {};
    }
  }
}
let _textureId = 0;
class Texture extends EventDispatcher$1 {
  constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) {
    super();
    this.isTexture = true;
    Object.defineProperty(this, "id", { value: _textureId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.source = new Source(image);
    this.mipmaps = [];
    this.mapping = mapping;
    this.channel = 0;
    this.wrapS = wrapS;
    this.wrapT = wrapT;
    this.magFilter = magFilter;
    this.minFilter = minFilter;
    this.anisotropy = anisotropy;
    this.format = format;
    this.internalFormat = null;
    this.type = type;
    this.offset = new Vector2(0, 0);
    this.repeat = new Vector2(1, 1);
    this.center = new Vector2(0, 0);
    this.rotation = 0;
    this.matrixAutoUpdate = true;
    this.matrix = new Matrix3();
    this.generateMipmaps = true;
    this.premultiplyAlpha = false;
    this.flipY = true;
    this.unpackAlignment = 4;
    this.colorSpace = colorSpace;
    this.userData = {};
    this.version = 0;
    this.onUpdate = null;
    this.isRenderTargetTexture = false;
    this.pmremVersion = 0;
  }
  get image() {
    return this.source.data;
  }
  set image(value = null) {
    this.source.data = value;
  }
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.name = source.name;
    this.source = source.source;
    this.mipmaps = source.mipmaps.slice(0);
    this.mapping = source.mapping;
    this.channel = source.channel;
    this.wrapS = source.wrapS;
    this.wrapT = source.wrapT;
    this.magFilter = source.magFilter;
    this.minFilter = source.minFilter;
    this.anisotropy = source.anisotropy;
    this.format = source.format;
    this.internalFormat = source.internalFormat;
    this.type = source.type;
    this.offset.copy(source.offset);
    this.repeat.copy(source.repeat);
    this.center.copy(source.center);
    this.rotation = source.rotation;
    this.matrixAutoUpdate = source.matrixAutoUpdate;
    this.matrix.copy(source.matrix);
    this.generateMipmaps = source.generateMipmaps;
    this.premultiplyAlpha = source.premultiplyAlpha;
    this.flipY = source.flipY;
    this.unpackAlignment = source.unpackAlignment;
    this.colorSpace = source.colorSpace;
    this.userData = JSON.parse(JSON.stringify(source.userData));
    this.needsUpdate = true;
    return this;
  }
  toJSON(meta2) {
    const isRootObject = meta2 === void 0 || typeof meta2 === "string";
    if (!isRootObject && meta2.textures[this.uuid] !== void 0) {
      return meta2.textures[this.uuid];
    }
    const output = {
      metadata: {
        version: 4.6,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(meta2).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    if (Object.keys(this.userData).length > 0) output.userData = this.userData;
    if (!isRootObject) {
      meta2.textures[this.uuid] = output;
    }
    return output;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  transformUv(uv) {
    if (this.mapping !== UVMapping) return uv;
    uv.applyMatrix3(this.matrix);
    if (uv.x < 0 || uv.x > 1) {
      switch (this.wrapS) {
        case RepeatWrapping:
          uv.x = uv.x - Math.floor(uv.x);
          break;
        case ClampToEdgeWrapping:
          uv.x = uv.x < 0 ? 0 : 1;
          break;
        case MirroredRepeatWrapping:
          if (Math.abs(Math.floor(uv.x) % 2) === 1) {
            uv.x = Math.ceil(uv.x) - uv.x;
          } else {
            uv.x = uv.x - Math.floor(uv.x);
          }
          break;
      }
    }
    if (uv.y < 0 || uv.y > 1) {
      switch (this.wrapT) {
        case RepeatWrapping:
          uv.y = uv.y - Math.floor(uv.y);
          break;
        case ClampToEdgeWrapping:
          uv.y = uv.y < 0 ? 0 : 1;
          break;
        case MirroredRepeatWrapping:
          if (Math.abs(Math.floor(uv.y) % 2) === 1) {
            uv.y = Math.ceil(uv.y) - uv.y;
          } else {
            uv.y = uv.y - Math.floor(uv.y);
          }
          break;
      }
    }
    if (this.flipY) {
      uv.y = 1 - uv.y;
    }
    return uv;
  }
  set needsUpdate(value) {
    if (value === true) {
      this.version++;
      this.source.needsUpdate = true;
    }
  }
  set needsPMREMUpdate(value) {
    if (value === true) {
      this.pmremVersion++;
    }
  }
}
Texture.DEFAULT_IMAGE = null;
Texture.DEFAULT_MAPPING = UVMapping;
Texture.DEFAULT_ANISOTROPY = 1;
class Vector4 {
  constructor(x = 0, y2 = 0, z2 = 0, w2 = 1) {
    Vector4.prototype.isVector4 = true;
    this.x = x;
    this.y = y2;
    this.z = z2;
    this.w = w2;
  }
  get width() {
    return this.z;
  }
  set width(value) {
    this.z = value;
  }
  get height() {
    return this.w;
  }
  set height(value) {
    this.w = value;
  }
  set(x, y2, z2, w2) {
    this.x = x;
    this.y = y2;
    this.z = z2;
    this.w = w2;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    this.z = scalar;
    this.w = scalar;
    return this;
  }
  setX(x) {
    this.x = x;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setZ(z2) {
    this.z = z2;
    return this;
  }
  setW(w2) {
    this.w = w2;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      case 2:
        this.z = value;
        break;
      case 3:
        this.w = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      case 3:
        return this.w;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z, this.w);
  }
  copy(v5) {
    this.x = v5.x;
    this.y = v5.y;
    this.z = v5.z;
    this.w = v5.w !== void 0 ? v5.w : 1;
    return this;
  }
  add(v5) {
    this.x += v5.x;
    this.y += v5.y;
    this.z += v5.z;
    this.w += v5.w;
    return this;
  }
  addScalar(s2) {
    this.x += s2;
    this.y += s2;
    this.z += s2;
    this.w += s2;
    return this;
  }
  addVectors(a3, b2) {
    this.x = a3.x + b2.x;
    this.y = a3.y + b2.y;
    this.z = a3.z + b2.z;
    this.w = a3.w + b2.w;
    return this;
  }
  addScaledVector(v5, s2) {
    this.x += v5.x * s2;
    this.y += v5.y * s2;
    this.z += v5.z * s2;
    this.w += v5.w * s2;
    return this;
  }
  sub(v5) {
    this.x -= v5.x;
    this.y -= v5.y;
    this.z -= v5.z;
    this.w -= v5.w;
    return this;
  }
  subScalar(s2) {
    this.x -= s2;
    this.y -= s2;
    this.z -= s2;
    this.w -= s2;
    return this;
  }
  subVectors(a3, b2) {
    this.x = a3.x - b2.x;
    this.y = a3.y - b2.y;
    this.z = a3.z - b2.z;
    this.w = a3.w - b2.w;
    return this;
  }
  multiply(v5) {
    this.x *= v5.x;
    this.y *= v5.y;
    this.z *= v5.z;
    this.w *= v5.w;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    this.z *= scalar;
    this.w *= scalar;
    return this;
  }
  applyMatrix4(m2) {
    const x = this.x, y2 = this.y, z2 = this.z, w2 = this.w;
    const e2 = m2.elements;
    this.x = e2[0] * x + e2[4] * y2 + e2[8] * z2 + e2[12] * w2;
    this.y = e2[1] * x + e2[5] * y2 + e2[9] * z2 + e2[13] * w2;
    this.z = e2[2] * x + e2[6] * y2 + e2[10] * z2 + e2[14] * w2;
    this.w = e2[3] * x + e2[7] * y2 + e2[11] * z2 + e2[15] * w2;
    return this;
  }
  divide(v5) {
    this.x /= v5.x;
    this.y /= v5.y;
    this.z /= v5.z;
    this.w /= v5.w;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  setAxisAngleFromQuaternion(q3) {
    this.w = 2 * Math.acos(q3.w);
    const s2 = Math.sqrt(1 - q3.w * q3.w);
    if (s2 < 1e-4) {
      this.x = 1;
      this.y = 0;
      this.z = 0;
    } else {
      this.x = q3.x / s2;
      this.y = q3.y / s2;
      this.z = q3.z / s2;
    }
    return this;
  }
  setAxisAngleFromRotationMatrix(m2) {
    let angle, x, y2, z2;
    const epsilon2 = 0.01, epsilon22 = 0.1, te2 = m2.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10];
    if (Math.abs(m12 - m21) < epsilon2 && Math.abs(m13 - m31) < epsilon2 && Math.abs(m23 - m32) < epsilon2) {
      if (Math.abs(m12 + m21) < epsilon22 && Math.abs(m13 + m31) < epsilon22 && Math.abs(m23 + m32) < epsilon22 && Math.abs(m11 + m22 + m33 - 3) < epsilon22) {
        this.set(1, 0, 0, 0);
        return this;
      }
      angle = Math.PI;
      const xx = (m11 + 1) / 2;
      const yy = (m22 + 1) / 2;
      const zz = (m33 + 1) / 2;
      const xy = (m12 + m21) / 4;
      const xz = (m13 + m31) / 4;
      const yz = (m23 + m32) / 4;
      if (xx > yy && xx > zz) {
        if (xx < epsilon2) {
          x = 0;
          y2 = 0.707106781;
          z2 = 0.707106781;
        } else {
          x = Math.sqrt(xx);
          y2 = xy / x;
          z2 = xz / x;
        }
      } else if (yy > zz) {
        if (yy < epsilon2) {
          x = 0.707106781;
          y2 = 0;
          z2 = 0.707106781;
        } else {
          y2 = Math.sqrt(yy);
          x = xy / y2;
          z2 = yz / y2;
        }
      } else {
        if (zz < epsilon2) {
          x = 0.707106781;
          y2 = 0.707106781;
          z2 = 0;
        } else {
          z2 = Math.sqrt(zz);
          x = xz / z2;
          y2 = yz / z2;
        }
      }
      this.set(x, y2, z2, angle);
      return this;
    }
    let s2 = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12));
    if (Math.abs(s2) < 1e-3) s2 = 1;
    this.x = (m32 - m23) / s2;
    this.y = (m13 - m31) / s2;
    this.z = (m21 - m12) / s2;
    this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
    return this;
  }
  setFromMatrixPosition(m2) {
    const e2 = m2.elements;
    this.x = e2[12];
    this.y = e2[13];
    this.z = e2[14];
    this.w = e2[15];
    return this;
  }
  min(v5) {
    this.x = Math.min(this.x, v5.x);
    this.y = Math.min(this.y, v5.y);
    this.z = Math.min(this.z, v5.z);
    this.w = Math.min(this.w, v5.w);
    return this;
  }
  max(v5) {
    this.x = Math.max(this.x, v5.x);
    this.y = Math.max(this.y, v5.y);
    this.z = Math.max(this.z, v5.z);
    this.w = Math.max(this.w, v5.w);
    return this;
  }
  clamp(min, max2) {
    this.x = clamp(this.x, min.x, max2.x);
    this.y = clamp(this.y, min.y, max2.y);
    this.z = clamp(this.z, min.z, max2.z);
    this.w = clamp(this.w, min.w, max2.w);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp(this.x, minVal, maxVal);
    this.y = clamp(this.y, minVal, maxVal);
    this.z = clamp(this.z, minVal, maxVal);
    this.w = clamp(this.w, minVal, maxVal);
    return this;
  }
  clampLength(min, max2) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max2));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    this.z = Math.floor(this.z);
    this.w = Math.floor(this.w);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    this.z = Math.ceil(this.z);
    this.w = Math.ceil(this.w);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    this.z = Math.round(this.z);
    this.w = Math.round(this.w);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    this.z = Math.trunc(this.z);
    this.w = Math.trunc(this.w);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    this.z = -this.z;
    this.w = -this.w;
    return this;
  }
  dot(v5) {
    return this.x * v5.x + this.y * v5.y + this.z * v5.z + this.w * v5.w;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v5, alpha) {
    this.x += (v5.x - this.x) * alpha;
    this.y += (v5.y - this.y) * alpha;
    this.z += (v5.z - this.z) * alpha;
    this.w += (v5.w - this.w) * alpha;
    return this;
  }
  lerpVectors(v12, v22, alpha) {
    this.x = v12.x + (v22.x - v12.x) * alpha;
    this.y = v12.y + (v22.y - v12.y) * alpha;
    this.z = v12.z + (v22.z - v12.z) * alpha;
    this.w = v12.w + (v22.w - v12.w) * alpha;
    return this;
  }
  equals(v5) {
    return v5.x === this.x && v5.y === this.y && v5.z === this.z && v5.w === this.w;
  }
  fromArray(array, offset = 0) {
    this.x = array[offset];
    this.y = array[offset + 1];
    this.z = array[offset + 2];
    this.w = array[offset + 3];
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this.x;
    array[offset + 1] = this.y;
    array[offset + 2] = this.z;
    array[offset + 3] = this.w;
    return array;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    this.z = attribute.getZ(index);
    this.w = attribute.getW(index);
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    this.z = Math.random();
    this.w = Math.random();
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
    yield this.z;
    yield this.w;
  }
}
class RenderTarget extends EventDispatcher$1 {
  constructor(width = 1, height = 1, options = {}) {
    super();
    this.isRenderTarget = true;
    this.width = width;
    this.height = height;
    this.depth = 1;
    this.scissor = new Vector4(0, 0, width, height);
    this.scissorTest = false;
    this.viewport = new Vector4(0, 0, width, height);
    const image = { width, height, depth: 1 };
    options = Object.assign({
      generateMipmaps: false,
      internalFormat: null,
      minFilter: LinearFilter,
      depthBuffer: true,
      stencilBuffer: false,
      resolveDepthBuffer: true,
      resolveStencilBuffer: true,
      depthTexture: null,
      samples: 0,
      count: 1
    }, options);
    const texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace);
    texture.flipY = false;
    texture.generateMipmaps = options.generateMipmaps;
    texture.internalFormat = options.internalFormat;
    this.textures = [];
    const count = options.count;
    for (let i2 = 0; i2 < count; i2++) {
      this.textures[i2] = texture.clone();
      this.textures[i2].isRenderTargetTexture = true;
    }
    this.depthBuffer = options.depthBuffer;
    this.stencilBuffer = options.stencilBuffer;
    this.resolveDepthBuffer = options.resolveDepthBuffer;
    this.resolveStencilBuffer = options.resolveStencilBuffer;
    this.depthTexture = options.depthTexture;
    this.samples = options.samples;
  }
  get texture() {
    return this.textures[0];
  }
  set texture(value) {
    this.textures[0] = value;
  }
  setSize(width, height, depth = 1) {
    if (this.width !== width || this.height !== height || this.depth !== depth) {
      this.width = width;
      this.height = height;
      this.depth = depth;
      for (let i2 = 0, il = this.textures.length; i2 < il; i2++) {
        this.textures[i2].image.width = width;
        this.textures[i2].image.height = height;
        this.textures[i2].image.depth = depth;
      }
      this.dispose();
    }
    this.viewport.set(0, 0, width, height);
    this.scissor.set(0, 0, width, height);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.width = source.width;
    this.height = source.height;
    this.depth = source.depth;
    this.scissor.copy(source.scissor);
    this.scissorTest = source.scissorTest;
    this.viewport.copy(source.viewport);
    this.textures.length = 0;
    for (let i2 = 0, il = source.textures.length; i2 < il; i2++) {
      this.textures[i2] = source.textures[i2].clone();
      this.textures[i2].isRenderTargetTexture = true;
    }
    const image = Object.assign({}, source.texture.image);
    this.texture.source = new Source(image);
    this.depthBuffer = source.depthBuffer;
    this.stencilBuffer = source.stencilBuffer;
    this.resolveDepthBuffer = source.resolveDepthBuffer;
    this.resolveStencilBuffer = source.resolveStencilBuffer;
    if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
    this.samples = source.samples;
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
class WebGLRenderTarget extends RenderTarget {
  constructor(width = 1, height = 1, options = {}) {
    super(width, height, options);
    this.isWebGLRenderTarget = true;
  }
}
class DataArrayTexture extends Texture {
  constructor(data = null, width = 1, height = 1, depth = 1) {
    super(null);
    this.isDataArrayTexture = true;
    this.image = { data, width, height, depth };
    this.magFilter = NearestFilter;
    this.minFilter = NearestFilter;
    this.wrapR = ClampToEdgeWrapping;
    this.generateMipmaps = false;
    this.flipY = false;
    this.unpackAlignment = 1;
    this.layerUpdates = /* @__PURE__ */ new Set();
  }
  addLayerUpdate(layerIndex) {
    this.layerUpdates.add(layerIndex);
  }
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class WebGLArrayRenderTarget extends WebGLRenderTarget {
  constructor(width = 1, height = 1, depth = 1, options = {}) {
    super(width, height, options);
    this.isWebGLArrayRenderTarget = true;
    this.depth = depth;
    this.texture = new DataArrayTexture(null, width, height, depth);
    this.texture.isRenderTargetTexture = true;
  }
}
class Data3DTexture extends Texture {
  constructor(data = null, width = 1, height = 1, depth = 1) {
    super(null);
    this.isData3DTexture = true;
    this.image = { data, width, height, depth };
    this.magFilter = NearestFilter;
    this.minFilter = NearestFilter;
    this.wrapR = ClampToEdgeWrapping;
    this.generateMipmaps = false;
    this.flipY = false;
    this.unpackAlignment = 1;
  }
}
class WebGL3DRenderTarget extends WebGLRenderTarget {
  constructor(width = 1, height = 1, depth = 1, options = {}) {
    super(width, height, options);
    this.isWebGL3DRenderTarget = true;
    this.depth = depth;
    this.texture = new Data3DTexture(null, width, height, depth);
    this.texture.isRenderTargetTexture = true;
  }
}
class Quaternion {
  constructor(x = 0, y2 = 0, z2 = 0, w2 = 1) {
    this.isQuaternion = true;
    this._x = x;
    this._y = y2;
    this._z = z2;
    this._w = w2;
  }
  static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t2) {
    let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3];
    const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3];
    if (t2 === 0) {
      dst[dstOffset + 0] = x0;
      dst[dstOffset + 1] = y0;
      dst[dstOffset + 2] = z0;
      dst[dstOffset + 3] = w0;
      return;
    }
    if (t2 === 1) {
      dst[dstOffset + 0] = x1;
      dst[dstOffset + 1] = y1;
      dst[dstOffset + 2] = z1;
      dst[dstOffset + 3] = w1;
      return;
    }
    if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
      let s2 = 1 - t2;
      const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos;
      if (sqrSin > Number.EPSILON) {
        const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir);
        s2 = Math.sin(s2 * len) / sin;
        t2 = Math.sin(t2 * len) / sin;
      }
      const tDir = t2 * dir;
      x0 = x0 * s2 + x1 * tDir;
      y0 = y0 * s2 + y1 * tDir;
      z0 = z0 * s2 + z1 * tDir;
      w0 = w0 * s2 + w1 * tDir;
      if (s2 === 1 - t2) {
        const f2 = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
        x0 *= f2;
        y0 *= f2;
        z0 *= f2;
        w0 *= f2;
      }
    }
    dst[dstOffset] = x0;
    dst[dstOffset + 1] = y0;
    dst[dstOffset + 2] = z0;
    dst[dstOffset + 3] = w0;
  }
  static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
    const x0 = src0[srcOffset0];
    const y0 = src0[srcOffset0 + 1];
    const z0 = src0[srcOffset0 + 2];
    const w0 = src0[srcOffset0 + 3];
    const x1 = src1[srcOffset1];
    const y1 = src1[srcOffset1 + 1];
    const z1 = src1[srcOffset1 + 2];
    const w1 = src1[srcOffset1 + 3];
    dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
    dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
    dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
    dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
    return dst;
  }
  get x() {
    return this._x;
  }
  set x(value) {
    this._x = value;
    this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(value) {
    this._y = value;
    this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(value) {
    this._z = value;
    this._onChangeCallback();
  }
  get w() {
    return this._w;
  }
  set w(value) {
    this._w = value;
    this._onChangeCallback();
  }
  set(x, y2, z2, w2) {
    this._x = x;
    this._y = y2;
    this._z = z2;
    this._w = w2;
    this._onChangeCallback();
    return this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  copy(quaternion) {
    this._x = quaternion.x;
    this._y = quaternion.y;
    this._z = quaternion.z;
    this._w = quaternion.w;
    this._onChangeCallback();
    return this;
  }
  setFromEuler(euler, update = true) {
    const x = euler._x, y2 = euler._y, z2 = euler._z, order = euler._order;
    const cos = Math.cos;
    const sin = Math.sin;
    const c1 = cos(x / 2);
    const c2 = cos(y2 / 2);
    const c3 = cos(z2 / 2);
    const s1 = sin(x / 2);
    const s2 = sin(y2 / 2);
    const s3 = sin(z2 / 2);
    switch (order) {
      case "XYZ":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "YXZ":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      case "ZXY":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "ZYX":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      case "YZX":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "XZY":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order);
    }
    if (update === true) this._onChangeCallback();
    return this;
  }
  setFromAxisAngle(axis, angle) {
    const halfAngle = angle / 2, s2 = Math.sin(halfAngle);
    this._x = axis.x * s2;
    this._y = axis.y * s2;
    this._z = axis.z * s2;
    this._w = Math.cos(halfAngle);
    this._onChangeCallback();
    return this;
  }
  setFromRotationMatrix(m2) {
    const te2 = m2.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10], trace = m11 + m22 + m33;
    if (trace > 0) {
      const s2 = 0.5 / Math.sqrt(trace + 1);
      this._w = 0.25 / s2;
      this._x = (m32 - m23) * s2;
      this._y = (m13 - m31) * s2;
      this._z = (m21 - m12) * s2;
    } else if (m11 > m22 && m11 > m33) {
      const s2 = 2 * Math.sqrt(1 + m11 - m22 - m33);
      this._w = (m32 - m23) / s2;
      this._x = 0.25 * s2;
      this._y = (m12 + m21) / s2;
      this._z = (m13 + m31) / s2;
    } else if (m22 > m33) {
      const s2 = 2 * Math.sqrt(1 + m22 - m11 - m33);
      this._w = (m13 - m31) / s2;
      this._x = (m12 + m21) / s2;
      this._y = 0.25 * s2;
      this._z = (m23 + m32) / s2;
    } else {
      const s2 = 2 * Math.sqrt(1 + m33 - m11 - m22);
      this._w = (m21 - m12) / s2;
      this._x = (m13 + m31) / s2;
      this._y = (m23 + m32) / s2;
      this._z = 0.25 * s2;
    }
    this._onChangeCallback();
    return this;
  }
  setFromUnitVectors(vFrom, vTo) {
    let r2 = vFrom.dot(vTo) + 1;
    if (r2 < Number.EPSILON) {
      r2 = 0;
      if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
        this._x = -vFrom.y;
        this._y = vFrom.x;
        this._z = 0;
        this._w = r2;
      } else {
        this._x = 0;
        this._y = -vFrom.z;
        this._z = vFrom.y;
        this._w = r2;
      }
    } else {
      this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
      this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
      this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
      this._w = r2;
    }
    return this.normalize();
  }
  angleTo(q3) {
    return 2 * Math.acos(Math.abs(clamp(this.dot(q3), -1, 1)));
  }
  rotateTowards(q3, step) {
    const angle = this.angleTo(q3);
    if (angle === 0) return this;
    const t2 = Math.min(1, step / angle);
    this.slerp(q3, t2);
    return this;
  }
  identity() {
    return this.set(0, 0, 0, 1);
  }
  invert() {
    return this.conjugate();
  }
  conjugate() {
    this._x *= -1;
    this._y *= -1;
    this._z *= -1;
    this._onChangeCallback();
    return this;
  }
  dot(v5) {
    return this._x * v5._x + this._y * v5._y + this._z * v5._z + this._w * v5._w;
  }
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  normalize() {
    let l2 = this.length();
    if (l2 === 0) {
      this._x = 0;
      this._y = 0;
      this._z = 0;
      this._w = 1;
    } else {
      l2 = 1 / l2;
      this._x = this._x * l2;
      this._y = this._y * l2;
      this._z = this._z * l2;
      this._w = this._w * l2;
    }
    this._onChangeCallback();
    return this;
  }
  multiply(q3) {
    return this.multiplyQuaternions(this, q3);
  }
  premultiply(q3) {
    return this.multiplyQuaternions(q3, this);
  }
  multiplyQuaternions(a3, b2) {
    const qax = a3._x, qay = a3._y, qaz = a3._z, qaw = a3._w;
    const qbx = b2._x, qby = b2._y, qbz = b2._z, qbw = b2._w;
    this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
    this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
    this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
    this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
    this._onChangeCallback();
    return this;
  }
  slerp(qb, t2) {
    if (t2 === 0) return this;
    if (t2 === 1) return this.copy(qb);
    const x = this._x, y2 = this._y, z2 = this._z, w2 = this._w;
    let cosHalfTheta = w2 * qb._w + x * qb._x + y2 * qb._y + z2 * qb._z;
    if (cosHalfTheta < 0) {
      this._w = -qb._w;
      this._x = -qb._x;
      this._y = -qb._y;
      this._z = -qb._z;
      cosHalfTheta = -cosHalfTheta;
    } else {
      this.copy(qb);
    }
    if (cosHalfTheta >= 1) {
      this._w = w2;
      this._x = x;
      this._y = y2;
      this._z = z2;
      return this;
    }
    const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta;
    if (sqrSinHalfTheta <= Number.EPSILON) {
      const s2 = 1 - t2;
      this._w = s2 * w2 + t2 * this._w;
      this._x = s2 * x + t2 * this._x;
      this._y = s2 * y2 + t2 * this._y;
      this._z = s2 * z2 + t2 * this._z;
      this.normalize();
      return this;
    }
    const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
    const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
    const ratioA = Math.sin((1 - t2) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t2 * halfTheta) / sinHalfTheta;
    this._w = w2 * ratioA + this._w * ratioB;
    this._x = x * ratioA + this._x * ratioB;
    this._y = y2 * ratioA + this._y * ratioB;
    this._z = z2 * ratioA + this._z * ratioB;
    this._onChangeCallback();
    return this;
  }
  slerpQuaternions(qa, qb, t2) {
    return this.copy(qa).slerp(qb, t2);
  }
  random() {
    const theta1 = 2 * Math.PI * Math.random();
    const theta2 = 2 * Math.PI * Math.random();
    const x0 = Math.random();
    const r1 = Math.sqrt(1 - x0);
    const r2 = Math.sqrt(x0);
    return this.set(
      r1 * Math.sin(theta1),
      r1 * Math.cos(theta1),
      r2 * Math.sin(theta2),
      r2 * Math.cos(theta2)
    );
  }
  equals(quaternion) {
    return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  }
  fromArray(array, offset = 0) {
    this._x = array[offset];
    this._y = array[offset + 1];
    this._z = array[offset + 2];
    this._w = array[offset + 3];
    this._onChangeCallback();
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this._x;
    array[offset + 1] = this._y;
    array[offset + 2] = this._z;
    array[offset + 3] = this._w;
    return array;
  }
  fromBufferAttribute(attribute, index) {
    this._x = attribute.getX(index);
    this._y = attribute.getY(index);
    this._z = attribute.getZ(index);
    this._w = attribute.getW(index);
    this._onChangeCallback();
    return this;
  }
  toJSON() {
    return this.toArray();
  }
  _onChange(callback) {
    this._onChangeCallback = callback;
    return this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x;
    yield this._y;
    yield this._z;
    yield this._w;
  }
}
class Vector3 {
  constructor(x = 0, y2 = 0, z2 = 0) {
    Vector3.prototype.isVector3 = true;
    this.x = x;
    this.y = y2;
    this.z = z2;
  }
  set(x, y2, z2) {
    if (z2 === void 0) z2 = this.z;
    this.x = x;
    this.y = y2;
    this.z = z2;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    this.z = scalar;
    return this;
  }
  setX(x) {
    this.x = x;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setZ(z2) {
    this.z = z2;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      case 2:
        this.z = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  copy(v5) {
    this.x = v5.x;
    this.y = v5.y;
    this.z = v5.z;
    return this;
  }
  add(v5) {
    this.x += v5.x;
    this.y += v5.y;
    this.z += v5.z;
    return this;
  }
  addScalar(s2) {
    this.x += s2;
    this.y += s2;
    this.z += s2;
    return this;
  }
  addVectors(a3, b2) {
    this.x = a3.x + b2.x;
    this.y = a3.y + b2.y;
    this.z = a3.z + b2.z;
    return this;
  }
  addScaledVector(v5, s2) {
    this.x += v5.x * s2;
    this.y += v5.y * s2;
    this.z += v5.z * s2;
    return this;
  }
  sub(v5) {
    this.x -= v5.x;
    this.y -= v5.y;
    this.z -= v5.z;
    return this;
  }
  subScalar(s2) {
    this.x -= s2;
    this.y -= s2;
    this.z -= s2;
    return this;
  }
  subVectors(a3, b2) {
    this.x = a3.x - b2.x;
    this.y = a3.y - b2.y;
    this.z = a3.z - b2.z;
    return this;
  }
  multiply(v5) {
    this.x *= v5.x;
    this.y *= v5.y;
    this.z *= v5.z;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    this.z *= scalar;
    return this;
  }
  multiplyVectors(a3, b2) {
    this.x = a3.x * b2.x;
    this.y = a3.y * b2.y;
    this.z = a3.z * b2.z;
    return this;
  }
  applyEuler(euler) {
    return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  }
  applyAxisAngle(axis, angle) {
    return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  }
  applyMatrix3(m2) {
    const x = this.x, y2 = this.y, z2 = this.z;
    const e2 = m2.elements;
    this.x = e2[0] * x + e2[3] * y2 + e2[6] * z2;
    this.y = e2[1] * x + e2[4] * y2 + e2[7] * z2;
    this.z = e2[2] * x + e2[5] * y2 + e2[8] * z2;
    return this;
  }
  applyNormalMatrix(m2) {
    return this.applyMatrix3(m2).normalize();
  }
  applyMatrix4(m2) {
    const x = this.x, y2 = this.y, z2 = this.z;
    const e2 = m2.elements;
    const w2 = 1 / (e2[3] * x + e2[7] * y2 + e2[11] * z2 + e2[15]);
    this.x = (e2[0] * x + e2[4] * y2 + e2[8] * z2 + e2[12]) * w2;
    this.y = (e2[1] * x + e2[5] * y2 + e2[9] * z2 + e2[13]) * w2;
    this.z = (e2[2] * x + e2[6] * y2 + e2[10] * z2 + e2[14]) * w2;
    return this;
  }
  applyQuaternion(q3) {
    const vx = this.x, vy = this.y, vz = this.z;
    const qx = q3.x, qy = q3.y, qz = q3.z, qw = q3.w;
    const tx = 2 * (qy * vz - qz * vy);
    const ty = 2 * (qz * vx - qx * vz);
    const tz = 2 * (qx * vy - qy * vx);
    this.x = vx + qw * tx + qy * tz - qz * ty;
    this.y = vy + qw * ty + qz * tx - qx * tz;
    this.z = vz + qw * tz + qx * ty - qy * tx;
    return this;
  }
  project(camera) {
    return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  }
  unproject(camera) {
    return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  }
  transformDirection(m2) {
    const x = this.x, y2 = this.y, z2 = this.z;
    const e2 = m2.elements;
    this.x = e2[0] * x + e2[4] * y2 + e2[8] * z2;
    this.y = e2[1] * x + e2[5] * y2 + e2[9] * z2;
    this.z = e2[2] * x + e2[6] * y2 + e2[10] * z2;
    return this.normalize();
  }
  divide(v5) {
    this.x /= v5.x;
    this.y /= v5.y;
    this.z /= v5.z;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  min(v5) {
    this.x = Math.min(this.x, v5.x);
    this.y = Math.min(this.y, v5.y);
    this.z = Math.min(this.z, v5.z);
    return this;
  }
  max(v5) {
    this.x = Math.max(this.x, v5.x);
    this.y = Math.max(this.y, v5.y);
    this.z = Math.max(this.z, v5.z);
    return this;
  }
  clamp(min, max2) {
    this.x = clamp(this.x, min.x, max2.x);
    this.y = clamp(this.y, min.y, max2.y);
    this.z = clamp(this.z, min.z, max2.z);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp(this.x, minVal, maxVal);
    this.y = clamp(this.y, minVal, maxVal);
    this.z = clamp(this.z, minVal, maxVal);
    return this;
  }
  clampLength(min, max2) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max2));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    this.z = Math.floor(this.z);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    this.z = Math.ceil(this.z);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    this.z = Math.round(this.z);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    this.z = Math.trunc(this.z);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    this.z = -this.z;
    return this;
  }
  dot(v5) {
    return this.x * v5.x + this.y * v5.y + this.z * v5.z;
  }
  // TODO lengthSquared?
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v5, alpha) {
    this.x += (v5.x - this.x) * alpha;
    this.y += (v5.y - this.y) * alpha;
    this.z += (v5.z - this.z) * alpha;
    return this;
  }
  lerpVectors(v12, v22, alpha) {
    this.x = v12.x + (v22.x - v12.x) * alpha;
    this.y = v12.y + (v22.y - v12.y) * alpha;
    this.z = v12.z + (v22.z - v12.z) * alpha;
    return this;
  }
  cross(v5) {
    return this.crossVectors(this, v5);
  }
  crossVectors(a3, b2) {
    const ax = a3.x, ay = a3.y, az = a3.z;
    const bx = b2.x, by = b2.y, bz = b2.z;
    this.x = ay * bz - az * by;
    this.y = az * bx - ax * bz;
    this.z = ax * by - ay * bx;
    return this;
  }
  projectOnVector(v5) {
    const denominator = v5.lengthSq();
    if (denominator === 0) return this.set(0, 0, 0);
    const scalar = v5.dot(this) / denominator;
    return this.copy(v5).multiplyScalar(scalar);
  }
  projectOnPlane(planeNormal) {
    _vector$c.copy(this).projectOnVector(planeNormal);
    return this.sub(_vector$c);
  }
  reflect(normal) {
    return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  }
  angleTo(v5) {
    const denominator = Math.sqrt(this.lengthSq() * v5.lengthSq());
    if (denominator === 0) return Math.PI / 2;
    const theta = this.dot(v5) / denominator;
    return Math.acos(clamp(theta, -1, 1));
  }
  distanceTo(v5) {
    return Math.sqrt(this.distanceToSquared(v5));
  }
  distanceToSquared(v5) {
    const dx = this.x - v5.x, dy = this.y - v5.y, dz = this.z - v5.z;
    return dx * dx + dy * dy + dz * dz;
  }
  manhattanDistanceTo(v5) {
    return Math.abs(this.x - v5.x) + Math.abs(this.y - v5.y) + Math.abs(this.z - v5.z);
  }
  setFromSpherical(s2) {
    return this.setFromSphericalCoords(s2.radius, s2.phi, s2.theta);
  }
  setFromSphericalCoords(radius, phi, theta) {
    const sinPhiRadius = Math.sin(phi) * radius;
    this.x = sinPhiRadius * Math.sin(theta);
    this.y = Math.cos(phi) * radius;
    this.z = sinPhiRadius * Math.cos(theta);
    return this;
  }
  setFromCylindrical(c2) {
    return this.setFromCylindricalCoords(c2.radius, c2.theta, c2.y);
  }
  setFromCylindricalCoords(radius, theta, y2) {
    this.x = radius * Math.sin(theta);
    this.y = y2;
    this.z = radius * Math.cos(theta);
    return this;
  }
  setFromMatrixPosition(m2) {
    const e2 = m2.elements;
    this.x = e2[12];
    this.y = e2[13];
    this.z = e2[14];
    return this;
  }
  setFromMatrixScale(m2) {
    const sx = this.setFromMatrixColumn(m2, 0).length();
    const sy = this.setFromMatrixColumn(m2, 1).length();
    const sz = this.setFromMatrixColumn(m2, 2).length();
    this.x = sx;
    this.y = sy;
    this.z = sz;
    return this;
  }
  setFromMatrixColumn(m2, index) {
    return this.fromArray(m2.elements, index * 4);
  }
  setFromMatrix3Column(m2, index) {
    return this.fromArray(m2.elements, index * 3);
  }
  setFromEuler(e2) {
    this.x = e2._x;
    this.y = e2._y;
    this.z = e2._z;
    return this;
  }
  setFromColor(c2) {
    this.x = c2.r;
    this.y = c2.g;
    this.z = c2.b;
    return this;
  }
  equals(v5) {
    return v5.x === this.x && v5.y === this.y && v5.z === this.z;
  }
  fromArray(array, offset = 0) {
    this.x = array[offset];
    this.y = array[offset + 1];
    this.z = array[offset + 2];
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this.x;
    array[offset + 1] = this.y;
    array[offset + 2] = this.z;
    return array;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    this.z = attribute.getZ(index);
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    this.z = Math.random();
    return this;
  }
  randomDirection() {
    const theta = Math.random() * Math.PI * 2;
    const u2 = Math.random() * 2 - 1;
    const c2 = Math.sqrt(1 - u2 * u2);
    this.x = c2 * Math.cos(theta);
    this.y = u2;
    this.z = c2 * Math.sin(theta);
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
    yield this.z;
  }
}
const _vector$c = /* @__PURE__ */ new Vector3();
const _quaternion$4 = /* @__PURE__ */ new Quaternion();
class Box3 {
  constructor(min = new Vector3(Infinity, Infinity, Infinity), max2 = new Vector3(-Infinity, -Infinity, -Infinity)) {
    this.isBox3 = true;
    this.min = min;
    this.max = max2;
  }
  set(min, max2) {
    this.min.copy(min);
    this.max.copy(max2);
    return this;
  }
  setFromArray(array) {
    this.makeEmpty();
    for (let i2 = 0, il = array.length; i2 < il; i2 += 3) {
      this.expandByPoint(_vector$b.fromArray(array, i2));
    }
    return this;
  }
  setFromBufferAttribute(attribute) {
    this.makeEmpty();
    for (let i2 = 0, il = attribute.count; i2 < il; i2++) {
      this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i2));
    }
    return this;
  }
  setFromPoints(points) {
    this.makeEmpty();
    for (let i2 = 0, il = points.length; i2 < il; i2++) {
      this.expandByPoint(points[i2]);
    }
    return this;
  }
  setFromCenterAndSize(center, size) {
    const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
    this.min.copy(center).sub(halfSize);
    this.max.copy(center).add(halfSize);
    return this;
  }
  setFromObject(object, precise = false) {
    this.makeEmpty();
    return this.expandByObject(object, precise);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(box) {
    this.min.copy(box.min);
    this.max.copy(box.max);
    return this;
  }
  makeEmpty() {
    this.min.x = this.min.y = this.min.z = Infinity;
    this.max.x = this.max.y = this.max.z = -Infinity;
    return this;
  }
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  }
  getCenter(target) {
    return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  getSize(target) {
    return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  }
  expandByPoint(point) {
    this.min.min(point);
    this.max.max(point);
    return this;
  }
  expandByVector(vector) {
    this.min.sub(vector);
    this.max.add(vector);
    return this;
  }
  expandByScalar(scalar) {
    this.min.addScalar(-scalar);
    this.max.addScalar(scalar);
    return this;
  }
  expandByObject(object, precise = false) {
    object.updateWorldMatrix(false, false);
    const geometry = object.geometry;
    if (geometry !== void 0) {
      const positionAttribute = geometry.getAttribute("position");
      if (precise === true && positionAttribute !== void 0 && object.isInstancedMesh !== true) {
        for (let i2 = 0, l2 = positionAttribute.count; i2 < l2; i2++) {
          if (object.isMesh === true) {
            object.getVertexPosition(i2, _vector$b);
          } else {
            _vector$b.fromBufferAttribute(positionAttribute, i2);
          }
          _vector$b.applyMatrix4(object.matrixWorld);
          this.expandByPoint(_vector$b);
        }
      } else {
        if (object.boundingBox !== void 0) {
          if (object.boundingBox === null) {
            object.computeBoundingBox();
          }
          _box$4.copy(object.boundingBox);
        } else {
          if (geometry.boundingBox === null) {
            geometry.computeBoundingBox();
          }
          _box$4.copy(geometry.boundingBox);
        }
        _box$4.applyMatrix4(object.matrixWorld);
        this.union(_box$4);
      }
    }
    const children = object.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      this.expandByObject(children[i2], precise);
    }
    return this;
  }
  containsPoint(point) {
    return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z;
  }
  containsBox(box) {
    return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  }
  getParameter(point, target) {
    return target.set(
      (point.x - this.min.x) / (this.max.x - this.min.x),
      (point.y - this.min.y) / (this.max.y - this.min.y),
      (point.z - this.min.z) / (this.max.z - this.min.z)
    );
  }
  intersectsBox(box) {
    return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z;
  }
  intersectsSphere(sphere) {
    this.clampPoint(sphere.center, _vector$b);
    return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  }
  intersectsPlane(plane) {
    let min, max2;
    if (plane.normal.x > 0) {
      min = plane.normal.x * this.min.x;
      max2 = plane.normal.x * this.max.x;
    } else {
      min = plane.normal.x * this.max.x;
      max2 = plane.normal.x * this.min.x;
    }
    if (plane.normal.y > 0) {
      min += plane.normal.y * this.min.y;
      max2 += plane.normal.y * this.max.y;
    } else {
      min += plane.normal.y * this.max.y;
      max2 += plane.normal.y * this.min.y;
    }
    if (plane.normal.z > 0) {
      min += plane.normal.z * this.min.z;
      max2 += plane.normal.z * this.max.z;
    } else {
      min += plane.normal.z * this.max.z;
      max2 += plane.normal.z * this.min.z;
    }
    return min <= -plane.constant && max2 >= -plane.constant;
  }
  intersectsTriangle(triangle) {
    if (this.isEmpty()) {
      return false;
    }
    this.getCenter(_center);
    _extents.subVectors(this.max, _center);
    _v0$2.subVectors(triangle.a, _center);
    _v1$7.subVectors(triangle.b, _center);
    _v2$4.subVectors(triangle.c, _center);
    _f0.subVectors(_v1$7, _v0$2);
    _f1.subVectors(_v2$4, _v1$7);
    _f2.subVectors(_v0$2, _v2$4);
    let axes = [
      0,
      -_f0.z,
      _f0.y,
      0,
      -_f1.z,
      _f1.y,
      0,
      -_f2.z,
      _f2.y,
      _f0.z,
      0,
      -_f0.x,
      _f1.z,
      0,
      -_f1.x,
      _f2.z,
      0,
      -_f2.x,
      -_f0.y,
      _f0.x,
      0,
      -_f1.y,
      _f1.x,
      0,
      -_f2.y,
      _f2.x,
      0
    ];
    if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
      return false;
    }
    axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
    if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
      return false;
    }
    _triangleNormal.crossVectors(_f0, _f1);
    axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
    return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents);
  }
  clampPoint(point, target) {
    return target.copy(point).clamp(this.min, this.max);
  }
  distanceToPoint(point) {
    return this.clampPoint(point, _vector$b).distanceTo(point);
  }
  getBoundingSphere(target) {
    if (this.isEmpty()) {
      target.makeEmpty();
    } else {
      this.getCenter(target.center);
      target.radius = this.getSize(_vector$b).length() * 0.5;
    }
    return target;
  }
  intersect(box) {
    this.min.max(box.min);
    this.max.min(box.max);
    if (this.isEmpty()) this.makeEmpty();
    return this;
  }
  union(box) {
    this.min.min(box.min);
    this.max.max(box.max);
    return this;
  }
  applyMatrix4(matrix) {
    if (this.isEmpty()) return this;
    _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix);
    _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix);
    _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix);
    _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix);
    _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix);
    _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix);
    _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix);
    _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix);
    this.setFromPoints(_points);
    return this;
  }
  translate(offset) {
    this.min.add(offset);
    this.max.add(offset);
    return this;
  }
  equals(box) {
    return box.min.equals(this.min) && box.max.equals(this.max);
  }
}
const _points = [
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3(),
  /* @__PURE__ */ new Vector3()
];
const _vector$b = /* @__PURE__ */ new Vector3();
const _box$4 = /* @__PURE__ */ new Box3();
const _v0$2 = /* @__PURE__ */ new Vector3();
const _v1$7 = /* @__PURE__ */ new Vector3();
const _v2$4 = /* @__PURE__ */ new Vector3();
const _f0 = /* @__PURE__ */ new Vector3();
const _f1 = /* @__PURE__ */ new Vector3();
const _f2 = /* @__PURE__ */ new Vector3();
const _center = /* @__PURE__ */ new Vector3();
const _extents = /* @__PURE__ */ new Vector3();
const _triangleNormal = /* @__PURE__ */ new Vector3();
const _testAxis = /* @__PURE__ */ new Vector3();
function satForAxes(axes, v0, v12, v22, extents) {
  for (let i2 = 0, j2 = axes.length - 3; i2 <= j2; i2 += 3) {
    _testAxis.fromArray(axes, i2);
    const r2 = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z);
    const p0 = v0.dot(_testAxis);
    const p1 = v12.dot(_testAxis);
    const p2 = v22.dot(_testAxis);
    if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r2) {
      return false;
    }
  }
  return true;
}
const _box$3 = /* @__PURE__ */ new Box3();
const _v1$6 = /* @__PURE__ */ new Vector3();
const _v2$3 = /* @__PURE__ */ new Vector3();
class Sphere {
  constructor(center = new Vector3(), radius = -1) {
    this.isSphere = true;
    this.center = center;
    this.radius = radius;
  }
  set(center, radius) {
    this.center.copy(center);
    this.radius = radius;
    return this;
  }
  setFromPoints(points, optionalCenter) {
    const center = this.center;
    if (optionalCenter !== void 0) {
      center.copy(optionalCenter);
    } else {
      _box$3.setFromPoints(points).getCenter(center);
    }
    let maxRadiusSq = 0;
    for (let i2 = 0, il = points.length; i2 < il; i2++) {
      maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i2]));
    }
    this.radius = Math.sqrt(maxRadiusSq);
    return this;
  }
  copy(sphere) {
    this.center.copy(sphere.center);
    this.radius = sphere.radius;
    return this;
  }
  isEmpty() {
    return this.radius < 0;
  }
  makeEmpty() {
    this.center.set(0, 0, 0);
    this.radius = -1;
    return this;
  }
  containsPoint(point) {
    return point.distanceToSquared(this.center) <= this.radius * this.radius;
  }
  distanceToPoint(point) {
    return point.distanceTo(this.center) - this.radius;
  }
  intersectsSphere(sphere) {
    const radiusSum = this.radius + sphere.radius;
    return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  }
  intersectsBox(box) {
    return box.intersectsSphere(this);
  }
  intersectsPlane(plane) {
    return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  }
  clampPoint(point, target) {
    const deltaLengthSq = this.center.distanceToSquared(point);
    target.copy(point);
    if (deltaLengthSq > this.radius * this.radius) {
      target.sub(this.center).normalize();
      target.multiplyScalar(this.radius).add(this.center);
    }
    return target;
  }
  getBoundingBox(target) {
    if (this.isEmpty()) {
      target.makeEmpty();
      return target;
    }
    target.set(this.center, this.center);
    target.expandByScalar(this.radius);
    return target;
  }
  applyMatrix4(matrix) {
    this.center.applyMatrix4(matrix);
    this.radius = this.radius * matrix.getMaxScaleOnAxis();
    return this;
  }
  translate(offset) {
    this.center.add(offset);
    return this;
  }
  expandByPoint(point) {
    if (this.isEmpty()) {
      this.center.copy(point);
      this.radius = 0;
      return this;
    }
    _v1$6.subVectors(point, this.center);
    const lengthSq = _v1$6.lengthSq();
    if (lengthSq > this.radius * this.radius) {
      const length = Math.sqrt(lengthSq);
      const delta = (length - this.radius) * 0.5;
      this.center.addScaledVector(_v1$6, delta / length);
      this.radius += delta;
    }
    return this;
  }
  union(sphere) {
    if (sphere.isEmpty()) {
      return this;
    }
    if (this.isEmpty()) {
      this.copy(sphere);
      return this;
    }
    if (this.center.equals(sphere.center) === true) {
      this.radius = Math.max(this.radius, sphere.radius);
    } else {
      _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius);
      this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3));
      this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3));
    }
    return this;
  }
  equals(sphere) {
    return sphere.center.equals(this.center) && sphere.radius === this.radius;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const _vector$a = /* @__PURE__ */ new Vector3();
const _segCenter = /* @__PURE__ */ new Vector3();
const _segDir = /* @__PURE__ */ new Vector3();
const _diff = /* @__PURE__ */ new Vector3();
const _edge1 = /* @__PURE__ */ new Vector3();
const _edge2 = /* @__PURE__ */ new Vector3();
const _normal$1 = /* @__PURE__ */ new Vector3();
class Ray {
  constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
    this.origin = origin;
    this.direction = direction;
  }
  set(origin, direction) {
    this.origin.copy(origin);
    this.direction.copy(direction);
    return this;
  }
  copy(ray) {
    this.origin.copy(ray.origin);
    this.direction.copy(ray.direction);
    return this;
  }
  at(t2, target) {
    return target.copy(this.origin).addScaledVector(this.direction, t2);
  }
  lookAt(v5) {
    this.direction.copy(v5).sub(this.origin).normalize();
    return this;
  }
  recast(t2) {
    this.origin.copy(this.at(t2, _vector$a));
    return this;
  }
  closestPointToPoint(point, target) {
    target.subVectors(point, this.origin);
    const directionDistance = target.dot(this.direction);
    if (directionDistance < 0) {
      return target.copy(this.origin);
    }
    return target.copy(this.origin).addScaledVector(this.direction, directionDistance);
  }
  distanceToPoint(point) {
    return Math.sqrt(this.distanceSqToPoint(point));
  }
  distanceSqToPoint(point) {
    const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction);
    if (directionDistance < 0) {
      return this.origin.distanceToSquared(point);
    }
    _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance);
    return _vector$a.distanceToSquared(point);
  }
  distanceSqToSegment(v0, v12, optionalPointOnRay, optionalPointOnSegment) {
    _segCenter.copy(v0).add(v12).multiplyScalar(0.5);
    _segDir.copy(v12).sub(v0).normalize();
    _diff.copy(this.origin).sub(_segCenter);
    const segExtent = v0.distanceTo(v12) * 0.5;
    const a01 = -this.direction.dot(_segDir);
    const b0 = _diff.dot(this.direction);
    const b1 = -_diff.dot(_segDir);
    const c2 = _diff.lengthSq();
    const det = Math.abs(1 - a01 * a01);
    let s0, s1, sqrDist, extDet;
    if (det > 0) {
      s0 = a01 * b1 - b0;
      s1 = a01 * b0 - b1;
      extDet = segExtent * det;
      if (s0 >= 0) {
        if (s1 >= -extDet) {
          if (s1 <= extDet) {
            const invDet = 1 / det;
            s0 *= invDet;
            s1 *= invDet;
            sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c2;
          } else {
            s1 = segExtent;
            s0 = Math.max(0, -(a01 * s1 + b0));
            sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2;
          }
        } else {
          s1 = -segExtent;
          s0 = Math.max(0, -(a01 * s1 + b0));
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2;
        }
      } else {
        if (s1 <= -extDet) {
          s0 = Math.max(0, -(-a01 * segExtent + b0));
          s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2;
        } else if (s1 <= extDet) {
          s0 = 0;
          s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = s1 * (s1 + 2 * b1) + c2;
        } else {
          s0 = Math.max(0, -(a01 * segExtent + b0));
          s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2;
        }
      }
    } else {
      s1 = a01 > 0 ? -segExtent : segExtent;
      s0 = Math.max(0, -(a01 * s1 + b0));
      sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2;
    }
    if (optionalPointOnRay) {
      optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0);
    }
    if (optionalPointOnSegment) {
      optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1);
    }
    return sqrDist;
  }
  intersectSphere(sphere, target) {
    _vector$a.subVectors(sphere.center, this.origin);
    const tca = _vector$a.dot(this.direction);
    const d2 = _vector$a.dot(_vector$a) - tca * tca;
    const radius2 = sphere.radius * sphere.radius;
    if (d2 > radius2) return null;
    const thc = Math.sqrt(radius2 - d2);
    const t0 = tca - thc;
    const t1 = tca + thc;
    if (t1 < 0) return null;
    if (t0 < 0) return this.at(t1, target);
    return this.at(t0, target);
  }
  intersectsSphere(sphere) {
    return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  }
  distanceToPlane(plane) {
    const denominator = plane.normal.dot(this.direction);
    if (denominator === 0) {
      if (plane.distanceToPoint(this.origin) === 0) {
        return 0;
      }
      return null;
    }
    const t2 = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
    return t2 >= 0 ? t2 : null;
  }
  intersectPlane(plane, target) {
    const t2 = this.distanceToPlane(plane);
    if (t2 === null) {
      return null;
    }
    return this.at(t2, target);
  }
  intersectsPlane(plane) {
    const distToPoint = plane.distanceToPoint(this.origin);
    if (distToPoint === 0) {
      return true;
    }
    const denominator = plane.normal.dot(this.direction);
    if (denominator * distToPoint < 0) {
      return true;
    }
    return false;
  }
  intersectBox(box, target) {
    let tmin, tmax, tymin, tymax, tzmin, tzmax;
    const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z;
    const origin = this.origin;
    if (invdirx >= 0) {
      tmin = (box.min.x - origin.x) * invdirx;
      tmax = (box.max.x - origin.x) * invdirx;
    } else {
      tmin = (box.max.x - origin.x) * invdirx;
      tmax = (box.min.x - origin.x) * invdirx;
    }
    if (invdiry >= 0) {
      tymin = (box.min.y - origin.y) * invdiry;
      tymax = (box.max.y - origin.y) * invdiry;
    } else {
      tymin = (box.max.y - origin.y) * invdiry;
      tymax = (box.min.y - origin.y) * invdiry;
    }
    if (tmin > tymax || tymin > tmax) return null;
    if (tymin > tmin || isNaN(tmin)) tmin = tymin;
    if (tymax < tmax || isNaN(tmax)) tmax = tymax;
    if (invdirz >= 0) {
      tzmin = (box.min.z - origin.z) * invdirz;
      tzmax = (box.max.z - origin.z) * invdirz;
    } else {
      tzmin = (box.max.z - origin.z) * invdirz;
      tzmax = (box.min.z - origin.z) * invdirz;
    }
    if (tmin > tzmax || tzmin > tmax) return null;
    if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
    if (tzmax < tmax || tmax !== tmax) tmax = tzmax;
    if (tmax < 0) return null;
    return this.at(tmin >= 0 ? tmin : tmax, target);
  }
  intersectsBox(box) {
    return this.intersectBox(box, _vector$a) !== null;
  }
  intersectTriangle(a3, b2, c2, backfaceCulling, target) {
    _edge1.subVectors(b2, a3);
    _edge2.subVectors(c2, a3);
    _normal$1.crossVectors(_edge1, _edge2);
    let DdN = this.direction.dot(_normal$1);
    let sign2;
    if (DdN > 0) {
      if (backfaceCulling) return null;
      sign2 = 1;
    } else if (DdN < 0) {
      sign2 = -1;
      DdN = -DdN;
    } else {
      return null;
    }
    _diff.subVectors(this.origin, a3);
    const DdQxE2 = sign2 * this.direction.dot(_edge2.crossVectors(_diff, _edge2));
    if (DdQxE2 < 0) {
      return null;
    }
    const DdE1xQ = sign2 * this.direction.dot(_edge1.cross(_diff));
    if (DdE1xQ < 0) {
      return null;
    }
    if (DdQxE2 + DdE1xQ > DdN) {
      return null;
    }
    const QdN = -sign2 * _diff.dot(_normal$1);
    if (QdN < 0) {
      return null;
    }
    return this.at(QdN / DdN, target);
  }
  applyMatrix4(matrix4) {
    this.origin.applyMatrix4(matrix4);
    this.direction.transformDirection(matrix4);
    return this;
  }
  equals(ray) {
    return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
class Matrix4 {
  constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    Matrix4.prototype.isMatrix4 = true;
    this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ];
    if (n11 !== void 0) {
      this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44);
    }
  }
  set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    const te2 = this.elements;
    te2[0] = n11;
    te2[4] = n12;
    te2[8] = n13;
    te2[12] = n14;
    te2[1] = n21;
    te2[5] = n22;
    te2[9] = n23;
    te2[13] = n24;
    te2[2] = n31;
    te2[6] = n32;
    te2[10] = n33;
    te2[14] = n34;
    te2[3] = n41;
    te2[7] = n42;
    te2[11] = n43;
    te2[15] = n44;
    return this;
  }
  identity() {
    this.set(
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  clone() {
    return new Matrix4().fromArray(this.elements);
  }
  copy(m2) {
    const te2 = this.elements;
    const me2 = m2.elements;
    te2[0] = me2[0];
    te2[1] = me2[1];
    te2[2] = me2[2];
    te2[3] = me2[3];
    te2[4] = me2[4];
    te2[5] = me2[5];
    te2[6] = me2[6];
    te2[7] = me2[7];
    te2[8] = me2[8];
    te2[9] = me2[9];
    te2[10] = me2[10];
    te2[11] = me2[11];
    te2[12] = me2[12];
    te2[13] = me2[13];
    te2[14] = me2[14];
    te2[15] = me2[15];
    return this;
  }
  copyPosition(m2) {
    const te2 = this.elements, me2 = m2.elements;
    te2[12] = me2[12];
    te2[13] = me2[13];
    te2[14] = me2[14];
    return this;
  }
  setFromMatrix3(m2) {
    const me2 = m2.elements;
    this.set(
      me2[0],
      me2[3],
      me2[6],
      0,
      me2[1],
      me2[4],
      me2[7],
      0,
      me2[2],
      me2[5],
      me2[8],
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  extractBasis(xAxis, yAxis, zAxis) {
    xAxis.setFromMatrixColumn(this, 0);
    yAxis.setFromMatrixColumn(this, 1);
    zAxis.setFromMatrixColumn(this, 2);
    return this;
  }
  makeBasis(xAxis, yAxis, zAxis) {
    this.set(
      xAxis.x,
      yAxis.x,
      zAxis.x,
      0,
      xAxis.y,
      yAxis.y,
      zAxis.y,
      0,
      xAxis.z,
      yAxis.z,
      zAxis.z,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  extractRotation(m2) {
    const te2 = this.elements;
    const me2 = m2.elements;
    const scaleX = 1 / _v1$5.setFromMatrixColumn(m2, 0).length();
    const scaleY = 1 / _v1$5.setFromMatrixColumn(m2, 1).length();
    const scaleZ = 1 / _v1$5.setFromMatrixColumn(m2, 2).length();
    te2[0] = me2[0] * scaleX;
    te2[1] = me2[1] * scaleX;
    te2[2] = me2[2] * scaleX;
    te2[3] = 0;
    te2[4] = me2[4] * scaleY;
    te2[5] = me2[5] * scaleY;
    te2[6] = me2[6] * scaleY;
    te2[7] = 0;
    te2[8] = me2[8] * scaleZ;
    te2[9] = me2[9] * scaleZ;
    te2[10] = me2[10] * scaleZ;
    te2[11] = 0;
    te2[12] = 0;
    te2[13] = 0;
    te2[14] = 0;
    te2[15] = 1;
    return this;
  }
  makeRotationFromEuler(euler) {
    const te2 = this.elements;
    const x = euler.x, y2 = euler.y, z2 = euler.z;
    const a3 = Math.cos(x), b2 = Math.sin(x);
    const c2 = Math.cos(y2), d2 = Math.sin(y2);
    const e2 = Math.cos(z2), f2 = Math.sin(z2);
    if (euler.order === "XYZ") {
      const ae = a3 * e2, af = a3 * f2, be2 = b2 * e2, bf = b2 * f2;
      te2[0] = c2 * e2;
      te2[4] = -c2 * f2;
      te2[8] = d2;
      te2[1] = af + be2 * d2;
      te2[5] = ae - bf * d2;
      te2[9] = -b2 * c2;
      te2[2] = bf - ae * d2;
      te2[6] = be2 + af * d2;
      te2[10] = a3 * c2;
    } else if (euler.order === "YXZ") {
      const ce2 = c2 * e2, cf = c2 * f2, de2 = d2 * e2, df = d2 * f2;
      te2[0] = ce2 + df * b2;
      te2[4] = de2 * b2 - cf;
      te2[8] = a3 * d2;
      te2[1] = a3 * f2;
      te2[5] = a3 * e2;
      te2[9] = -b2;
      te2[2] = cf * b2 - de2;
      te2[6] = df + ce2 * b2;
      te2[10] = a3 * c2;
    } else if (euler.order === "ZXY") {
      const ce2 = c2 * e2, cf = c2 * f2, de2 = d2 * e2, df = d2 * f2;
      te2[0] = ce2 - df * b2;
      te2[4] = -a3 * f2;
      te2[8] = de2 + cf * b2;
      te2[1] = cf + de2 * b2;
      te2[5] = a3 * e2;
      te2[9] = df - ce2 * b2;
      te2[2] = -a3 * d2;
      te2[6] = b2;
      te2[10] = a3 * c2;
    } else if (euler.order === "ZYX") {
      const ae = a3 * e2, af = a3 * f2, be2 = b2 * e2, bf = b2 * f2;
      te2[0] = c2 * e2;
      te2[4] = be2 * d2 - af;
      te2[8] = ae * d2 + bf;
      te2[1] = c2 * f2;
      te2[5] = bf * d2 + ae;
      te2[9] = af * d2 - be2;
      te2[2] = -d2;
      te2[6] = b2 * c2;
      te2[10] = a3 * c2;
    } else if (euler.order === "YZX") {
      const ac = a3 * c2, ad = a3 * d2, bc = b2 * c2, bd = b2 * d2;
      te2[0] = c2 * e2;
      te2[4] = bd - ac * f2;
      te2[8] = bc * f2 + ad;
      te2[1] = f2;
      te2[5] = a3 * e2;
      te2[9] = -b2 * e2;
      te2[2] = -d2 * e2;
      te2[6] = ad * f2 + bc;
      te2[10] = ac - bd * f2;
    } else if (euler.order === "XZY") {
      const ac = a3 * c2, ad = a3 * d2, bc = b2 * c2, bd = b2 * d2;
      te2[0] = c2 * e2;
      te2[4] = -f2;
      te2[8] = d2 * e2;
      te2[1] = ac * f2 + bd;
      te2[5] = a3 * e2;
      te2[9] = ad * f2 - bc;
      te2[2] = bc * f2 - ad;
      te2[6] = b2 * e2;
      te2[10] = bd * f2 + ac;
    }
    te2[3] = 0;
    te2[7] = 0;
    te2[11] = 0;
    te2[12] = 0;
    te2[13] = 0;
    te2[14] = 0;
    te2[15] = 1;
    return this;
  }
  makeRotationFromQuaternion(q3) {
    return this.compose(_zero, q3, _one);
  }
  lookAt(eye, target, up) {
    const te2 = this.elements;
    _z.subVectors(eye, target);
    if (_z.lengthSq() === 0) {
      _z.z = 1;
    }
    _z.normalize();
    _x.crossVectors(up, _z);
    if (_x.lengthSq() === 0) {
      if (Math.abs(up.z) === 1) {
        _z.x += 1e-4;
      } else {
        _z.z += 1e-4;
      }
      _z.normalize();
      _x.crossVectors(up, _z);
    }
    _x.normalize();
    _y.crossVectors(_z, _x);
    te2[0] = _x.x;
    te2[4] = _y.x;
    te2[8] = _z.x;
    te2[1] = _x.y;
    te2[5] = _y.y;
    te2[9] = _z.y;
    te2[2] = _x.z;
    te2[6] = _y.z;
    te2[10] = _z.z;
    return this;
  }
  multiply(m2) {
    return this.multiplyMatrices(this, m2);
  }
  premultiply(m2) {
    return this.multiplyMatrices(m2, this);
  }
  multiplyMatrices(a3, b2) {
    const ae = a3.elements;
    const be2 = b2.elements;
    const te2 = this.elements;
    const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
    const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
    const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
    const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
    const b11 = be2[0], b12 = be2[4], b13 = be2[8], b14 = be2[12];
    const b21 = be2[1], b22 = be2[5], b23 = be2[9], b24 = be2[13];
    const b31 = be2[2], b32 = be2[6], b33 = be2[10], b34 = be2[14];
    const b41 = be2[3], b42 = be2[7], b43 = be2[11], b44 = be2[15];
    te2[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
    te2[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
    te2[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
    te2[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
    te2[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
    te2[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
    te2[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
    te2[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
    te2[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
    te2[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
    te2[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
    te2[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
    te2[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
    te2[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
    te2[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
    te2[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
    return this;
  }
  multiplyScalar(s2) {
    const te2 = this.elements;
    te2[0] *= s2;
    te2[4] *= s2;
    te2[8] *= s2;
    te2[12] *= s2;
    te2[1] *= s2;
    te2[5] *= s2;
    te2[9] *= s2;
    te2[13] *= s2;
    te2[2] *= s2;
    te2[6] *= s2;
    te2[10] *= s2;
    te2[14] *= s2;
    te2[3] *= s2;
    te2[7] *= s2;
    te2[11] *= s2;
    te2[15] *= s2;
    return this;
  }
  determinant() {
    const te2 = this.elements;
    const n11 = te2[0], n12 = te2[4], n13 = te2[8], n14 = te2[12];
    const n21 = te2[1], n22 = te2[5], n23 = te2[9], n24 = te2[13];
    const n31 = te2[2], n32 = te2[6], n33 = te2[10], n34 = te2[14];
    const n41 = te2[3], n42 = te2[7], n43 = te2[11], n44 = te2[15];
    return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  }
  transpose() {
    const te2 = this.elements;
    let tmp2;
    tmp2 = te2[1];
    te2[1] = te2[4];
    te2[4] = tmp2;
    tmp2 = te2[2];
    te2[2] = te2[8];
    te2[8] = tmp2;
    tmp2 = te2[6];
    te2[6] = te2[9];
    te2[9] = tmp2;
    tmp2 = te2[3];
    te2[3] = te2[12];
    te2[12] = tmp2;
    tmp2 = te2[7];
    te2[7] = te2[13];
    te2[13] = tmp2;
    tmp2 = te2[11];
    te2[11] = te2[14];
    te2[14] = tmp2;
    return this;
  }
  setPosition(x, y2, z2) {
    const te2 = this.elements;
    if (x.isVector3) {
      te2[12] = x.x;
      te2[13] = x.y;
      te2[14] = x.z;
    } else {
      te2[12] = x;
      te2[13] = y2;
      te2[14] = z2;
    }
    return this;
  }
  invert() {
    const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n41 = te2[3], n12 = te2[4], n22 = te2[5], n32 = te2[6], n42 = te2[7], n13 = te2[8], n23 = te2[9], n33 = te2[10], n43 = te2[11], n14 = te2[12], n24 = te2[13], n34 = te2[14], n44 = te2[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
    const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
    if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const detInv = 1 / det;
    te2[0] = t11 * detInv;
    te2[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
    te2[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
    te2[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
    te2[4] = t12 * detInv;
    te2[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
    te2[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
    te2[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
    te2[8] = t13 * detInv;
    te2[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
    te2[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
    te2[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
    te2[12] = t14 * detInv;
    te2[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
    te2[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
    te2[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
    return this;
  }
  scale(v5) {
    const te2 = this.elements;
    const x = v5.x, y2 = v5.y, z2 = v5.z;
    te2[0] *= x;
    te2[4] *= y2;
    te2[8] *= z2;
    te2[1] *= x;
    te2[5] *= y2;
    te2[9] *= z2;
    te2[2] *= x;
    te2[6] *= y2;
    te2[10] *= z2;
    te2[3] *= x;
    te2[7] *= y2;
    te2[11] *= z2;
    return this;
  }
  getMaxScaleOnAxis() {
    const te2 = this.elements;
    const scaleXSq = te2[0] * te2[0] + te2[1] * te2[1] + te2[2] * te2[2];
    const scaleYSq = te2[4] * te2[4] + te2[5] * te2[5] + te2[6] * te2[6];
    const scaleZSq = te2[8] * te2[8] + te2[9] * te2[9] + te2[10] * te2[10];
    return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  }
  makeTranslation(x, y2, z2) {
    if (x.isVector3) {
      this.set(
        1,
        0,
        0,
        x.x,
        0,
        1,
        0,
        x.y,
        0,
        0,
        1,
        x.z,
        0,
        0,
        0,
        1
      );
    } else {
      this.set(
        1,
        0,
        0,
        x,
        0,
        1,
        0,
        y2,
        0,
        0,
        1,
        z2,
        0,
        0,
        0,
        1
      );
    }
    return this;
  }
  makeRotationX(theta) {
    const c2 = Math.cos(theta), s2 = Math.sin(theta);
    this.set(
      1,
      0,
      0,
      0,
      0,
      c2,
      -s2,
      0,
      0,
      s2,
      c2,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeRotationY(theta) {
    const c2 = Math.cos(theta), s2 = Math.sin(theta);
    this.set(
      c2,
      0,
      s2,
      0,
      0,
      1,
      0,
      0,
      -s2,
      0,
      c2,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeRotationZ(theta) {
    const c2 = Math.cos(theta), s2 = Math.sin(theta);
    this.set(
      c2,
      -s2,
      0,
      0,
      s2,
      c2,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeRotationAxis(axis, angle) {
    const c2 = Math.cos(angle);
    const s2 = Math.sin(angle);
    const t2 = 1 - c2;
    const x = axis.x, y2 = axis.y, z2 = axis.z;
    const tx = t2 * x, ty = t2 * y2;
    this.set(
      tx * x + c2,
      tx * y2 - s2 * z2,
      tx * z2 + s2 * y2,
      0,
      tx * y2 + s2 * z2,
      ty * y2 + c2,
      ty * z2 - s2 * x,
      0,
      tx * z2 - s2 * y2,
      ty * z2 + s2 * x,
      t2 * z2 * z2 + c2,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeScale(x, y2, z2) {
    this.set(
      x,
      0,
      0,
      0,
      0,
      y2,
      0,
      0,
      0,
      0,
      z2,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  makeShear(xy, xz, yx, yz, zx, zy) {
    this.set(
      1,
      yx,
      zx,
      0,
      xy,
      1,
      zy,
      0,
      xz,
      yz,
      1,
      0,
      0,
      0,
      0,
      1
    );
    return this;
  }
  compose(position, quaternion, scale) {
    const te2 = this.elements;
    const x = quaternion._x, y2 = quaternion._y, z2 = quaternion._z, w2 = quaternion._w;
    const x2 = x + x, y22 = y2 + y2, z22 = z2 + z2;
    const xx = x * x2, xy = x * y22, xz = x * z22;
    const yy = y2 * y22, yz = y2 * z22, zz = z2 * z22;
    const wx = w2 * x2, wy = w2 * y22, wz = w2 * z22;
    const sx = scale.x, sy = scale.y, sz = scale.z;
    te2[0] = (1 - (yy + zz)) * sx;
    te2[1] = (xy + wz) * sx;
    te2[2] = (xz - wy) * sx;
    te2[3] = 0;
    te2[4] = (xy - wz) * sy;
    te2[5] = (1 - (xx + zz)) * sy;
    te2[6] = (yz + wx) * sy;
    te2[7] = 0;
    te2[8] = (xz + wy) * sz;
    te2[9] = (yz - wx) * sz;
    te2[10] = (1 - (xx + yy)) * sz;
    te2[11] = 0;
    te2[12] = position.x;
    te2[13] = position.y;
    te2[14] = position.z;
    te2[15] = 1;
    return this;
  }
  decompose(position, quaternion, scale) {
    const te2 = this.elements;
    let sx = _v1$5.set(te2[0], te2[1], te2[2]).length();
    const sy = _v1$5.set(te2[4], te2[5], te2[6]).length();
    const sz = _v1$5.set(te2[8], te2[9], te2[10]).length();
    const det = this.determinant();
    if (det < 0) sx = -sx;
    position.x = te2[12];
    position.y = te2[13];
    position.z = te2[14];
    _m1$2.copy(this);
    const invSX = 1 / sx;
    const invSY = 1 / sy;
    const invSZ = 1 / sz;
    _m1$2.elements[0] *= invSX;
    _m1$2.elements[1] *= invSX;
    _m1$2.elements[2] *= invSX;
    _m1$2.elements[4] *= invSY;
    _m1$2.elements[5] *= invSY;
    _m1$2.elements[6] *= invSY;
    _m1$2.elements[8] *= invSZ;
    _m1$2.elements[9] *= invSZ;
    _m1$2.elements[10] *= invSZ;
    quaternion.setFromRotationMatrix(_m1$2);
    scale.x = sx;
    scale.y = sy;
    scale.z = sz;
    return this;
  }
  makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) {
    const te2 = this.elements;
    const x = 2 * near / (right - left);
    const y2 = 2 * near / (top - bottom);
    const a3 = (right + left) / (right - left);
    const b2 = (top + bottom) / (top - bottom);
    let c2, d2;
    if (coordinateSystem === WebGLCoordinateSystem) {
      c2 = -(far + near) / (far - near);
      d2 = -2 * far * near / (far - near);
    } else if (coordinateSystem === WebGPUCoordinateSystem) {
      c2 = -far / (far - near);
      d2 = -far * near / (far - near);
    } else {
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem);
    }
    te2[0] = x;
    te2[4] = 0;
    te2[8] = a3;
    te2[12] = 0;
    te2[1] = 0;
    te2[5] = y2;
    te2[9] = b2;
    te2[13] = 0;
    te2[2] = 0;
    te2[6] = 0;
    te2[10] = c2;
    te2[14] = d2;
    te2[3] = 0;
    te2[7] = 0;
    te2[11] = -1;
    te2[15] = 0;
    return this;
  }
  makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) {
    const te2 = this.elements;
    const w2 = 1 / (right - left);
    const h2 = 1 / (top - bottom);
    const p2 = 1 / (far - near);
    const x = (right + left) * w2;
    const y2 = (top + bottom) * h2;
    let z2, zInv;
    if (coordinateSystem === WebGLCoordinateSystem) {
      z2 = (far + near) * p2;
      zInv = -2 * p2;
    } else if (coordinateSystem === WebGPUCoordinateSystem) {
      z2 = near * p2;
      zInv = -1 * p2;
    } else {
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem);
    }
    te2[0] = 2 * w2;
    te2[4] = 0;
    te2[8] = 0;
    te2[12] = -x;
    te2[1] = 0;
    te2[5] = 2 * h2;
    te2[9] = 0;
    te2[13] = -y2;
    te2[2] = 0;
    te2[6] = 0;
    te2[10] = zInv;
    te2[14] = -z2;
    te2[3] = 0;
    te2[7] = 0;
    te2[11] = 0;
    te2[15] = 1;
    return this;
  }
  equals(matrix) {
    const te2 = this.elements;
    const me2 = matrix.elements;
    for (let i2 = 0; i2 < 16; i2++) {
      if (te2[i2] !== me2[i2]) return false;
    }
    return true;
  }
  fromArray(array, offset = 0) {
    for (let i2 = 0; i2 < 16; i2++) {
      this.elements[i2] = array[i2 + offset];
    }
    return this;
  }
  toArray(array = [], offset = 0) {
    const te2 = this.elements;
    array[offset] = te2[0];
    array[offset + 1] = te2[1];
    array[offset + 2] = te2[2];
    array[offset + 3] = te2[3];
    array[offset + 4] = te2[4];
    array[offset + 5] = te2[5];
    array[offset + 6] = te2[6];
    array[offset + 7] = te2[7];
    array[offset + 8] = te2[8];
    array[offset + 9] = te2[9];
    array[offset + 10] = te2[10];
    array[offset + 11] = te2[11];
    array[offset + 12] = te2[12];
    array[offset + 13] = te2[13];
    array[offset + 14] = te2[14];
    array[offset + 15] = te2[15];
    return array;
  }
}
const _v1$5 = /* @__PURE__ */ new Vector3();
const _m1$2 = /* @__PURE__ */ new Matrix4();
const _zero = /* @__PURE__ */ new Vector3(0, 0, 0);
const _one = /* @__PURE__ */ new Vector3(1, 1, 1);
const _x = /* @__PURE__ */ new Vector3();
const _y = /* @__PURE__ */ new Vector3();
const _z = /* @__PURE__ */ new Vector3();
const _matrix$2 = /* @__PURE__ */ new Matrix4();
const _quaternion$3 = /* @__PURE__ */ new Quaternion();
class Euler {
  constructor(x = 0, y2 = 0, z2 = 0, order = Euler.DEFAULT_ORDER) {
    this.isEuler = true;
    this._x = x;
    this._y = y2;
    this._z = z2;
    this._order = order;
  }
  get x() {
    return this._x;
  }
  set x(value) {
    this._x = value;
    this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(value) {
    this._y = value;
    this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(value) {
    this._z = value;
    this._onChangeCallback();
  }
  get order() {
    return this._order;
  }
  set order(value) {
    this._order = value;
    this._onChangeCallback();
  }
  set(x, y2, z2, order = this._order) {
    this._x = x;
    this._y = y2;
    this._z = z2;
    this._order = order;
    this._onChangeCallback();
    return this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  copy(euler) {
    this._x = euler._x;
    this._y = euler._y;
    this._z = euler._z;
    this._order = euler._order;
    this._onChangeCallback();
    return this;
  }
  setFromRotationMatrix(m2, order = this._order, update = true) {
    const te2 = m2.elements;
    const m11 = te2[0], m12 = te2[4], m13 = te2[8];
    const m21 = te2[1], m22 = te2[5], m23 = te2[9];
    const m31 = te2[2], m32 = te2[6], m33 = te2[10];
    switch (order) {
      case "XYZ":
        this._y = Math.asin(clamp(m13, -1, 1));
        if (Math.abs(m13) < 0.9999999) {
          this._x = Math.atan2(-m23, m33);
          this._z = Math.atan2(-m12, m11);
        } else {
          this._x = Math.atan2(m32, m22);
          this._z = 0;
        }
        break;
      case "YXZ":
        this._x = Math.asin(-clamp(m23, -1, 1));
        if (Math.abs(m23) < 0.9999999) {
          this._y = Math.atan2(m13, m33);
          this._z = Math.atan2(m21, m22);
        } else {
          this._y = Math.atan2(-m31, m11);
          this._z = 0;
        }
        break;
      case "ZXY":
        this._x = Math.asin(clamp(m32, -1, 1));
        if (Math.abs(m32) < 0.9999999) {
          this._y = Math.atan2(-m31, m33);
          this._z = Math.atan2(-m12, m22);
        } else {
          this._y = 0;
          this._z = Math.atan2(m21, m11);
        }
        break;
      case "ZYX":
        this._y = Math.asin(-clamp(m31, -1, 1));
        if (Math.abs(m31) < 0.9999999) {
          this._x = Math.atan2(m32, m33);
          this._z = Math.atan2(m21, m11);
        } else {
          this._x = 0;
          this._z = Math.atan2(-m12, m22);
        }
        break;
      case "YZX":
        this._z = Math.asin(clamp(m21, -1, 1));
        if (Math.abs(m21) < 0.9999999) {
          this._x = Math.atan2(-m23, m22);
          this._y = Math.atan2(-m31, m11);
        } else {
          this._x = 0;
          this._y = Math.atan2(m13, m33);
        }
        break;
      case "XZY":
        this._z = Math.asin(-clamp(m12, -1, 1));
        if (Math.abs(m12) < 0.9999999) {
          this._x = Math.atan2(m32, m22);
          this._y = Math.atan2(m13, m11);
        } else {
          this._x = Math.atan2(-m23, m33);
          this._y = 0;
        }
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order);
    }
    this._order = order;
    if (update === true) this._onChangeCallback();
    return this;
  }
  setFromQuaternion(q3, order, update) {
    _matrix$2.makeRotationFromQuaternion(q3);
    return this.setFromRotationMatrix(_matrix$2, order, update);
  }
  setFromVector3(v5, order = this._order) {
    return this.set(v5.x, v5.y, v5.z, order);
  }
  reorder(newOrder) {
    _quaternion$3.setFromEuler(this);
    return this.setFromQuaternion(_quaternion$3, newOrder);
  }
  equals(euler) {
    return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  }
  fromArray(array) {
    this._x = array[0];
    this._y = array[1];
    this._z = array[2];
    if (array[3] !== void 0) this._order = array[3];
    this._onChangeCallback();
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this._x;
    array[offset + 1] = this._y;
    array[offset + 2] = this._z;
    array[offset + 3] = this._order;
    return array;
  }
  _onChange(callback) {
    this._onChangeCallback = callback;
    return this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x;
    yield this._y;
    yield this._z;
    yield this._order;
  }
}
Euler.DEFAULT_ORDER = "XYZ";
class Layers {
  constructor() {
    this.mask = 1 | 0;
  }
  set(channel) {
    this.mask = (1 << channel | 0) >>> 0;
  }
  enable(channel) {
    this.mask |= 1 << channel | 0;
  }
  enableAll() {
    this.mask = 4294967295 | 0;
  }
  toggle(channel) {
    this.mask ^= 1 << channel | 0;
  }
  disable(channel) {
    this.mask &= ~(1 << channel | 0);
  }
  disableAll() {
    this.mask = 0;
  }
  test(layers) {
    return (this.mask & layers.mask) !== 0;
  }
  isEnabled(channel) {
    return (this.mask & (1 << channel | 0)) !== 0;
  }
}
let _object3DId = 0;
const _v1$4 = /* @__PURE__ */ new Vector3();
const _q1 = /* @__PURE__ */ new Quaternion();
const _m1$1$1 = /* @__PURE__ */ new Matrix4();
const _target = /* @__PURE__ */ new Vector3();
const _position$3 = /* @__PURE__ */ new Vector3();
const _scale$2 = /* @__PURE__ */ new Vector3();
const _quaternion$2 = /* @__PURE__ */ new Quaternion();
const _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0);
const _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0);
const _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1);
const _addedEvent = { type: "added" };
const _removedEvent = { type: "removed" };
const _childaddedEvent = { type: "childadded", child: null };
const _childremovedEvent = { type: "childremoved", child: null };
class Object3D extends EventDispatcher$1 {
  constructor() {
    super();
    this.isObject3D = true;
    Object.defineProperty(this, "id", { value: _object3DId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "Object3D";
    this.parent = null;
    this.children = [];
    this.up = Object3D.DEFAULT_UP.clone();
    const position = new Vector3();
    const rotation = new Euler();
    const quaternion = new Quaternion();
    const scale = new Vector3(1, 1, 1);
    function onRotationChange() {
      quaternion.setFromEuler(rotation, false);
    }
    function onQuaternionChange() {
      rotation.setFromQuaternion(quaternion, void 0, false);
    }
    rotation._onChange(onRotationChange);
    quaternion._onChange(onQuaternionChange);
    Object.defineProperties(this, {
      position: {
        configurable: true,
        enumerable: true,
        value: position
      },
      rotation: {
        configurable: true,
        enumerable: true,
        value: rotation
      },
      quaternion: {
        configurable: true,
        enumerable: true,
        value: quaternion
      },
      scale: {
        configurable: true,
        enumerable: true,
        value: scale
      },
      modelViewMatrix: {
        value: new Matrix4()
      },
      normalMatrix: {
        value: new Matrix3()
      }
    });
    this.matrix = new Matrix4();
    this.matrixWorld = new Matrix4();
    this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
    this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE;
    this.matrixWorldNeedsUpdate = false;
    this.layers = new Layers();
    this.visible = true;
    this.castShadow = false;
    this.receiveShadow = false;
    this.frustumCulled = true;
    this.renderOrder = 0;
    this.animations = [];
    this.userData = {};
  }
  onBeforeShadow() {
  }
  onAfterShadow() {
  }
  onBeforeRender() {
  }
  onAfterRender() {
  }
  applyMatrix4(matrix) {
    if (this.matrixAutoUpdate) this.updateMatrix();
    this.matrix.premultiply(matrix);
    this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  applyQuaternion(q3) {
    this.quaternion.premultiply(q3);
    return this;
  }
  setRotationFromAxisAngle(axis, angle) {
    this.quaternion.setFromAxisAngle(axis, angle);
  }
  setRotationFromEuler(euler) {
    this.quaternion.setFromEuler(euler, true);
  }
  setRotationFromMatrix(m2) {
    this.quaternion.setFromRotationMatrix(m2);
  }
  setRotationFromQuaternion(q3) {
    this.quaternion.copy(q3);
  }
  rotateOnAxis(axis, angle) {
    _q1.setFromAxisAngle(axis, angle);
    this.quaternion.multiply(_q1);
    return this;
  }
  rotateOnWorldAxis(axis, angle) {
    _q1.setFromAxisAngle(axis, angle);
    this.quaternion.premultiply(_q1);
    return this;
  }
  rotateX(angle) {
    return this.rotateOnAxis(_xAxis, angle);
  }
  rotateY(angle) {
    return this.rotateOnAxis(_yAxis, angle);
  }
  rotateZ(angle) {
    return this.rotateOnAxis(_zAxis, angle);
  }
  translateOnAxis(axis, distance) {
    _v1$4.copy(axis).applyQuaternion(this.quaternion);
    this.position.add(_v1$4.multiplyScalar(distance));
    return this;
  }
  translateX(distance) {
    return this.translateOnAxis(_xAxis, distance);
  }
  translateY(distance) {
    return this.translateOnAxis(_yAxis, distance);
  }
  translateZ(distance) {
    return this.translateOnAxis(_zAxis, distance);
  }
  localToWorld(vector) {
    this.updateWorldMatrix(true, false);
    return vector.applyMatrix4(this.matrixWorld);
  }
  worldToLocal(vector) {
    this.updateWorldMatrix(true, false);
    return vector.applyMatrix4(_m1$1$1.copy(this.matrixWorld).invert());
  }
  lookAt(x, y2, z2) {
    if (x.isVector3) {
      _target.copy(x);
    } else {
      _target.set(x, y2, z2);
    }
    const parent = this.parent;
    this.updateWorldMatrix(true, false);
    _position$3.setFromMatrixPosition(this.matrixWorld);
    if (this.isCamera || this.isLight) {
      _m1$1$1.lookAt(_position$3, _target, this.up);
    } else {
      _m1$1$1.lookAt(_target, _position$3, this.up);
    }
    this.quaternion.setFromRotationMatrix(_m1$1$1);
    if (parent) {
      _m1$1$1.extractRotation(parent.matrixWorld);
      _q1.setFromRotationMatrix(_m1$1$1);
      this.quaternion.premultiply(_q1.invert());
    }
  }
  add(object) {
    if (arguments.length > 1) {
      for (let i2 = 0; i2 < arguments.length; i2++) {
        this.add(arguments[i2]);
      }
      return this;
    }
    if (object === this) {
      console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
      return this;
    }
    if (object && object.isObject3D) {
      object.removeFromParent();
      object.parent = this;
      this.children.push(object);
      object.dispatchEvent(_addedEvent);
      _childaddedEvent.child = object;
      this.dispatchEvent(_childaddedEvent);
      _childaddedEvent.child = null;
    } else {
      console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
    }
    return this;
  }
  remove(object) {
    if (arguments.length > 1) {
      for (let i2 = 0; i2 < arguments.length; i2++) {
        this.remove(arguments[i2]);
      }
      return this;
    }
    const index = this.children.indexOf(object);
    if (index !== -1) {
      object.parent = null;
      this.children.splice(index, 1);
      object.dispatchEvent(_removedEvent);
      _childremovedEvent.child = object;
      this.dispatchEvent(_childremovedEvent);
      _childremovedEvent.child = null;
    }
    return this;
  }
  removeFromParent() {
    const parent = this.parent;
    if (parent !== null) {
      parent.remove(this);
    }
    return this;
  }
  clear() {
    return this.remove(...this.children);
  }
  attach(object) {
    this.updateWorldMatrix(true, false);
    _m1$1$1.copy(this.matrixWorld).invert();
    if (object.parent !== null) {
      object.parent.updateWorldMatrix(true, false);
      _m1$1$1.multiply(object.parent.matrixWorld);
    }
    object.applyMatrix4(_m1$1$1);
    object.removeFromParent();
    object.parent = this;
    this.children.push(object);
    object.updateWorldMatrix(false, true);
    object.dispatchEvent(_addedEvent);
    _childaddedEvent.child = object;
    this.dispatchEvent(_childaddedEvent);
    _childaddedEvent.child = null;
    return this;
  }
  getObjectById(id) {
    return this.getObjectByProperty("id", id);
  }
  getObjectByName(name) {
    return this.getObjectByProperty("name", name);
  }
  getObjectByProperty(name, value) {
    if (this[name] === value) return this;
    for (let i2 = 0, l2 = this.children.length; i2 < l2; i2++) {
      const child = this.children[i2];
      const object = child.getObjectByProperty(name, value);
      if (object !== void 0) {
        return object;
      }
    }
    return void 0;
  }
  getObjectsByProperty(name, value, result = []) {
    if (this[name] === value) result.push(this);
    const children = this.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      children[i2].getObjectsByProperty(name, value, result);
    }
    return result;
  }
  getWorldPosition(target) {
    this.updateWorldMatrix(true, false);
    return target.setFromMatrixPosition(this.matrixWorld);
  }
  getWorldQuaternion(target) {
    this.updateWorldMatrix(true, false);
    this.matrixWorld.decompose(_position$3, target, _scale$2);
    return target;
  }
  getWorldScale(target) {
    this.updateWorldMatrix(true, false);
    this.matrixWorld.decompose(_position$3, _quaternion$2, target);
    return target;
  }
  getWorldDirection(target) {
    this.updateWorldMatrix(true, false);
    const e2 = this.matrixWorld.elements;
    return target.set(e2[8], e2[9], e2[10]).normalize();
  }
  raycast() {
  }
  traverse(callback) {
    callback(this);
    const children = this.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      children[i2].traverse(callback);
    }
  }
  traverseVisible(callback) {
    if (this.visible === false) return;
    callback(this);
    const children = this.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      children[i2].traverseVisible(callback);
    }
  }
  traverseAncestors(callback) {
    const parent = this.parent;
    if (parent !== null) {
      callback(parent);
      parent.traverseAncestors(callback);
    }
  }
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale);
    this.matrixWorldNeedsUpdate = true;
  }
  updateMatrixWorld(force) {
    if (this.matrixAutoUpdate) this.updateMatrix();
    if (this.matrixWorldNeedsUpdate || force) {
      if (this.matrixWorldAutoUpdate === true) {
        if (this.parent === null) {
          this.matrixWorld.copy(this.matrix);
        } else {
          this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
        }
      }
      this.matrixWorldNeedsUpdate = false;
      force = true;
    }
    const children = this.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      const child = children[i2];
      child.updateMatrixWorld(force);
    }
  }
  updateWorldMatrix(updateParents, updateChildren) {
    const parent = this.parent;
    if (updateParents === true && parent !== null) {
      parent.updateWorldMatrix(true, false);
    }
    if (this.matrixAutoUpdate) this.updateMatrix();
    if (this.matrixWorldAutoUpdate === true) {
      if (this.parent === null) {
        this.matrixWorld.copy(this.matrix);
      } else {
        this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
      }
    }
    if (updateChildren === true) {
      const children = this.children;
      for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
        const child = children[i2];
        child.updateWorldMatrix(false, true);
      }
    }
  }
  toJSON(meta2) {
    const isRootObject = meta2 === void 0 || typeof meta2 === "string";
    const output = {};
    if (isRootObject) {
      meta2 = {
        geometries: {},
        materials: {},
        textures: {},
        images: {},
        shapes: {},
        skeletons: {},
        animations: {},
        nodes: {}
      };
      output.metadata = {
        version: 4.6,
        type: "Object",
        generator: "Object3D.toJSON"
      };
    }
    const object = {};
    object.uuid = this.uuid;
    object.type = this.type;
    if (this.name !== "") object.name = this.name;
    if (this.castShadow === true) object.castShadow = true;
    if (this.receiveShadow === true) object.receiveShadow = true;
    if (this.visible === false) object.visible = false;
    if (this.frustumCulled === false) object.frustumCulled = false;
    if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
    if (Object.keys(this.userData).length > 0) object.userData = this.userData;
    object.layers = this.layers.mask;
    object.matrix = this.matrix.toArray();
    object.up = this.up.toArray();
    if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false;
    if (this.isInstancedMesh) {
      object.type = "InstancedMesh";
      object.count = this.count;
      object.instanceMatrix = this.instanceMatrix.toJSON();
      if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
    }
    if (this.isBatchedMesh) {
      object.type = "BatchedMesh";
      object.perObjectFrustumCulled = this.perObjectFrustumCulled;
      object.sortObjects = this.sortObjects;
      object.drawRanges = this._drawRanges;
      object.reservedRanges = this._reservedRanges;
      object.visibility = this._visibility;
      object.active = this._active;
      object.bounds = this._bounds.map((bound) => ({
        boxInitialized: bound.boxInitialized,
        boxMin: bound.box.min.toArray(),
        boxMax: bound.box.max.toArray(),
        sphereInitialized: bound.sphereInitialized,
        sphereRadius: bound.sphere.radius,
        sphereCenter: bound.sphere.center.toArray()
      }));
      object.maxInstanceCount = this._maxInstanceCount;
      object.maxVertexCount = this._maxVertexCount;
      object.maxIndexCount = this._maxIndexCount;
      object.geometryInitialized = this._geometryInitialized;
      object.geometryCount = this._geometryCount;
      object.matricesTexture = this._matricesTexture.toJSON(meta2);
      if (this._colorsTexture !== null) object.colorsTexture = this._colorsTexture.toJSON(meta2);
      if (this.boundingSphere !== null) {
        object.boundingSphere = {
          center: object.boundingSphere.center.toArray(),
          radius: object.boundingSphere.radius
        };
      }
      if (this.boundingBox !== null) {
        object.boundingBox = {
          min: object.boundingBox.min.toArray(),
          max: object.boundingBox.max.toArray()
        };
      }
    }
    function serialize(library, element) {
      if (library[element.uuid] === void 0) {
        library[element.uuid] = element.toJSON(meta2);
      }
      return element.uuid;
    }
    if (this.isScene) {
      if (this.background) {
        if (this.background.isColor) {
          object.background = this.background.toJSON();
        } else if (this.background.isTexture) {
          object.background = this.background.toJSON(meta2).uuid;
        }
      }
      if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
        object.environment = this.environment.toJSON(meta2).uuid;
      }
    } else if (this.isMesh || this.isLine || this.isPoints) {
      object.geometry = serialize(meta2.geometries, this.geometry);
      const parameters = this.geometry.parameters;
      if (parameters !== void 0 && parameters.shapes !== void 0) {
        const shapes = parameters.shapes;
        if (Array.isArray(shapes)) {
          for (let i2 = 0, l2 = shapes.length; i2 < l2; i2++) {
            const shape = shapes[i2];
            serialize(meta2.shapes, shape);
          }
        } else {
          serialize(meta2.shapes, shapes);
        }
      }
    }
    if (this.isSkinnedMesh) {
      object.bindMode = this.bindMode;
      object.bindMatrix = this.bindMatrix.toArray();
      if (this.skeleton !== void 0) {
        serialize(meta2.skeletons, this.skeleton);
        object.skeleton = this.skeleton.uuid;
      }
    }
    if (this.material !== void 0) {
      if (Array.isArray(this.material)) {
        const uuids = [];
        for (let i2 = 0, l2 = this.material.length; i2 < l2; i2++) {
          uuids.push(serialize(meta2.materials, this.material[i2]));
        }
        object.material = uuids;
      } else {
        object.material = serialize(meta2.materials, this.material);
      }
    }
    if (this.children.length > 0) {
      object.children = [];
      for (let i2 = 0; i2 < this.children.length; i2++) {
        object.children.push(this.children[i2].toJSON(meta2).object);
      }
    }
    if (this.animations.length > 0) {
      object.animations = [];
      for (let i2 = 0; i2 < this.animations.length; i2++) {
        const animation = this.animations[i2];
        object.animations.push(serialize(meta2.animations, animation));
      }
    }
    if (isRootObject) {
      const geometries = extractFromCache(meta2.geometries);
      const materials = extractFromCache(meta2.materials);
      const textures = extractFromCache(meta2.textures);
      const images = extractFromCache(meta2.images);
      const shapes = extractFromCache(meta2.shapes);
      const skeletons = extractFromCache(meta2.skeletons);
      const animations = extractFromCache(meta2.animations);
      const nodes = extractFromCache(meta2.nodes);
      if (geometries.length > 0) output.geometries = geometries;
      if (materials.length > 0) output.materials = materials;
      if (textures.length > 0) output.textures = textures;
      if (images.length > 0) output.images = images;
      if (shapes.length > 0) output.shapes = shapes;
      if (skeletons.length > 0) output.skeletons = skeletons;
      if (animations.length > 0) output.animations = animations;
      if (nodes.length > 0) output.nodes = nodes;
    }
    output.object = object;
    return output;
    function extractFromCache(cache) {
      const values = [];
      for (const key in cache) {
        const data = cache[key];
        delete data.metadata;
        values.push(data);
      }
      return values;
    }
  }
  clone(recursive) {
    return new this.constructor().copy(this, recursive);
  }
  copy(source, recursive = true) {
    this.name = source.name;
    this.up.copy(source.up);
    this.position.copy(source.position);
    this.rotation.order = source.rotation.order;
    this.quaternion.copy(source.quaternion);
    this.scale.copy(source.scale);
    this.matrix.copy(source.matrix);
    this.matrixWorld.copy(source.matrixWorld);
    this.matrixAutoUpdate = source.matrixAutoUpdate;
    this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
    this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
    this.layers.mask = source.layers.mask;
    this.visible = source.visible;
    this.castShadow = source.castShadow;
    this.receiveShadow = source.receiveShadow;
    this.frustumCulled = source.frustumCulled;
    this.renderOrder = source.renderOrder;
    this.animations = source.animations.slice();
    this.userData = JSON.parse(JSON.stringify(source.userData));
    if (recursive === true) {
      for (let i2 = 0; i2 < source.children.length; i2++) {
        const child = source.children[i2];
        this.add(child.clone());
      }
    }
    return this;
  }
}
Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0);
Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
const _v0$1 = /* @__PURE__ */ new Vector3();
const _v1$3 = /* @__PURE__ */ new Vector3();
const _v2$2 = /* @__PURE__ */ new Vector3();
const _v3$2 = /* @__PURE__ */ new Vector3();
const _vab = /* @__PURE__ */ new Vector3();
const _vac = /* @__PURE__ */ new Vector3();
const _vbc = /* @__PURE__ */ new Vector3();
const _vap = /* @__PURE__ */ new Vector3();
const _vbp = /* @__PURE__ */ new Vector3();
const _vcp = /* @__PURE__ */ new Vector3();
const _v40 = /* @__PURE__ */ new Vector4();
const _v41 = /* @__PURE__ */ new Vector4();
const _v42 = /* @__PURE__ */ new Vector4();
class Triangle {
  constructor(a3 = new Vector3(), b2 = new Vector3(), c2 = new Vector3()) {
    this.a = a3;
    this.b = b2;
    this.c = c2;
  }
  static getNormal(a3, b2, c2, target) {
    target.subVectors(c2, b2);
    _v0$1.subVectors(a3, b2);
    target.cross(_v0$1);
    const targetLengthSq = target.lengthSq();
    if (targetLengthSq > 0) {
      return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
    }
    return target.set(0, 0, 0);
  }
  // static/instance method to calculate barycentric coordinates
  // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  static getBarycoord(point, a3, b2, c2, target) {
    _v0$1.subVectors(c2, a3);
    _v1$3.subVectors(b2, a3);
    _v2$2.subVectors(point, a3);
    const dot00 = _v0$1.dot(_v0$1);
    const dot01 = _v0$1.dot(_v1$3);
    const dot02 = _v0$1.dot(_v2$2);
    const dot11 = _v1$3.dot(_v1$3);
    const dot12 = _v1$3.dot(_v2$2);
    const denom = dot00 * dot11 - dot01 * dot01;
    if (denom === 0) {
      target.set(0, 0, 0);
      return null;
    }
    const invDenom = 1 / denom;
    const u2 = (dot11 * dot02 - dot01 * dot12) * invDenom;
    const v5 = (dot00 * dot12 - dot01 * dot02) * invDenom;
    return target.set(1 - u2 - v5, v5, u2);
  }
  static containsPoint(point, a3, b2, c2) {
    if (this.getBarycoord(point, a3, b2, c2, _v3$2) === null) {
      return false;
    }
    return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1;
  }
  static getInterpolation(point, p1, p2, p3, v12, v22, v32, target) {
    if (this.getBarycoord(point, p1, p2, p3, _v3$2) === null) {
      target.x = 0;
      target.y = 0;
      if ("z" in target) target.z = 0;
      if ("w" in target) target.w = 0;
      return null;
    }
    target.setScalar(0);
    target.addScaledVector(v12, _v3$2.x);
    target.addScaledVector(v22, _v3$2.y);
    target.addScaledVector(v32, _v3$2.z);
    return target;
  }
  static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) {
    _v40.setScalar(0);
    _v41.setScalar(0);
    _v42.setScalar(0);
    _v40.fromBufferAttribute(attr, i1);
    _v41.fromBufferAttribute(attr, i2);
    _v42.fromBufferAttribute(attr, i3);
    target.setScalar(0);
    target.addScaledVector(_v40, barycoord.x);
    target.addScaledVector(_v41, barycoord.y);
    target.addScaledVector(_v42, barycoord.z);
    return target;
  }
  static isFrontFacing(a3, b2, c2, direction) {
    _v0$1.subVectors(c2, b2);
    _v1$3.subVectors(a3, b2);
    return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  }
  set(a3, b2, c2) {
    this.a.copy(a3);
    this.b.copy(b2);
    this.c.copy(c2);
    return this;
  }
  setFromPointsAndIndices(points, i0, i1, i2) {
    this.a.copy(points[i0]);
    this.b.copy(points[i1]);
    this.c.copy(points[i2]);
    return this;
  }
  setFromAttributeAndIndices(attribute, i0, i1, i2) {
    this.a.fromBufferAttribute(attribute, i0);
    this.b.fromBufferAttribute(attribute, i1);
    this.c.fromBufferAttribute(attribute, i2);
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(triangle) {
    this.a.copy(triangle.a);
    this.b.copy(triangle.b);
    this.c.copy(triangle.c);
    return this;
  }
  getArea() {
    _v0$1.subVectors(this.c, this.b);
    _v1$3.subVectors(this.a, this.b);
    return _v0$1.cross(_v1$3).length() * 0.5;
  }
  getMidpoint(target) {
    return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  }
  getNormal(target) {
    return Triangle.getNormal(this.a, this.b, this.c, target);
  }
  getPlane(target) {
    return target.setFromCoplanarPoints(this.a, this.b, this.c);
  }
  getBarycoord(point, target) {
    return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  }
  getInterpolation(point, v12, v22, v32, target) {
    return Triangle.getInterpolation(point, this.a, this.b, this.c, v12, v22, v32, target);
  }
  containsPoint(point) {
    return Triangle.containsPoint(point, this.a, this.b, this.c);
  }
  isFrontFacing(direction) {
    return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  }
  intersectsBox(box) {
    return box.intersectsTriangle(this);
  }
  closestPointToPoint(p2, target) {
    const a3 = this.a, b2 = this.b, c2 = this.c;
    let v5, w2;
    _vab.subVectors(b2, a3);
    _vac.subVectors(c2, a3);
    _vap.subVectors(p2, a3);
    const d1 = _vab.dot(_vap);
    const d2 = _vac.dot(_vap);
    if (d1 <= 0 && d2 <= 0) {
      return target.copy(a3);
    }
    _vbp.subVectors(p2, b2);
    const d3 = _vab.dot(_vbp);
    const d4 = _vac.dot(_vbp);
    if (d3 >= 0 && d4 <= d3) {
      return target.copy(b2);
    }
    const vc = d1 * d4 - d3 * d2;
    if (vc <= 0 && d1 >= 0 && d3 <= 0) {
      v5 = d1 / (d1 - d3);
      return target.copy(a3).addScaledVector(_vab, v5);
    }
    _vcp.subVectors(p2, c2);
    const d5 = _vab.dot(_vcp);
    const d6 = _vac.dot(_vcp);
    if (d6 >= 0 && d5 <= d6) {
      return target.copy(c2);
    }
    const vb = d5 * d2 - d1 * d6;
    if (vb <= 0 && d2 >= 0 && d6 <= 0) {
      w2 = d2 / (d2 - d6);
      return target.copy(a3).addScaledVector(_vac, w2);
    }
    const va = d3 * d6 - d5 * d4;
    if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
      _vbc.subVectors(c2, b2);
      w2 = (d4 - d3) / (d4 - d3 + (d5 - d6));
      return target.copy(b2).addScaledVector(_vbc, w2);
    }
    const denom = 1 / (va + vb + vc);
    v5 = vb * denom;
    w2 = vc * denom;
    return target.copy(a3).addScaledVector(_vab, v5).addScaledVector(_vac, w2);
  }
  equals(triangle) {
    return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  }
}
const _colorKeywords = {
  "aliceblue": 15792383,
  "antiquewhite": 16444375,
  "aqua": 65535,
  "aquamarine": 8388564,
  "azure": 15794175,
  "beige": 16119260,
  "bisque": 16770244,
  "black": 0,
  "blanchedalmond": 16772045,
  "blue": 255,
  "blueviolet": 9055202,
  "brown": 10824234,
  "burlywood": 14596231,
  "cadetblue": 6266528,
  "chartreuse": 8388352,
  "chocolate": 13789470,
  "coral": 16744272,
  "cornflowerblue": 6591981,
  "cornsilk": 16775388,
  "crimson": 14423100,
  "cyan": 65535,
  "darkblue": 139,
  "darkcyan": 35723,
  "darkgoldenrod": 12092939,
  "darkgray": 11119017,
  "darkgreen": 25600,
  "darkgrey": 11119017,
  "darkkhaki": 12433259,
  "darkmagenta": 9109643,
  "darkolivegreen": 5597999,
  "darkorange": 16747520,
  "darkorchid": 10040012,
  "darkred": 9109504,
  "darksalmon": 15308410,
  "darkseagreen": 9419919,
  "darkslateblue": 4734347,
  "darkslategray": 3100495,
  "darkslategrey": 3100495,
  "darkturquoise": 52945,
  "darkviolet": 9699539,
  "deeppink": 16716947,
  "deepskyblue": 49151,
  "dimgray": 6908265,
  "dimgrey": 6908265,
  "dodgerblue": 2003199,
  "firebrick": 11674146,
  "floralwhite": 16775920,
  "forestgreen": 2263842,
  "fuchsia": 16711935,
  "gainsboro": 14474460,
  "ghostwhite": 16316671,
  "gold": 16766720,
  "goldenrod": 14329120,
  "gray": 8421504,
  "green": 32768,
  "greenyellow": 11403055,
  "grey": 8421504,
  "honeydew": 15794160,
  "hotpink": 16738740,
  "indianred": 13458524,
  "indigo": 4915330,
  "ivory": 16777200,
  "khaki": 15787660,
  "lavender": 15132410,
  "lavenderblush": 16773365,
  "lawngreen": 8190976,
  "lemonchiffon": 16775885,
  "lightblue": 11393254,
  "lightcoral": 15761536,
  "lightcyan": 14745599,
  "lightgoldenrodyellow": 16448210,
  "lightgray": 13882323,
  "lightgreen": 9498256,
  "lightgrey": 13882323,
  "lightpink": 16758465,
  "lightsalmon": 16752762,
  "lightseagreen": 2142890,
  "lightskyblue": 8900346,
  "lightslategray": 7833753,
  "lightslategrey": 7833753,
  "lightsteelblue": 11584734,
  "lightyellow": 16777184,
  "lime": 65280,
  "limegreen": 3329330,
  "linen": 16445670,
  "magenta": 16711935,
  "maroon": 8388608,
  "mediumaquamarine": 6737322,
  "mediumblue": 205,
  "mediumorchid": 12211667,
  "mediumpurple": 9662683,
  "mediumseagreen": 3978097,
  "mediumslateblue": 8087790,
  "mediumspringgreen": 64154,
  "mediumturquoise": 4772300,
  "mediumvioletred": 13047173,
  "midnightblue": 1644912,
  "mintcream": 16121850,
  "mistyrose": 16770273,
  "moccasin": 16770229,
  "navajowhite": 16768685,
  "navy": 128,
  "oldlace": 16643558,
  "olive": 8421376,
  "olivedrab": 7048739,
  "orange": 16753920,
  "orangered": 16729344,
  "orchid": 14315734,
  "palegoldenrod": 15657130,
  "palegreen": 10025880,
  "paleturquoise": 11529966,
  "palevioletred": 14381203,
  "papayawhip": 16773077,
  "peachpuff": 16767673,
  "peru": 13468991,
  "pink": 16761035,
  "plum": 14524637,
  "powderblue": 11591910,
  "purple": 8388736,
  "rebeccapurple": 6697881,
  "red": 16711680,
  "rosybrown": 12357519,
  "royalblue": 4286945,
  "saddlebrown": 9127187,
  "salmon": 16416882,
  "sandybrown": 16032864,
  "seagreen": 3050327,
  "seashell": 16774638,
  "sienna": 10506797,
  "silver": 12632256,
  "skyblue": 8900331,
  "slateblue": 6970061,
  "slategray": 7372944,
  "slategrey": 7372944,
  "snow": 16775930,
  "springgreen": 65407,
  "steelblue": 4620980,
  "tan": 13808780,
  "teal": 32896,
  "thistle": 14204888,
  "tomato": 16737095,
  "turquoise": 4251856,
  "violet": 15631086,
  "wheat": 16113331,
  "white": 16777215,
  "whitesmoke": 16119285,
  "yellow": 16776960,
  "yellowgreen": 10145074
};
const _hslA = { h: 0, s: 0, l: 0 };
const _hslB = { h: 0, s: 0, l: 0 };
function hue2rgb(p2, q3, t2) {
  if (t2 < 0) t2 += 1;
  if (t2 > 1) t2 -= 1;
  if (t2 < 1 / 6) return p2 + (q3 - p2) * 6 * t2;
  if (t2 < 1 / 2) return q3;
  if (t2 < 2 / 3) return p2 + (q3 - p2) * 6 * (2 / 3 - t2);
  return p2;
}
class Color {
  constructor(r2, g2, b2) {
    this.isColor = true;
    this.r = 1;
    this.g = 1;
    this.b = 1;
    return this.set(r2, g2, b2);
  }
  set(r2, g2, b2) {
    if (g2 === void 0 && b2 === void 0) {
      const value = r2;
      if (value && value.isColor) {
        this.copy(value);
      } else if (typeof value === "number") {
        this.setHex(value);
      } else if (typeof value === "string") {
        this.setStyle(value);
      }
    } else {
      this.setRGB(r2, g2, b2);
    }
    return this;
  }
  setScalar(scalar) {
    this.r = scalar;
    this.g = scalar;
    this.b = scalar;
    return this;
  }
  setHex(hex2, colorSpace = SRGBColorSpace) {
    hex2 = Math.floor(hex2);
    this.r = (hex2 >> 16 & 255) / 255;
    this.g = (hex2 >> 8 & 255) / 255;
    this.b = (hex2 & 255) / 255;
    ColorManagement.toWorkingColorSpace(this, colorSpace);
    return this;
  }
  setRGB(r2, g2, b2, colorSpace = ColorManagement.workingColorSpace) {
    this.r = r2;
    this.g = g2;
    this.b = b2;
    ColorManagement.toWorkingColorSpace(this, colorSpace);
    return this;
  }
  setHSL(h2, s2, l2, colorSpace = ColorManagement.workingColorSpace) {
    h2 = euclideanModulo(h2, 1);
    s2 = clamp(s2, 0, 1);
    l2 = clamp(l2, 0, 1);
    if (s2 === 0) {
      this.r = this.g = this.b = l2;
    } else {
      const p2 = l2 <= 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2;
      const q3 = 2 * l2 - p2;
      this.r = hue2rgb(q3, p2, h2 + 1 / 3);
      this.g = hue2rgb(q3, p2, h2);
      this.b = hue2rgb(q3, p2, h2 - 1 / 3);
    }
    ColorManagement.toWorkingColorSpace(this, colorSpace);
    return this;
  }
  setStyle(style, colorSpace = SRGBColorSpace) {
    function handleAlpha(string) {
      if (string === void 0) return;
      if (parseFloat(string) < 1) {
        console.warn("THREE.Color: Alpha component of " + style + " will be ignored.");
      }
    }
    let m2;
    if (m2 = /^(\w+)\(([^\)]*)\)/.exec(style)) {
      let color;
      const name = m2[1];
      const components = m2[2];
      switch (name) {
        case "rgb":
        case "rgba":
          if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color[4]);
            return this.setRGB(
              Math.min(255, parseInt(color[1], 10)) / 255,
              Math.min(255, parseInt(color[2], 10)) / 255,
              Math.min(255, parseInt(color[3], 10)) / 255,
              colorSpace
            );
          }
          if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color[4]);
            return this.setRGB(
              Math.min(100, parseInt(color[1], 10)) / 100,
              Math.min(100, parseInt(color[2], 10)) / 100,
              Math.min(100, parseInt(color[3], 10)) / 100,
              colorSpace
            );
          }
          break;
        case "hsl":
        case "hsla":
          if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color[4]);
            return this.setHSL(
              parseFloat(color[1]) / 360,
              parseFloat(color[2]) / 100,
              parseFloat(color[3]) / 100,
              colorSpace
            );
          }
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + style);
      }
    } else if (m2 = /^\#([A-Fa-f\d]+)$/.exec(style)) {
      const hex2 = m2[1];
      const size = hex2.length;
      if (size === 3) {
        return this.setRGB(
          parseInt(hex2.charAt(0), 16) / 15,
          parseInt(hex2.charAt(1), 16) / 15,
          parseInt(hex2.charAt(2), 16) / 15,
          colorSpace
        );
      } else if (size === 6) {
        return this.setHex(parseInt(hex2, 16), colorSpace);
      } else {
        console.warn("THREE.Color: Invalid hex color " + style);
      }
    } else if (style && style.length > 0) {
      return this.setColorName(style, colorSpace);
    }
    return this;
  }
  setColorName(style, colorSpace = SRGBColorSpace) {
    const hex2 = _colorKeywords[style.toLowerCase()];
    if (hex2 !== void 0) {
      this.setHex(hex2, colorSpace);
    } else {
      console.warn("THREE.Color: Unknown color " + style);
    }
    return this;
  }
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  copy(color) {
    this.r = color.r;
    this.g = color.g;
    this.b = color.b;
    return this;
  }
  copySRGBToLinear(color) {
    this.r = SRGBToLinear(color.r);
    this.g = SRGBToLinear(color.g);
    this.b = SRGBToLinear(color.b);
    return this;
  }
  copyLinearToSRGB(color) {
    this.r = LinearToSRGB(color.r);
    this.g = LinearToSRGB(color.g);
    this.b = LinearToSRGB(color.b);
    return this;
  }
  convertSRGBToLinear() {
    this.copySRGBToLinear(this);
    return this;
  }
  convertLinearToSRGB() {
    this.copyLinearToSRGB(this);
    return this;
  }
  getHex(colorSpace = SRGBColorSpace) {
    ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace);
    return Math.round(clamp(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp(_color.g * 255, 0, 255)) * 256 + Math.round(clamp(_color.b * 255, 0, 255));
  }
  getHexString(colorSpace = SRGBColorSpace) {
    return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6);
  }
  getHSL(target, colorSpace = ColorManagement.workingColorSpace) {
    ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace);
    const r2 = _color.r, g2 = _color.g, b2 = _color.b;
    const max2 = Math.max(r2, g2, b2);
    const min = Math.min(r2, g2, b2);
    let hue, saturation;
    const lightness = (min + max2) / 2;
    if (min === max2) {
      hue = 0;
      saturation = 0;
    } else {
      const delta = max2 - min;
      saturation = lightness <= 0.5 ? delta / (max2 + min) : delta / (2 - max2 - min);
      switch (max2) {
        case r2:
          hue = (g2 - b2) / delta + (g2 < b2 ? 6 : 0);
          break;
        case g2:
          hue = (b2 - r2) / delta + 2;
          break;
        case b2:
          hue = (r2 - g2) / delta + 4;
          break;
      }
      hue /= 6;
    }
    target.h = hue;
    target.s = saturation;
    target.l = lightness;
    return target;
  }
  getRGB(target, colorSpace = ColorManagement.workingColorSpace) {
    ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace);
    target.r = _color.r;
    target.g = _color.g;
    target.b = _color.b;
    return target;
  }
  getStyle(colorSpace = SRGBColorSpace) {
    ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace);
    const r2 = _color.r, g2 = _color.g, b2 = _color.b;
    if (colorSpace !== SRGBColorSpace) {
      return `color(${colorSpace} ${r2.toFixed(3)} ${g2.toFixed(3)} ${b2.toFixed(3)})`;
    }
    return `rgb(${Math.round(r2 * 255)},${Math.round(g2 * 255)},${Math.round(b2 * 255)})`;
  }
  offsetHSL(h2, s2, l2) {
    this.getHSL(_hslA);
    return this.setHSL(_hslA.h + h2, _hslA.s + s2, _hslA.l + l2);
  }
  add(color) {
    this.r += color.r;
    this.g += color.g;
    this.b += color.b;
    return this;
  }
  addColors(color1, color2) {
    this.r = color1.r + color2.r;
    this.g = color1.g + color2.g;
    this.b = color1.b + color2.b;
    return this;
  }
  addScalar(s2) {
    this.r += s2;
    this.g += s2;
    this.b += s2;
    return this;
  }
  sub(color) {
    this.r = Math.max(0, this.r - color.r);
    this.g = Math.max(0, this.g - color.g);
    this.b = Math.max(0, this.b - color.b);
    return this;
  }
  multiply(color) {
    this.r *= color.r;
    this.g *= color.g;
    this.b *= color.b;
    return this;
  }
  multiplyScalar(s2) {
    this.r *= s2;
    this.g *= s2;
    this.b *= s2;
    return this;
  }
  lerp(color, alpha) {
    this.r += (color.r - this.r) * alpha;
    this.g += (color.g - this.g) * alpha;
    this.b += (color.b - this.b) * alpha;
    return this;
  }
  lerpColors(color1, color2, alpha) {
    this.r = color1.r + (color2.r - color1.r) * alpha;
    this.g = color1.g + (color2.g - color1.g) * alpha;
    this.b = color1.b + (color2.b - color1.b) * alpha;
    return this;
  }
  lerpHSL(color, alpha) {
    this.getHSL(_hslA);
    color.getHSL(_hslB);
    const h2 = lerp(_hslA.h, _hslB.h, alpha);
    const s2 = lerp(_hslA.s, _hslB.s, alpha);
    const l2 = lerp(_hslA.l, _hslB.l, alpha);
    this.setHSL(h2, s2, l2);
    return this;
  }
  setFromVector3(v5) {
    this.r = v5.x;
    this.g = v5.y;
    this.b = v5.z;
    return this;
  }
  applyMatrix3(m2) {
    const r2 = this.r, g2 = this.g, b2 = this.b;
    const e2 = m2.elements;
    this.r = e2[0] * r2 + e2[3] * g2 + e2[6] * b2;
    this.g = e2[1] * r2 + e2[4] * g2 + e2[7] * b2;
    this.b = e2[2] * r2 + e2[5] * g2 + e2[8] * b2;
    return this;
  }
  equals(c2) {
    return c2.r === this.r && c2.g === this.g && c2.b === this.b;
  }
  fromArray(array, offset = 0) {
    this.r = array[offset];
    this.g = array[offset + 1];
    this.b = array[offset + 2];
    return this;
  }
  toArray(array = [], offset = 0) {
    array[offset] = this.r;
    array[offset + 1] = this.g;
    array[offset + 2] = this.b;
    return array;
  }
  fromBufferAttribute(attribute, index) {
    this.r = attribute.getX(index);
    this.g = attribute.getY(index);
    this.b = attribute.getZ(index);
    return this;
  }
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r;
    yield this.g;
    yield this.b;
  }
}
const _color = /* @__PURE__ */ new Color();
Color.NAMES = _colorKeywords;
let _materialId = 0;
class Material extends EventDispatcher$1 {
  constructor() {
    super();
    this.isMaterial = true;
    Object.defineProperty(this, "id", { value: _materialId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "Material";
    this.blending = NormalBlending;
    this.side = FrontSide;
    this.vertexColors = false;
    this.opacity = 1;
    this.transparent = false;
    this.alphaHash = false;
    this.blendSrc = SrcAlphaFactor;
    this.blendDst = OneMinusSrcAlphaFactor;
    this.blendEquation = AddEquation;
    this.blendSrcAlpha = null;
    this.blendDstAlpha = null;
    this.blendEquationAlpha = null;
    this.blendColor = new Color(0, 0, 0);
    this.blendAlpha = 0;
    this.depthFunc = LessEqualDepth;
    this.depthTest = true;
    this.depthWrite = true;
    this.stencilWriteMask = 255;
    this.stencilFunc = AlwaysStencilFunc;
    this.stencilRef = 0;
    this.stencilFuncMask = 255;
    this.stencilFail = KeepStencilOp;
    this.stencilZFail = KeepStencilOp;
    this.stencilZPass = KeepStencilOp;
    this.stencilWrite = false;
    this.clippingPlanes = null;
    this.clipIntersection = false;
    this.clipShadows = false;
    this.shadowSide = null;
    this.colorWrite = true;
    this.precision = null;
    this.polygonOffset = false;
    this.polygonOffsetFactor = 0;
    this.polygonOffsetUnits = 0;
    this.dithering = false;
    this.alphaToCoverage = false;
    this.premultipliedAlpha = false;
    this.forceSinglePass = false;
    this.visible = true;
    this.toneMapped = true;
    this.userData = {};
    this.version = 0;
    this._alphaTest = 0;
  }
  get alphaTest() {
    return this._alphaTest;
  }
  set alphaTest(value) {
    if (this._alphaTest > 0 !== value > 0) {
      this.version++;
    }
    this._alphaTest = value;
  }
  // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  onBeforeRender() {
  }
  onBeforeCompile() {
  }
  customProgramCacheKey() {
    return this.onBeforeCompile.toString();
  }
  setValues(values) {
    if (values === void 0) return;
    for (const key in values) {
      const newValue = values[key];
      if (newValue === void 0) {
        console.warn(`THREE.Material: parameter '${key}' has value of undefined.`);
        continue;
      }
      const currentValue = this[key];
      if (currentValue === void 0) {
        console.warn(`THREE.Material: '${key}' is not a property of THREE.${this.type}.`);
        continue;
      }
      if (currentValue && currentValue.isColor) {
        currentValue.set(newValue);
      } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) {
        currentValue.copy(newValue);
      } else {
        this[key] = newValue;
      }
    }
  }
  toJSON(meta2) {
    const isRootObject = meta2 === void 0 || typeof meta2 === "string";
    if (isRootObject) {
      meta2 = {
        textures: {},
        images: {}
      };
    }
    const data = {
      metadata: {
        version: 4.6,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    data.uuid = this.uuid;
    data.type = this.type;
    if (this.name !== "") data.name = this.name;
    if (this.color && this.color.isColor) data.color = this.color.getHex();
    if (this.roughness !== void 0) data.roughness = this.roughness;
    if (this.metalness !== void 0) data.metalness = this.metalness;
    if (this.sheen !== void 0) data.sheen = this.sheen;
    if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
    if (this.sheenRoughness !== void 0) data.sheenRoughness = this.sheenRoughness;
    if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
    if (this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
    if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
    if (this.specularIntensity !== void 0) data.specularIntensity = this.specularIntensity;
    if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
    if (this.shininess !== void 0) data.shininess = this.shininess;
    if (this.clearcoat !== void 0) data.clearcoat = this.clearcoat;
    if (this.clearcoatRoughness !== void 0) data.clearcoatRoughness = this.clearcoatRoughness;
    if (this.clearcoatMap && this.clearcoatMap.isTexture) {
      data.clearcoatMap = this.clearcoatMap.toJSON(meta2).uuid;
    }
    if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
      data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta2).uuid;
    }
    if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
      data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta2).uuid;
      data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
    }
    if (this.dispersion !== void 0) data.dispersion = this.dispersion;
    if (this.iridescence !== void 0) data.iridescence = this.iridescence;
    if (this.iridescenceIOR !== void 0) data.iridescenceIOR = this.iridescenceIOR;
    if (this.iridescenceThicknessRange !== void 0) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
    if (this.iridescenceMap && this.iridescenceMap.isTexture) {
      data.iridescenceMap = this.iridescenceMap.toJSON(meta2).uuid;
    }
    if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
      data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta2).uuid;
    }
    if (this.anisotropy !== void 0) data.anisotropy = this.anisotropy;
    if (this.anisotropyRotation !== void 0) data.anisotropyRotation = this.anisotropyRotation;
    if (this.anisotropyMap && this.anisotropyMap.isTexture) {
      data.anisotropyMap = this.anisotropyMap.toJSON(meta2).uuid;
    }
    if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta2).uuid;
    if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta2).uuid;
    if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta2).uuid;
    if (this.lightMap && this.lightMap.isTexture) {
      data.lightMap = this.lightMap.toJSON(meta2).uuid;
      data.lightMapIntensity = this.lightMapIntensity;
    }
    if (this.aoMap && this.aoMap.isTexture) {
      data.aoMap = this.aoMap.toJSON(meta2).uuid;
      data.aoMapIntensity = this.aoMapIntensity;
    }
    if (this.bumpMap && this.bumpMap.isTexture) {
      data.bumpMap = this.bumpMap.toJSON(meta2).uuid;
      data.bumpScale = this.bumpScale;
    }
    if (this.normalMap && this.normalMap.isTexture) {
      data.normalMap = this.normalMap.toJSON(meta2).uuid;
      data.normalMapType = this.normalMapType;
      data.normalScale = this.normalScale.toArray();
    }
    if (this.displacementMap && this.displacementMap.isTexture) {
      data.displacementMap = this.displacementMap.toJSON(meta2).uuid;
      data.displacementScale = this.displacementScale;
      data.displacementBias = this.displacementBias;
    }
    if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta2).uuid;
    if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta2).uuid;
    if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta2).uuid;
    if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta2).uuid;
    if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta2).uuid;
    if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta2).uuid;
    if (this.envMap && this.envMap.isTexture) {
      data.envMap = this.envMap.toJSON(meta2).uuid;
      if (this.combine !== void 0) data.combine = this.combine;
    }
    if (this.envMapRotation !== void 0) data.envMapRotation = this.envMapRotation.toArray();
    if (this.envMapIntensity !== void 0) data.envMapIntensity = this.envMapIntensity;
    if (this.reflectivity !== void 0) data.reflectivity = this.reflectivity;
    if (this.refractionRatio !== void 0) data.refractionRatio = this.refractionRatio;
    if (this.gradientMap && this.gradientMap.isTexture) {
      data.gradientMap = this.gradientMap.toJSON(meta2).uuid;
    }
    if (this.transmission !== void 0) data.transmission = this.transmission;
    if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta2).uuid;
    if (this.thickness !== void 0) data.thickness = this.thickness;
    if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta2).uuid;
    if (this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance;
    if (this.attenuationColor !== void 0) data.attenuationColor = this.attenuationColor.getHex();
    if (this.size !== void 0) data.size = this.size;
    if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
    if (this.sizeAttenuation !== void 0) data.sizeAttenuation = this.sizeAttenuation;
    if (this.blending !== NormalBlending) data.blending = this.blending;
    if (this.side !== FrontSide) data.side = this.side;
    if (this.vertexColors === true) data.vertexColors = true;
    if (this.opacity < 1) data.opacity = this.opacity;
    if (this.transparent === true) data.transparent = true;
    if (this.blendSrc !== SrcAlphaFactor) data.blendSrc = this.blendSrc;
    if (this.blendDst !== OneMinusSrcAlphaFactor) data.blendDst = this.blendDst;
    if (this.blendEquation !== AddEquation) data.blendEquation = this.blendEquation;
    if (this.blendSrcAlpha !== null) data.blendSrcAlpha = this.blendSrcAlpha;
    if (this.blendDstAlpha !== null) data.blendDstAlpha = this.blendDstAlpha;
    if (this.blendEquationAlpha !== null) data.blendEquationAlpha = this.blendEquationAlpha;
    if (this.blendColor && this.blendColor.isColor) data.blendColor = this.blendColor.getHex();
    if (this.blendAlpha !== 0) data.blendAlpha = this.blendAlpha;
    if (this.depthFunc !== LessEqualDepth) data.depthFunc = this.depthFunc;
    if (this.depthTest === false) data.depthTest = this.depthTest;
    if (this.depthWrite === false) data.depthWrite = this.depthWrite;
    if (this.colorWrite === false) data.colorWrite = this.colorWrite;
    if (this.stencilWriteMask !== 255) data.stencilWriteMask = this.stencilWriteMask;
    if (this.stencilFunc !== AlwaysStencilFunc) data.stencilFunc = this.stencilFunc;
    if (this.stencilRef !== 0) data.stencilRef = this.stencilRef;
    if (this.stencilFuncMask !== 255) data.stencilFuncMask = this.stencilFuncMask;
    if (this.stencilFail !== KeepStencilOp) data.stencilFail = this.stencilFail;
    if (this.stencilZFail !== KeepStencilOp) data.stencilZFail = this.stencilZFail;
    if (this.stencilZPass !== KeepStencilOp) data.stencilZPass = this.stencilZPass;
    if (this.stencilWrite === true) data.stencilWrite = this.stencilWrite;
    if (this.rotation !== void 0 && this.rotation !== 0) data.rotation = this.rotation;
    if (this.polygonOffset === true) data.polygonOffset = true;
    if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
    if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
    if (this.linewidth !== void 0 && this.linewidth !== 1) data.linewidth = this.linewidth;
    if (this.dashSize !== void 0) data.dashSize = this.dashSize;
    if (this.gapSize !== void 0) data.gapSize = this.gapSize;
    if (this.scale !== void 0) data.scale = this.scale;
    if (this.dithering === true) data.dithering = true;
    if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
    if (this.alphaHash === true) data.alphaHash = true;
    if (this.alphaToCoverage === true) data.alphaToCoverage = true;
    if (this.premultipliedAlpha === true) data.premultipliedAlpha = true;
    if (this.forceSinglePass === true) data.forceSinglePass = true;
    if (this.wireframe === true) data.wireframe = true;
    if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
    if (this.wireframeLinecap !== "round") data.wireframeLinecap = this.wireframeLinecap;
    if (this.wireframeLinejoin !== "round") data.wireframeLinejoin = this.wireframeLinejoin;
    if (this.flatShading === true) data.flatShading = true;
    if (this.visible === false) data.visible = false;
    if (this.toneMapped === false) data.toneMapped = false;
    if (this.fog === false) data.fog = false;
    if (Object.keys(this.userData).length > 0) data.userData = this.userData;
    function extractFromCache(cache) {
      const values = [];
      for (const key in cache) {
        const data2 = cache[key];
        delete data2.metadata;
        values.push(data2);
      }
      return values;
    }
    if (isRootObject) {
      const textures = extractFromCache(meta2.textures);
      const images = extractFromCache(meta2.images);
      if (textures.length > 0) data.textures = textures;
      if (images.length > 0) data.images = images;
    }
    return data;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.name = source.name;
    this.blending = source.blending;
    this.side = source.side;
    this.vertexColors = source.vertexColors;
    this.opacity = source.opacity;
    this.transparent = source.transparent;
    this.blendSrc = source.blendSrc;
    this.blendDst = source.blendDst;
    this.blendEquation = source.blendEquation;
    this.blendSrcAlpha = source.blendSrcAlpha;
    this.blendDstAlpha = source.blendDstAlpha;
    this.blendEquationAlpha = source.blendEquationAlpha;
    this.blendColor.copy(source.blendColor);
    this.blendAlpha = source.blendAlpha;
    this.depthFunc = source.depthFunc;
    this.depthTest = source.depthTest;
    this.depthWrite = source.depthWrite;
    this.stencilWriteMask = source.stencilWriteMask;
    this.stencilFunc = source.stencilFunc;
    this.stencilRef = source.stencilRef;
    this.stencilFuncMask = source.stencilFuncMask;
    this.stencilFail = source.stencilFail;
    this.stencilZFail = source.stencilZFail;
    this.stencilZPass = source.stencilZPass;
    this.stencilWrite = source.stencilWrite;
    const srcPlanes = source.clippingPlanes;
    let dstPlanes = null;
    if (srcPlanes !== null) {
      const n2 = srcPlanes.length;
      dstPlanes = new Array(n2);
      for (let i2 = 0; i2 !== n2; ++i2) {
        dstPlanes[i2] = srcPlanes[i2].clone();
      }
    }
    this.clippingPlanes = dstPlanes;
    this.clipIntersection = source.clipIntersection;
    this.clipShadows = source.clipShadows;
    this.shadowSide = source.shadowSide;
    this.colorWrite = source.colorWrite;
    this.precision = source.precision;
    this.polygonOffset = source.polygonOffset;
    this.polygonOffsetFactor = source.polygonOffsetFactor;
    this.polygonOffsetUnits = source.polygonOffsetUnits;
    this.dithering = source.dithering;
    this.alphaTest = source.alphaTest;
    this.alphaHash = source.alphaHash;
    this.alphaToCoverage = source.alphaToCoverage;
    this.premultipliedAlpha = source.premultipliedAlpha;
    this.forceSinglePass = source.forceSinglePass;
    this.visible = source.visible;
    this.toneMapped = source.toneMapped;
    this.userData = JSON.parse(JSON.stringify(source.userData));
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  set needsUpdate(value) {
    if (value === true) this.version++;
  }
  onBuild() {
    console.warn("Material: onBuild() has been removed.");
  }
}
class MeshBasicMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshBasicMaterial = true;
    this.type = "MeshBasicMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.specularMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler();
    this.combine = MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.specularMap = source.specularMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.combine = source.combine;
    this.reflectivity = source.reflectivity;
    this.refractionRatio = source.refractionRatio;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.fog = source.fog;
    return this;
  }
}
const _tables = /* @__PURE__ */ _generateTables();
function _generateTables() {
  const buffer = new ArrayBuffer(4);
  const floatView = new Float32Array(buffer);
  const uint32View = new Uint32Array(buffer);
  const baseTable = new Uint32Array(512);
  const shiftTable = new Uint32Array(512);
  for (let i2 = 0; i2 < 256; ++i2) {
    const e2 = i2 - 127;
    if (e2 < -27) {
      baseTable[i2] = 0;
      baseTable[i2 | 256] = 32768;
      shiftTable[i2] = 24;
      shiftTable[i2 | 256] = 24;
    } else if (e2 < -14) {
      baseTable[i2] = 1024 >> -e2 - 14;
      baseTable[i2 | 256] = 1024 >> -e2 - 14 | 32768;
      shiftTable[i2] = -e2 - 1;
      shiftTable[i2 | 256] = -e2 - 1;
    } else if (e2 <= 15) {
      baseTable[i2] = e2 + 15 << 10;
      baseTable[i2 | 256] = e2 + 15 << 10 | 32768;
      shiftTable[i2] = 13;
      shiftTable[i2 | 256] = 13;
    } else if (e2 < 128) {
      baseTable[i2] = 31744;
      baseTable[i2 | 256] = 64512;
      shiftTable[i2] = 24;
      shiftTable[i2 | 256] = 24;
    } else {
      baseTable[i2] = 31744;
      baseTable[i2 | 256] = 64512;
      shiftTable[i2] = 13;
      shiftTable[i2 | 256] = 13;
    }
  }
  const mantissaTable = new Uint32Array(2048);
  const exponentTable = new Uint32Array(64);
  const offsetTable = new Uint32Array(64);
  for (let i2 = 1; i2 < 1024; ++i2) {
    let m2 = i2 << 13;
    let e2 = 0;
    while ((m2 & 8388608) === 0) {
      m2 <<= 1;
      e2 -= 8388608;
    }
    m2 &= -8388609;
    e2 += 947912704;
    mantissaTable[i2] = m2 | e2;
  }
  for (let i2 = 1024; i2 < 2048; ++i2) {
    mantissaTable[i2] = 939524096 + (i2 - 1024 << 13);
  }
  for (let i2 = 1; i2 < 31; ++i2) {
    exponentTable[i2] = i2 << 23;
  }
  exponentTable[31] = 1199570944;
  exponentTable[32] = 2147483648;
  for (let i2 = 33; i2 < 63; ++i2) {
    exponentTable[i2] = 2147483648 + (i2 - 32 << 23);
  }
  exponentTable[63] = 3347054592;
  for (let i2 = 1; i2 < 64; ++i2) {
    if (i2 !== 32) {
      offsetTable[i2] = 1024;
    }
  }
  return {
    floatView,
    uint32View,
    baseTable,
    shiftTable,
    mantissaTable,
    exponentTable,
    offsetTable
  };
}
function toHalfFloat(val) {
  if (Math.abs(val) > 65504) console.warn("THREE.DataUtils.toHalfFloat(): Value out of range.");
  val = clamp(val, -65504, 65504);
  _tables.floatView[0] = val;
  const f2 = _tables.uint32View[0];
  const e2 = f2 >> 23 & 511;
  return _tables.baseTable[e2] + ((f2 & 8388607) >> _tables.shiftTable[e2]);
}
function fromHalfFloat(val) {
  const m2 = val >> 10;
  _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m2] + (val & 1023)] + _tables.exponentTable[m2];
  return _tables.floatView[0];
}
const DataUtils = {
  toHalfFloat,
  fromHalfFloat
};
const _vector$9 = /* @__PURE__ */ new Vector3();
const _vector2$1 = /* @__PURE__ */ new Vector2();
class BufferAttribute {
  constructor(array, itemSize, normalized = false) {
    if (Array.isArray(array)) {
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    }
    this.isBufferAttribute = true;
    this.name = "";
    this.array = array;
    this.itemSize = itemSize;
    this.count = array !== void 0 ? array.length / itemSize : 0;
    this.normalized = normalized;
    this.usage = StaticDrawUsage;
    this.updateRanges = [];
    this.gpuType = FloatType;
    this.version = 0;
  }
  onUploadCallback() {
  }
  set needsUpdate(value) {
    if (value === true) this.version++;
  }
  setUsage(value) {
    this.usage = value;
    return this;
  }
  addUpdateRange(start, count) {
    this.updateRanges.push({ start, count });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(source) {
    this.name = source.name;
    this.array = new source.array.constructor(source.array);
    this.itemSize = source.itemSize;
    this.count = source.count;
    this.normalized = source.normalized;
    this.usage = source.usage;
    this.gpuType = source.gpuType;
    return this;
  }
  copyAt(index1, attribute, index2) {
    index1 *= this.itemSize;
    index2 *= attribute.itemSize;
    for (let i2 = 0, l2 = this.itemSize; i2 < l2; i2++) {
      this.array[index1 + i2] = attribute.array[index2 + i2];
    }
    return this;
  }
  copyArray(array) {
    this.array.set(array);
    return this;
  }
  applyMatrix3(m2) {
    if (this.itemSize === 2) {
      for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
        _vector2$1.fromBufferAttribute(this, i2);
        _vector2$1.applyMatrix3(m2);
        this.setXY(i2, _vector2$1.x, _vector2$1.y);
      }
    } else if (this.itemSize === 3) {
      for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
        _vector$9.fromBufferAttribute(this, i2);
        _vector$9.applyMatrix3(m2);
        this.setXYZ(i2, _vector$9.x, _vector$9.y, _vector$9.z);
      }
    }
    return this;
  }
  applyMatrix4(m2) {
    for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
      _vector$9.fromBufferAttribute(this, i2);
      _vector$9.applyMatrix4(m2);
      this.setXYZ(i2, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  applyNormalMatrix(m2) {
    for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
      _vector$9.fromBufferAttribute(this, i2);
      _vector$9.applyNormalMatrix(m2);
      this.setXYZ(i2, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  transformDirection(m2) {
    for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
      _vector$9.fromBufferAttribute(this, i2);
      _vector$9.transformDirection(m2);
      this.setXYZ(i2, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  set(value, offset = 0) {
    this.array.set(value, offset);
    return this;
  }
  getComponent(index, component) {
    let value = this.array[index * this.itemSize + component];
    if (this.normalized) value = denormalize(value, this.array);
    return value;
  }
  setComponent(index, component, value) {
    if (this.normalized) value = normalize(value, this.array);
    this.array[index * this.itemSize + component] = value;
    return this;
  }
  getX(index) {
    let x = this.array[index * this.itemSize];
    if (this.normalized) x = denormalize(x, this.array);
    return x;
  }
  setX(index, x) {
    if (this.normalized) x = normalize(x, this.array);
    this.array[index * this.itemSize] = x;
    return this;
  }
  getY(index) {
    let y2 = this.array[index * this.itemSize + 1];
    if (this.normalized) y2 = denormalize(y2, this.array);
    return y2;
  }
  setY(index, y2) {
    if (this.normalized) y2 = normalize(y2, this.array);
    this.array[index * this.itemSize + 1] = y2;
    return this;
  }
  getZ(index) {
    let z2 = this.array[index * this.itemSize + 2];
    if (this.normalized) z2 = denormalize(z2, this.array);
    return z2;
  }
  setZ(index, z2) {
    if (this.normalized) z2 = normalize(z2, this.array);
    this.array[index * this.itemSize + 2] = z2;
    return this;
  }
  getW(index) {
    let w2 = this.array[index * this.itemSize + 3];
    if (this.normalized) w2 = denormalize(w2, this.array);
    return w2;
  }
  setW(index, w2) {
    if (this.normalized) w2 = normalize(w2, this.array);
    this.array[index * this.itemSize + 3] = w2;
    return this;
  }
  setXY(index, x, y2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
    }
    this.array[index + 0] = x;
    this.array[index + 1] = y2;
    return this;
  }
  setXYZ(index, x, y2, z2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
    }
    this.array[index + 0] = x;
    this.array[index + 1] = y2;
    this.array[index + 2] = z2;
    return this;
  }
  setXYZW(index, x, y2, z2, w2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
      w2 = normalize(w2, this.array);
    }
    this.array[index + 0] = x;
    this.array[index + 1] = y2;
    this.array[index + 2] = z2;
    this.array[index + 3] = w2;
    return this;
  }
  onUpload(callback) {
    this.onUploadCallback = callback;
    return this;
  }
  clone() {
    return new this.constructor(this.array, this.itemSize).copy(this);
  }
  toJSON() {
    const data = {
      itemSize: this.itemSize,
      type: this.array.constructor.name,
      array: Array.from(this.array),
      normalized: this.normalized
    };
    if (this.name !== "") data.name = this.name;
    if (this.usage !== StaticDrawUsage) data.usage = this.usage;
    return data;
  }
}
class Int8BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Int8Array(array), itemSize, normalized);
  }
}
class Uint8BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Uint8Array(array), itemSize, normalized);
  }
}
class Uint8ClampedBufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Uint8ClampedArray(array), itemSize, normalized);
  }
}
class Int16BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Int16Array(array), itemSize, normalized);
  }
}
class Uint16BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Uint16Array(array), itemSize, normalized);
  }
}
class Int32BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Int32Array(array), itemSize, normalized);
  }
}
class Uint32BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Uint32Array(array), itemSize, normalized);
  }
}
class Float16BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Uint16Array(array), itemSize, normalized);
    this.isFloat16BufferAttribute = true;
  }
  getX(index) {
    let x = fromHalfFloat(this.array[index * this.itemSize]);
    if (this.normalized) x = denormalize(x, this.array);
    return x;
  }
  setX(index, x) {
    if (this.normalized) x = normalize(x, this.array);
    this.array[index * this.itemSize] = toHalfFloat(x);
    return this;
  }
  getY(index) {
    let y2 = fromHalfFloat(this.array[index * this.itemSize + 1]);
    if (this.normalized) y2 = denormalize(y2, this.array);
    return y2;
  }
  setY(index, y2) {
    if (this.normalized) y2 = normalize(y2, this.array);
    this.array[index * this.itemSize + 1] = toHalfFloat(y2);
    return this;
  }
  getZ(index) {
    let z2 = fromHalfFloat(this.array[index * this.itemSize + 2]);
    if (this.normalized) z2 = denormalize(z2, this.array);
    return z2;
  }
  setZ(index, z2) {
    if (this.normalized) z2 = normalize(z2, this.array);
    this.array[index * this.itemSize + 2] = toHalfFloat(z2);
    return this;
  }
  getW(index) {
    let w2 = fromHalfFloat(this.array[index * this.itemSize + 3]);
    if (this.normalized) w2 = denormalize(w2, this.array);
    return w2;
  }
  setW(index, w2) {
    if (this.normalized) w2 = normalize(w2, this.array);
    this.array[index * this.itemSize + 3] = toHalfFloat(w2);
    return this;
  }
  setXY(index, x, y2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
    }
    this.array[index + 0] = toHalfFloat(x);
    this.array[index + 1] = toHalfFloat(y2);
    return this;
  }
  setXYZ(index, x, y2, z2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
    }
    this.array[index + 0] = toHalfFloat(x);
    this.array[index + 1] = toHalfFloat(y2);
    this.array[index + 2] = toHalfFloat(z2);
    return this;
  }
  setXYZW(index, x, y2, z2, w2) {
    index *= this.itemSize;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
      w2 = normalize(w2, this.array);
    }
    this.array[index + 0] = toHalfFloat(x);
    this.array[index + 1] = toHalfFloat(y2);
    this.array[index + 2] = toHalfFloat(z2);
    this.array[index + 3] = toHalfFloat(w2);
    return this;
  }
}
class Float32BufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized) {
    super(new Float32Array(array), itemSize, normalized);
  }
}
let _id$1 = 0;
const _m1$3 = /* @__PURE__ */ new Matrix4();
const _obj = /* @__PURE__ */ new Object3D();
const _offset = /* @__PURE__ */ new Vector3();
const _box$2 = /* @__PURE__ */ new Box3();
const _boxMorphTargets = /* @__PURE__ */ new Box3();
const _vector$8 = /* @__PURE__ */ new Vector3();
class BufferGeometry extends EventDispatcher$1 {
  constructor() {
    super();
    this.isBufferGeometry = true;
    Object.defineProperty(this, "id", { value: _id$1++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "BufferGeometry";
    this.index = null;
    this.indirect = null;
    this.attributes = {};
    this.morphAttributes = {};
    this.morphTargetsRelative = false;
    this.groups = [];
    this.boundingBox = null;
    this.boundingSphere = null;
    this.drawRange = { start: 0, count: Infinity };
    this.userData = {};
  }
  getIndex() {
    return this.index;
  }
  setIndex(index) {
    if (Array.isArray(index)) {
      this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
    } else {
      this.index = index;
    }
    return this;
  }
  setIndirect(indirect) {
    this.indirect = indirect;
    return this;
  }
  getIndirect() {
    return this.indirect;
  }
  getAttribute(name) {
    return this.attributes[name];
  }
  setAttribute(name, attribute) {
    this.attributes[name] = attribute;
    return this;
  }
  deleteAttribute(name) {
    delete this.attributes[name];
    return this;
  }
  hasAttribute(name) {
    return this.attributes[name] !== void 0;
  }
  addGroup(start, count, materialIndex = 0) {
    this.groups.push({
      start,
      count,
      materialIndex
    });
  }
  clearGroups() {
    this.groups = [];
  }
  setDrawRange(start, count) {
    this.drawRange.start = start;
    this.drawRange.count = count;
  }
  applyMatrix4(matrix) {
    const position = this.attributes.position;
    if (position !== void 0) {
      position.applyMatrix4(matrix);
      position.needsUpdate = true;
    }
    const normal = this.attributes.normal;
    if (normal !== void 0) {
      const normalMatrix = new Matrix3().getNormalMatrix(matrix);
      normal.applyNormalMatrix(normalMatrix);
      normal.needsUpdate = true;
    }
    const tangent = this.attributes.tangent;
    if (tangent !== void 0) {
      tangent.transformDirection(matrix);
      tangent.needsUpdate = true;
    }
    if (this.boundingBox !== null) {
      this.computeBoundingBox();
    }
    if (this.boundingSphere !== null) {
      this.computeBoundingSphere();
    }
    return this;
  }
  applyQuaternion(q3) {
    _m1$3.makeRotationFromQuaternion(q3);
    this.applyMatrix4(_m1$3);
    return this;
  }
  rotateX(angle) {
    _m1$3.makeRotationX(angle);
    this.applyMatrix4(_m1$3);
    return this;
  }
  rotateY(angle) {
    _m1$3.makeRotationY(angle);
    this.applyMatrix4(_m1$3);
    return this;
  }
  rotateZ(angle) {
    _m1$3.makeRotationZ(angle);
    this.applyMatrix4(_m1$3);
    return this;
  }
  translate(x, y2, z2) {
    _m1$3.makeTranslation(x, y2, z2);
    this.applyMatrix4(_m1$3);
    return this;
  }
  scale(x, y2, z2) {
    _m1$3.makeScale(x, y2, z2);
    this.applyMatrix4(_m1$3);
    return this;
  }
  lookAt(vector) {
    _obj.lookAt(vector);
    _obj.updateMatrix();
    this.applyMatrix4(_obj.matrix);
    return this;
  }
  center() {
    this.computeBoundingBox();
    this.boundingBox.getCenter(_offset).negate();
    this.translate(_offset.x, _offset.y, _offset.z);
    return this;
  }
  setFromPoints(points) {
    const positionAttribute = this.getAttribute("position");
    if (positionAttribute === void 0) {
      const position = [];
      for (let i2 = 0, l2 = points.length; i2 < l2; i2++) {
        const point = points[i2];
        position.push(point.x, point.y, point.z || 0);
      }
      this.setAttribute("position", new Float32BufferAttribute(position, 3));
    } else {
      const l2 = Math.min(points.length, positionAttribute.count);
      for (let i2 = 0; i2 < l2; i2++) {
        const point = points[i2];
        positionAttribute.setXYZ(i2, point.x, point.y, point.z || 0);
      }
      if (points.length > positionAttribute.count) {
        console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");
      }
      positionAttribute.needsUpdate = true;
    }
    return this;
  }
  computeBoundingBox() {
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    const position = this.attributes.position;
    const morphAttributesPosition = this.morphAttributes.position;
    if (position && position.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this);
      this.boundingBox.set(
        new Vector3(-Infinity, -Infinity, -Infinity),
        new Vector3(Infinity, Infinity, Infinity)
      );
      return;
    }
    if (position !== void 0) {
      this.boundingBox.setFromBufferAttribute(position);
      if (morphAttributesPosition) {
        for (let i2 = 0, il = morphAttributesPosition.length; i2 < il; i2++) {
          const morphAttribute = morphAttributesPosition[i2];
          _box$2.setFromBufferAttribute(morphAttribute);
          if (this.morphTargetsRelative) {
            _vector$8.addVectors(this.boundingBox.min, _box$2.min);
            this.boundingBox.expandByPoint(_vector$8);
            _vector$8.addVectors(this.boundingBox.max, _box$2.max);
            this.boundingBox.expandByPoint(_vector$8);
          } else {
            this.boundingBox.expandByPoint(_box$2.min);
            this.boundingBox.expandByPoint(_box$2.max);
          }
        }
      }
    } else {
      this.boundingBox.makeEmpty();
    }
    if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
      console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
    }
  }
  computeBoundingSphere() {
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    const position = this.attributes.position;
    const morphAttributesPosition = this.morphAttributes.position;
    if (position && position.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this);
      this.boundingSphere.set(new Vector3(), Infinity);
      return;
    }
    if (position) {
      const center = this.boundingSphere.center;
      _box$2.setFromBufferAttribute(position);
      if (morphAttributesPosition) {
        for (let i2 = 0, il = morphAttributesPosition.length; i2 < il; i2++) {
          const morphAttribute = morphAttributesPosition[i2];
          _boxMorphTargets.setFromBufferAttribute(morphAttribute);
          if (this.morphTargetsRelative) {
            _vector$8.addVectors(_box$2.min, _boxMorphTargets.min);
            _box$2.expandByPoint(_vector$8);
            _vector$8.addVectors(_box$2.max, _boxMorphTargets.max);
            _box$2.expandByPoint(_vector$8);
          } else {
            _box$2.expandByPoint(_boxMorphTargets.min);
            _box$2.expandByPoint(_boxMorphTargets.max);
          }
        }
      }
      _box$2.getCenter(center);
      let maxRadiusSq = 0;
      for (let i2 = 0, il = position.count; i2 < il; i2++) {
        _vector$8.fromBufferAttribute(position, i2);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
      }
      if (morphAttributesPosition) {
        for (let i2 = 0, il = morphAttributesPosition.length; i2 < il; i2++) {
          const morphAttribute = morphAttributesPosition[i2];
          const morphTargetsRelative = this.morphTargetsRelative;
          for (let j2 = 0, jl = morphAttribute.count; j2 < jl; j2++) {
            _vector$8.fromBufferAttribute(morphAttribute, j2);
            if (morphTargetsRelative) {
              _offset.fromBufferAttribute(position, j2);
              _vector$8.add(_offset);
            }
            maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
          }
        }
      }
      this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
      if (isNaN(this.boundingSphere.radius)) {
        console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
      }
    }
  }
  computeTangents() {
    const index = this.index;
    const attributes = this.attributes;
    if (index === null || attributes.position === void 0 || attributes.normal === void 0 || attributes.uv === void 0) {
      console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const positionAttribute = attributes.position;
    const normalAttribute = attributes.normal;
    const uvAttribute = attributes.uv;
    if (this.hasAttribute("tangent") === false) {
      this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4));
    }
    const tangentAttribute = this.getAttribute("tangent");
    const tan1 = [], tan2 = [];
    for (let i2 = 0; i2 < positionAttribute.count; i2++) {
      tan1[i2] = new Vector3();
      tan2[i2] = new Vector3();
    }
    const vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3();
    function handleTriangle(a3, b2, c2) {
      vA.fromBufferAttribute(positionAttribute, a3);
      vB.fromBufferAttribute(positionAttribute, b2);
      vC.fromBufferAttribute(positionAttribute, c2);
      uvA.fromBufferAttribute(uvAttribute, a3);
      uvB.fromBufferAttribute(uvAttribute, b2);
      uvC.fromBufferAttribute(uvAttribute, c2);
      vB.sub(vA);
      vC.sub(vA);
      uvB.sub(uvA);
      uvC.sub(uvA);
      const r2 = 1 / (uvB.x * uvC.y - uvC.x * uvB.y);
      if (!isFinite(r2)) return;
      sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r2);
      tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r2);
      tan1[a3].add(sdir);
      tan1[b2].add(sdir);
      tan1[c2].add(sdir);
      tan2[a3].add(tdir);
      tan2[b2].add(tdir);
      tan2[c2].add(tdir);
    }
    let groups = this.groups;
    if (groups.length === 0) {
      groups = [{
        start: 0,
        count: index.count
      }];
    }
    for (let i2 = 0, il = groups.length; i2 < il; ++i2) {
      const group = groups[i2];
      const start = group.start;
      const count = group.count;
      for (let j2 = start, jl = start + count; j2 < jl; j2 += 3) {
        handleTriangle(
          index.getX(j2 + 0),
          index.getX(j2 + 1),
          index.getX(j2 + 2)
        );
      }
    }
    const tmp2 = new Vector3(), tmp22 = new Vector3();
    const n2 = new Vector3(), n22 = new Vector3();
    function handleVertex(v5) {
      n2.fromBufferAttribute(normalAttribute, v5);
      n22.copy(n2);
      const t2 = tan1[v5];
      tmp2.copy(t2);
      tmp2.sub(n2.multiplyScalar(n2.dot(t2))).normalize();
      tmp22.crossVectors(n22, t2);
      const test = tmp22.dot(tan2[v5]);
      const w2 = test < 0 ? -1 : 1;
      tangentAttribute.setXYZW(v5, tmp2.x, tmp2.y, tmp2.z, w2);
    }
    for (let i2 = 0, il = groups.length; i2 < il; ++i2) {
      const group = groups[i2];
      const start = group.start;
      const count = group.count;
      for (let j2 = start, jl = start + count; j2 < jl; j2 += 3) {
        handleVertex(index.getX(j2 + 0));
        handleVertex(index.getX(j2 + 1));
        handleVertex(index.getX(j2 + 2));
      }
    }
  }
  computeVertexNormals() {
    const index = this.index;
    const positionAttribute = this.getAttribute("position");
    if (positionAttribute !== void 0) {
      let normalAttribute = this.getAttribute("normal");
      if (normalAttribute === void 0) {
        normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
        this.setAttribute("normal", normalAttribute);
      } else {
        for (let i2 = 0, il = normalAttribute.count; i2 < il; i2++) {
          normalAttribute.setXYZ(i2, 0, 0, 0);
        }
      }
      const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
      const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
      const cb = new Vector3(), ab = new Vector3();
      if (index) {
        for (let i2 = 0, il = index.count; i2 < il; i2 += 3) {
          const vA = index.getX(i2 + 0);
          const vB = index.getX(i2 + 1);
          const vC = index.getX(i2 + 2);
          pA.fromBufferAttribute(positionAttribute, vA);
          pB.fromBufferAttribute(positionAttribute, vB);
          pC.fromBufferAttribute(positionAttribute, vC);
          cb.subVectors(pC, pB);
          ab.subVectors(pA, pB);
          cb.cross(ab);
          nA.fromBufferAttribute(normalAttribute, vA);
          nB.fromBufferAttribute(normalAttribute, vB);
          nC.fromBufferAttribute(normalAttribute, vC);
          nA.add(cb);
          nB.add(cb);
          nC.add(cb);
          normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
          normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
          normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
        }
      } else {
        for (let i2 = 0, il = positionAttribute.count; i2 < il; i2 += 3) {
          pA.fromBufferAttribute(positionAttribute, i2 + 0);
          pB.fromBufferAttribute(positionAttribute, i2 + 1);
          pC.fromBufferAttribute(positionAttribute, i2 + 2);
          cb.subVectors(pC, pB);
          ab.subVectors(pA, pB);
          cb.cross(ab);
          normalAttribute.setXYZ(i2 + 0, cb.x, cb.y, cb.z);
          normalAttribute.setXYZ(i2 + 1, cb.x, cb.y, cb.z);
          normalAttribute.setXYZ(i2 + 2, cb.x, cb.y, cb.z);
        }
      }
      this.normalizeNormals();
      normalAttribute.needsUpdate = true;
    }
  }
  normalizeNormals() {
    const normals = this.attributes.normal;
    for (let i2 = 0, il = normals.count; i2 < il; i2++) {
      _vector$8.fromBufferAttribute(normals, i2);
      _vector$8.normalize();
      normals.setXYZ(i2, _vector$8.x, _vector$8.y, _vector$8.z);
    }
  }
  toNonIndexed() {
    function convertBufferAttribute(attribute, indices2) {
      const array = attribute.array;
      const itemSize = attribute.itemSize;
      const normalized = attribute.normalized;
      const array2 = new array.constructor(indices2.length * itemSize);
      let index = 0, index2 = 0;
      for (let i2 = 0, l2 = indices2.length; i2 < l2; i2++) {
        if (attribute.isInterleavedBufferAttribute) {
          index = indices2[i2] * attribute.data.stride + attribute.offset;
        } else {
          index = indices2[i2] * itemSize;
        }
        for (let j2 = 0; j2 < itemSize; j2++) {
          array2[index2++] = array[index++];
        }
      }
      return new BufferAttribute(array2, itemSize, normalized);
    }
    if (this.index === null) {
      console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.");
      return this;
    }
    const geometry2 = new BufferGeometry();
    const indices = this.index.array;
    const attributes = this.attributes;
    for (const name in attributes) {
      const attribute = attributes[name];
      const newAttribute = convertBufferAttribute(attribute, indices);
      geometry2.setAttribute(name, newAttribute);
    }
    const morphAttributes = this.morphAttributes;
    for (const name in morphAttributes) {
      const morphArray = [];
      const morphAttribute = morphAttributes[name];
      for (let i2 = 0, il = morphAttribute.length; i2 < il; i2++) {
        const attribute = morphAttribute[i2];
        const newAttribute = convertBufferAttribute(attribute, indices);
        morphArray.push(newAttribute);
      }
      geometry2.morphAttributes[name] = morphArray;
    }
    geometry2.morphTargetsRelative = this.morphTargetsRelative;
    const groups = this.groups;
    for (let i2 = 0, l2 = groups.length; i2 < l2; i2++) {
      const group = groups[i2];
      geometry2.addGroup(group.start, group.count, group.materialIndex);
    }
    return geometry2;
  }
  toJSON() {
    const data = {
      metadata: {
        version: 4.6,
        type: "BufferGeometry",
        generator: "BufferGeometry.toJSON"
      }
    };
    data.uuid = this.uuid;
    data.type = this.type;
    if (this.name !== "") data.name = this.name;
    if (Object.keys(this.userData).length > 0) data.userData = this.userData;
    if (this.parameters !== void 0) {
      const parameters = this.parameters;
      for (const key in parameters) {
        if (parameters[key] !== void 0) data[key] = parameters[key];
      }
      return data;
    }
    data.data = { attributes: {} };
    const index = this.index;
    if (index !== null) {
      data.data.index = {
        type: index.array.constructor.name,
        array: Array.prototype.slice.call(index.array)
      };
    }
    const attributes = this.attributes;
    for (const key in attributes) {
      const attribute = attributes[key];
      data.data.attributes[key] = attribute.toJSON(data.data);
    }
    const morphAttributes = {};
    let hasMorphAttributes = false;
    for (const key in this.morphAttributes) {
      const attributeArray = this.morphAttributes[key];
      const array = [];
      for (let i2 = 0, il = attributeArray.length; i2 < il; i2++) {
        const attribute = attributeArray[i2];
        array.push(attribute.toJSON(data.data));
      }
      if (array.length > 0) {
        morphAttributes[key] = array;
        hasMorphAttributes = true;
      }
    }
    if (hasMorphAttributes) {
      data.data.morphAttributes = morphAttributes;
      data.data.morphTargetsRelative = this.morphTargetsRelative;
    }
    const groups = this.groups;
    if (groups.length > 0) {
      data.data.groups = JSON.parse(JSON.stringify(groups));
    }
    const boundingSphere = this.boundingSphere;
    if (boundingSphere !== null) {
      data.data.boundingSphere = {
        center: boundingSphere.center.toArray(),
        radius: boundingSphere.radius
      };
    }
    return data;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.index = null;
    this.attributes = {};
    this.morphAttributes = {};
    this.groups = [];
    this.boundingBox = null;
    this.boundingSphere = null;
    const data = {};
    this.name = source.name;
    const index = source.index;
    if (index !== null) {
      this.setIndex(index.clone(data));
    }
    const attributes = source.attributes;
    for (const name in attributes) {
      const attribute = attributes[name];
      this.setAttribute(name, attribute.clone(data));
    }
    const morphAttributes = source.morphAttributes;
    for (const name in morphAttributes) {
      const array = [];
      const morphAttribute = morphAttributes[name];
      for (let i2 = 0, l2 = morphAttribute.length; i2 < l2; i2++) {
        array.push(morphAttribute[i2].clone(data));
      }
      this.morphAttributes[name] = array;
    }
    this.morphTargetsRelative = source.morphTargetsRelative;
    const groups = source.groups;
    for (let i2 = 0, l2 = groups.length; i2 < l2; i2++) {
      const group = groups[i2];
      this.addGroup(group.start, group.count, group.materialIndex);
    }
    const boundingBox = source.boundingBox;
    if (boundingBox !== null) {
      this.boundingBox = boundingBox.clone();
    }
    const boundingSphere = source.boundingSphere;
    if (boundingSphere !== null) {
      this.boundingSphere = boundingSphere.clone();
    }
    this.drawRange.start = source.drawRange.start;
    this.drawRange.count = source.drawRange.count;
    this.userData = source.userData;
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
const _inverseMatrix$3 = /* @__PURE__ */ new Matrix4();
const _ray$3 = /* @__PURE__ */ new Ray();
const _sphere$6 = /* @__PURE__ */ new Sphere();
const _sphereHitAt = /* @__PURE__ */ new Vector3();
const _vA$1 = /* @__PURE__ */ new Vector3();
const _vB$1 = /* @__PURE__ */ new Vector3();
const _vC$1 = /* @__PURE__ */ new Vector3();
const _tempA = /* @__PURE__ */ new Vector3();
const _morphA = /* @__PURE__ */ new Vector3();
const _intersectionPoint = /* @__PURE__ */ new Vector3();
const _intersectionPointWorld = /* @__PURE__ */ new Vector3();
class Mesh extends Object3D {
  constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
    super();
    this.isMesh = true;
    this.type = "Mesh";
    this.geometry = geometry;
    this.material = material;
    this.updateMorphTargets();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.morphTargetInfluences !== void 0) {
      this.morphTargetInfluences = source.morphTargetInfluences.slice();
    }
    if (source.morphTargetDictionary !== void 0) {
      this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
    }
    this.material = Array.isArray(source.material) ? source.material.slice() : source.material;
    this.geometry = source.geometry;
    return this;
  }
  updateMorphTargets() {
    const geometry = this.geometry;
    const morphAttributes = geometry.morphAttributes;
    const keys = Object.keys(morphAttributes);
    if (keys.length > 0) {
      const morphAttribute = morphAttributes[keys[0]];
      if (morphAttribute !== void 0) {
        this.morphTargetInfluences = [];
        this.morphTargetDictionary = {};
        for (let m2 = 0, ml = morphAttribute.length; m2 < ml; m2++) {
          const name = morphAttribute[m2].name || String(m2);
          this.morphTargetInfluences.push(0);
          this.morphTargetDictionary[name] = m2;
        }
      }
    }
  }
  getVertexPosition(index, target) {
    const geometry = this.geometry;
    const position = geometry.attributes.position;
    const morphPosition = geometry.morphAttributes.position;
    const morphTargetsRelative = geometry.morphTargetsRelative;
    target.fromBufferAttribute(position, index);
    const morphInfluences = this.morphTargetInfluences;
    if (morphPosition && morphInfluences) {
      _morphA.set(0, 0, 0);
      for (let i2 = 0, il = morphPosition.length; i2 < il; i2++) {
        const influence = morphInfluences[i2];
        const morphAttribute = morphPosition[i2];
        if (influence === 0) continue;
        _tempA.fromBufferAttribute(morphAttribute, index);
        if (morphTargetsRelative) {
          _morphA.addScaledVector(_tempA, influence);
        } else {
          _morphA.addScaledVector(_tempA.sub(target), influence);
        }
      }
      target.add(_morphA);
    }
    return target;
  }
  raycast(raycaster, intersects2) {
    const geometry = this.geometry;
    const material = this.material;
    const matrixWorld = this.matrixWorld;
    if (material === void 0) return;
    if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
    _sphere$6.copy(geometry.boundingSphere);
    _sphere$6.applyMatrix4(matrixWorld);
    _ray$3.copy(raycaster.ray).recast(raycaster.near);
    if (_sphere$6.containsPoint(_ray$3.origin) === false) {
      if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) return;
      if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) return;
    }
    _inverseMatrix$3.copy(matrixWorld).invert();
    _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3);
    if (geometry.boundingBox !== null) {
      if (_ray$3.intersectsBox(geometry.boundingBox) === false) return;
    }
    this._computeIntersections(raycaster, intersects2, _ray$3);
  }
  _computeIntersections(raycaster, intersects2, rayLocalSpace) {
    let intersection;
    const geometry = this.geometry;
    const material = this.material;
    const index = geometry.index;
    const position = geometry.attributes.position;
    const uv = geometry.attributes.uv;
    const uv1 = geometry.attributes.uv1;
    const normal = geometry.attributes.normal;
    const groups = geometry.groups;
    const drawRange = geometry.drawRange;
    if (index !== null) {
      if (Array.isArray(material)) {
        for (let i2 = 0, il = groups.length; i2 < il; i2++) {
          const group = groups[i2];
          const groupMaterial = material[group.materialIndex];
          const start = Math.max(group.start, drawRange.start);
          const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
          for (let j2 = start, jl = end; j2 < jl; j2 += 3) {
            const a3 = index.getX(j2);
            const b2 = index.getX(j2 + 1);
            const c2 = index.getX(j2 + 2);
            intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a3, b2, c2);
            if (intersection) {
              intersection.faceIndex = Math.floor(j2 / 3);
              intersection.face.materialIndex = group.materialIndex;
              intersects2.push(intersection);
            }
          }
        }
      } else {
        const start = Math.max(0, drawRange.start);
        const end = Math.min(index.count, drawRange.start + drawRange.count);
        for (let i2 = start, il = end; i2 < il; i2 += 3) {
          const a3 = index.getX(i2);
          const b2 = index.getX(i2 + 1);
          const c2 = index.getX(i2 + 2);
          intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a3, b2, c2);
          if (intersection) {
            intersection.faceIndex = Math.floor(i2 / 3);
            intersects2.push(intersection);
          }
        }
      }
    } else if (position !== void 0) {
      if (Array.isArray(material)) {
        for (let i2 = 0, il = groups.length; i2 < il; i2++) {
          const group = groups[i2];
          const groupMaterial = material[group.materialIndex];
          const start = Math.max(group.start, drawRange.start);
          const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
          for (let j2 = start, jl = end; j2 < jl; j2 += 3) {
            const a3 = j2;
            const b2 = j2 + 1;
            const c2 = j2 + 2;
            intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a3, b2, c2);
            if (intersection) {
              intersection.faceIndex = Math.floor(j2 / 3);
              intersection.face.materialIndex = group.materialIndex;
              intersects2.push(intersection);
            }
          }
        }
      } else {
        const start = Math.max(0, drawRange.start);
        const end = Math.min(position.count, drawRange.start + drawRange.count);
        for (let i2 = start, il = end; i2 < il; i2 += 3) {
          const a3 = i2;
          const b2 = i2 + 1;
          const c2 = i2 + 2;
          intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a3, b2, c2);
          if (intersection) {
            intersection.faceIndex = Math.floor(i2 / 3);
            intersects2.push(intersection);
          }
        }
      }
    }
  }
}
function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point) {
  let intersect2;
  if (material.side === BackSide) {
    intersect2 = ray.intersectTriangle(pC, pB, pA, true, point);
  } else {
    intersect2 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point);
  }
  if (intersect2 === null) return null;
  _intersectionPointWorld.copy(point);
  _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  if (distance < raycaster.near || distance > raycaster.far) return null;
  return {
    distance,
    point: _intersectionPointWorld.clone(),
    object
  };
}
function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a3, b2, c2) {
  object.getVertexPosition(a3, _vA$1);
  object.getVertexPosition(b2, _vB$1);
  object.getVertexPosition(c2, _vC$1);
  const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  if (intersection) {
    const barycoord = new Vector3();
    Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord);
    if (uv) {
      intersection.uv = Triangle.getInterpolatedAttribute(uv, a3, b2, c2, barycoord, new Vector2());
    }
    if (uv1) {
      intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a3, b2, c2, barycoord, new Vector2());
    }
    if (normal) {
      intersection.normal = Triangle.getInterpolatedAttribute(normal, a3, b2, c2, barycoord, new Vector3());
      if (intersection.normal.dot(ray.direction) > 0) {
        intersection.normal.multiplyScalar(-1);
      }
    }
    const face = {
      a: a3,
      b: b2,
      c: c2,
      normal: new Vector3(),
      materialIndex: 0
    };
    Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
    intersection.face = face;
    intersection.barycoord = barycoord;
  }
  return intersection;
}
class BoxGeometry extends BufferGeometry {
  constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
    super();
    this.type = "BoxGeometry";
    this.parameters = {
      width,
      height,
      depth,
      widthSegments,
      heightSegments,
      depthSegments
    };
    const scope = this;
    widthSegments = Math.floor(widthSegments);
    heightSegments = Math.floor(heightSegments);
    depthSegments = Math.floor(depthSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let numberOfVertices = 0;
    let groupStart = 0;
    buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0);
    buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1);
    buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2);
    buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3);
    buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4);
    buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5);
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function buildPlane(u2, v5, w2, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) {
      const segmentWidth = width2 / gridX;
      const segmentHeight = height2 / gridY;
      const widthHalf = width2 / 2;
      const heightHalf = height2 / 2;
      const depthHalf = depth2 / 2;
      const gridX1 = gridX + 1;
      const gridY1 = gridY + 1;
      let vertexCounter = 0;
      let groupCount = 0;
      const vector = new Vector3();
      for (let iy = 0; iy < gridY1; iy++) {
        const y2 = iy * segmentHeight - heightHalf;
        for (let ix = 0; ix < gridX1; ix++) {
          const x = ix * segmentWidth - widthHalf;
          vector[u2] = x * udir;
          vector[v5] = y2 * vdir;
          vector[w2] = depthHalf;
          vertices.push(vector.x, vector.y, vector.z);
          vector[u2] = 0;
          vector[v5] = 0;
          vector[w2] = depth2 > 0 ? 1 : -1;
          normals.push(vector.x, vector.y, vector.z);
          uvs.push(ix / gridX);
          uvs.push(1 - iy / gridY);
          vertexCounter += 1;
        }
      }
      for (let iy = 0; iy < gridY; iy++) {
        for (let ix = 0; ix < gridX; ix++) {
          const a3 = numberOfVertices + ix + gridX1 * iy;
          const b2 = numberOfVertices + ix + gridX1 * (iy + 1);
          const c2 = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
          const d2 = numberOfVertices + (ix + 1) + gridX1 * iy;
          indices.push(a3, b2, d2);
          indices.push(b2, c2, d2);
          groupCount += 6;
        }
      }
      scope.addGroup(groupStart, groupCount, materialIndex);
      groupStart += groupCount;
      numberOfVertices += vertexCounter;
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  }
}
function cloneUniforms(src) {
  const dst = {};
  for (const u2 in src) {
    dst[u2] = {};
    for (const p2 in src[u2]) {
      const property = src[u2][p2];
      if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
        if (property.isRenderTargetTexture) {
          console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().");
          dst[u2][p2] = null;
        } else {
          dst[u2][p2] = property.clone();
        }
      } else if (Array.isArray(property)) {
        dst[u2][p2] = property.slice();
      } else {
        dst[u2][p2] = property;
      }
    }
  }
  return dst;
}
function mergeUniforms(uniforms) {
  const merged = {};
  for (let u2 = 0; u2 < uniforms.length; u2++) {
    const tmp2 = cloneUniforms(uniforms[u2]);
    for (const p2 in tmp2) {
      merged[p2] = tmp2[p2];
    }
  }
  return merged;
}
function cloneUniformsGroups(src) {
  const dst = [];
  for (let u2 = 0; u2 < src.length; u2++) {
    dst.push(src[u2].clone());
  }
  return dst;
}
function getUnlitUniformColorSpace(renderer) {
  const currentRenderTarget = renderer.getRenderTarget();
  if (currentRenderTarget === null) {
    return renderer.outputColorSpace;
  }
  if (currentRenderTarget.isXRRenderTarget === true) {
    return currentRenderTarget.texture.colorSpace;
  }
  return ColorManagement.workingColorSpace;
}
const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
var default_vertex = "void main() {\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
var default_fragment = "void main() {\n	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
class ShaderMaterial extends Material {
  constructor(parameters) {
    super();
    this.isShaderMaterial = true;
    this.type = "ShaderMaterial";
    this.defines = {};
    this.uniforms = {};
    this.uniformsGroups = [];
    this.vertexShader = default_vertex;
    this.fragmentShader = default_fragment;
    this.linewidth = 1;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.fog = false;
    this.lights = false;
    this.clipping = false;
    this.forceSinglePass = true;
    this.extensions = {
      clipCullDistance: false,
      // set to use vertex shader clipping
      multiDraw: false
      // set to use vertex shader multi_draw / enable gl_DrawID
    };
    this.defaultAttributeValues = {
      "color": [1, 1, 1],
      "uv": [0, 0],
      "uv1": [0, 0]
    };
    this.index0AttributeName = void 0;
    this.uniformsNeedUpdate = false;
    this.glslVersion = null;
    if (parameters !== void 0) {
      this.setValues(parameters);
    }
  }
  copy(source) {
    super.copy(source);
    this.fragmentShader = source.fragmentShader;
    this.vertexShader = source.vertexShader;
    this.uniforms = cloneUniforms(source.uniforms);
    this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
    this.defines = Object.assign({}, source.defines);
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.fog = source.fog;
    this.lights = source.lights;
    this.clipping = source.clipping;
    this.extensions = Object.assign({}, source.extensions);
    this.glslVersion = source.glslVersion;
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.glslVersion = this.glslVersion;
    data.uniforms = {};
    for (const name in this.uniforms) {
      const uniform = this.uniforms[name];
      const value = uniform.value;
      if (value && value.isTexture) {
        data.uniforms[name] = {
          type: "t",
          value: value.toJSON(meta2).uuid
        };
      } else if (value && value.isColor) {
        data.uniforms[name] = {
          type: "c",
          value: value.getHex()
        };
      } else if (value && value.isVector2) {
        data.uniforms[name] = {
          type: "v2",
          value: value.toArray()
        };
      } else if (value && value.isVector3) {
        data.uniforms[name] = {
          type: "v3",
          value: value.toArray()
        };
      } else if (value && value.isVector4) {
        data.uniforms[name] = {
          type: "v4",
          value: value.toArray()
        };
      } else if (value && value.isMatrix3) {
        data.uniforms[name] = {
          type: "m3",
          value: value.toArray()
        };
      } else if (value && value.isMatrix4) {
        data.uniforms[name] = {
          type: "m4",
          value: value.toArray()
        };
      } else {
        data.uniforms[name] = {
          value
        };
      }
    }
    if (Object.keys(this.defines).length > 0) data.defines = this.defines;
    data.vertexShader = this.vertexShader;
    data.fragmentShader = this.fragmentShader;
    data.lights = this.lights;
    data.clipping = this.clipping;
    const extensions = {};
    for (const key in this.extensions) {
      if (this.extensions[key] === true) extensions[key] = true;
    }
    if (Object.keys(extensions).length > 0) data.extensions = extensions;
    return data;
  }
}
class Camera extends Object3D {
  constructor() {
    super();
    this.isCamera = true;
    this.type = "Camera";
    this.matrixWorldInverse = new Matrix4();
    this.projectionMatrix = new Matrix4();
    this.projectionMatrixInverse = new Matrix4();
    this.coordinateSystem = WebGLCoordinateSystem;
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.matrixWorldInverse.copy(source.matrixWorldInverse);
    this.projectionMatrix.copy(source.projectionMatrix);
    this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
    this.coordinateSystem = source.coordinateSystem;
    return this;
  }
  getWorldDirection(target) {
    return super.getWorldDirection(target).negate();
  }
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  updateWorldMatrix(updateParents, updateChildren) {
    super.updateWorldMatrix(updateParents, updateChildren);
    this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const _v3$1 = /* @__PURE__ */ new Vector3();
const _minTarget = /* @__PURE__ */ new Vector2();
const _maxTarget = /* @__PURE__ */ new Vector2();
class PerspectiveCamera extends Camera {
  constructor(fov2 = 50, aspect2 = 1, near = 0.1, far = 2e3) {
    super();
    this.isPerspectiveCamera = true;
    this.type = "PerspectiveCamera";
    this.fov = fov2;
    this.zoom = 1;
    this.near = near;
    this.far = far;
    this.focus = 10;
    this.aspect = aspect2;
    this.view = null;
    this.filmGauge = 35;
    this.filmOffset = 0;
    this.updateProjectionMatrix();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.fov = source.fov;
    this.zoom = source.zoom;
    this.near = source.near;
    this.far = source.far;
    this.focus = source.focus;
    this.aspect = source.aspect;
    this.view = source.view === null ? null : Object.assign({}, source.view);
    this.filmGauge = source.filmGauge;
    this.filmOffset = source.filmOffset;
    return this;
  }
  /**
   * Sets the FOV by focal length in respect to the current .filmGauge.
   *
   * The default film gauge is 35, so that the focal length can be specified for
   * a 35mm (full frame) camera.
   *
   * Values for focal length and film gauge must have the same unit.
   */
  setFocalLength(focalLength) {
    const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
    this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
    this.updateProjectionMatrix();
  }
  /**
   * Calculates the focal length from the current .fov and .filmGauge.
   */
  getFocalLength() {
    const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
    return 0.5 * this.getFilmHeight() / vExtentSlope;
  }
  getEffectiveFOV() {
    return RAD2DEG * 2 * Math.atan(
      Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom
    );
  }
  getFilmWidth() {
    return this.filmGauge * Math.min(this.aspect, 1);
  }
  getFilmHeight() {
    return this.filmGauge / Math.max(this.aspect, 1);
  }
  /**
   * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
   * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
   */
  getViewBounds(distance, minTarget, maxTarget) {
    _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse);
    minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z);
    _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse);
    maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z);
  }
  /**
   * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
   * Copies the result into the target Vector2, where x is width and y is height.
   */
  getViewSize(distance, target) {
    this.getViewBounds(distance, _minTarget, _maxTarget);
    return target.subVectors(_maxTarget, _minTarget);
  }
  /**
   * Sets an offset in a larger frustum. This is useful for multi-window or
   * multi-monitor/multi-machine setups.
   *
   * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
   * the monitors are in grid like this
   *
   *   +---+---+---+
   *   | A | B | C |
   *   +---+---+---+
   *   | D | E | F |
   *   +---+---+---+
   *
   * then for each monitor you would call it like this
   *
   *   const w = 1920;
   *   const h = 1080;
   *   const fullWidth = w * 3;
   *   const fullHeight = h * 2;
   *
   *   --A--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
   *   --B--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
   *   --C--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
   *   --D--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
   *   --E--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
   *   --F--
   *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
   *
   *   Note there is no reason monitors have to be the same size or in a grid.
   */
  setViewOffset(fullWidth, fullHeight, x, y2, width, height) {
    this.aspect = fullWidth / fullHeight;
    if (this.view === null) {
      this.view = {
        enabled: true,
        fullWidth: 1,
        fullHeight: 1,
        offsetX: 0,
        offsetY: 0,
        width: 1,
        height: 1
      };
    }
    this.view.enabled = true;
    this.view.fullWidth = fullWidth;
    this.view.fullHeight = fullHeight;
    this.view.offsetX = x;
    this.view.offsetY = y2;
    this.view.width = width;
    this.view.height = height;
    this.updateProjectionMatrix();
  }
  clearViewOffset() {
    if (this.view !== null) {
      this.view.enabled = false;
    }
    this.updateProjectionMatrix();
  }
  updateProjectionMatrix() {
    const near = this.near;
    let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
    let height = 2 * top;
    let width = this.aspect * height;
    let left = -0.5 * width;
    const view = this.view;
    if (this.view !== null && this.view.enabled) {
      const fullWidth = view.fullWidth, fullHeight = view.fullHeight;
      left += view.offsetX * width / fullWidth;
      top -= view.offsetY * height / fullHeight;
      width *= view.width / fullWidth;
      height *= view.height / fullHeight;
    }
    const skew = this.filmOffset;
    if (skew !== 0) left += near * skew / this.getFilmWidth();
    this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far, this.coordinateSystem);
    this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.object.fov = this.fov;
    data.object.zoom = this.zoom;
    data.object.near = this.near;
    data.object.far = this.far;
    data.object.focus = this.focus;
    data.object.aspect = this.aspect;
    if (this.view !== null) data.object.view = Object.assign({}, this.view);
    data.object.filmGauge = this.filmGauge;
    data.object.filmOffset = this.filmOffset;
    return data;
  }
}
const fov = -90;
const aspect = 1;
class CubeCamera extends Object3D {
  constructor(near, far, renderTarget) {
    super();
    this.type = "CubeCamera";
    this.renderTarget = renderTarget;
    this.coordinateSystem = null;
    this.activeMipmapLevel = 0;
    const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
    cameraPX.layers = this.layers;
    this.add(cameraPX);
    const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
    cameraNX.layers = this.layers;
    this.add(cameraNX);
    const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
    cameraPY.layers = this.layers;
    this.add(cameraPY);
    const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
    cameraNY.layers = this.layers;
    this.add(cameraNY);
    const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
    cameraPZ.layers = this.layers;
    this.add(cameraPZ);
    const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
    cameraNZ.layers = this.layers;
    this.add(cameraNZ);
  }
  updateCoordinateSystem() {
    const coordinateSystem = this.coordinateSystem;
    const cameras = this.children.concat();
    const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras;
    for (const camera of cameras) this.remove(camera);
    if (coordinateSystem === WebGLCoordinateSystem) {
      cameraPX.up.set(0, 1, 0);
      cameraPX.lookAt(1, 0, 0);
      cameraNX.up.set(0, 1, 0);
      cameraNX.lookAt(-1, 0, 0);
      cameraPY.up.set(0, 0, -1);
      cameraPY.lookAt(0, 1, 0);
      cameraNY.up.set(0, 0, 1);
      cameraNY.lookAt(0, -1, 0);
      cameraPZ.up.set(0, 1, 0);
      cameraPZ.lookAt(0, 0, 1);
      cameraNZ.up.set(0, 1, 0);
      cameraNZ.lookAt(0, 0, -1);
    } else if (coordinateSystem === WebGPUCoordinateSystem) {
      cameraPX.up.set(0, -1, 0);
      cameraPX.lookAt(-1, 0, 0);
      cameraNX.up.set(0, -1, 0);
      cameraNX.lookAt(1, 0, 0);
      cameraPY.up.set(0, 0, 1);
      cameraPY.lookAt(0, 1, 0);
      cameraNY.up.set(0, 0, -1);
      cameraNY.lookAt(0, -1, 0);
      cameraPZ.up.set(0, -1, 0);
      cameraPZ.lookAt(0, 0, 1);
      cameraNZ.up.set(0, -1, 0);
      cameraNZ.lookAt(0, 0, -1);
    } else {
      throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem);
    }
    for (const camera of cameras) {
      this.add(camera);
      camera.updateMatrixWorld();
    }
  }
  update(renderer, scene) {
    if (this.parent === null) this.updateMatrixWorld();
    const { renderTarget, activeMipmapLevel } = this;
    if (this.coordinateSystem !== renderer.coordinateSystem) {
      this.coordinateSystem = renderer.coordinateSystem;
      this.updateCoordinateSystem();
    }
    const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
    const currentRenderTarget = renderer.getRenderTarget();
    const currentActiveCubeFace = renderer.getActiveCubeFace();
    const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
    const currentXrEnabled = renderer.xr.enabled;
    renderer.xr.enabled = false;
    const generateMipmaps = renderTarget.texture.generateMipmaps;
    renderTarget.texture.generateMipmaps = false;
    renderer.setRenderTarget(renderTarget, 0, activeMipmapLevel);
    renderer.render(scene, cameraPX);
    renderer.setRenderTarget(renderTarget, 1, activeMipmapLevel);
    renderer.render(scene, cameraNX);
    renderer.setRenderTarget(renderTarget, 2, activeMipmapLevel);
    renderer.render(scene, cameraPY);
    renderer.setRenderTarget(renderTarget, 3, activeMipmapLevel);
    renderer.render(scene, cameraNY);
    renderer.setRenderTarget(renderTarget, 4, activeMipmapLevel);
    renderer.render(scene, cameraPZ);
    renderTarget.texture.generateMipmaps = generateMipmaps;
    renderer.setRenderTarget(renderTarget, 5, activeMipmapLevel);
    renderer.render(scene, cameraNZ);
    renderer.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel);
    renderer.xr.enabled = currentXrEnabled;
    renderTarget.texture.needsPMREMUpdate = true;
  }
}
class CubeTexture extends Texture {
  constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) {
    images = images !== void 0 ? images : [];
    mapping = mapping !== void 0 ? mapping : CubeReflectionMapping;
    super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace);
    this.isCubeTexture = true;
    this.flipY = false;
  }
  get images() {
    return this.image;
  }
  set images(value) {
    this.image = value;
  }
}
class WebGLCubeRenderTarget extends WebGLRenderTarget {
  constructor(size = 1, options = {}) {
    super(size, size, options);
    this.isWebGLCubeRenderTarget = true;
    const image = { width: size, height: size, depth: 1 };
    const images = [image, image, image, image, image, image];
    this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace);
    this.texture.isRenderTargetTexture = true;
    this.texture.generateMipmaps = options.generateMipmaps !== void 0 ? options.generateMipmaps : false;
    this.texture.minFilter = options.minFilter !== void 0 ? options.minFilter : LinearFilter;
  }
  fromEquirectangularTexture(renderer, texture) {
    this.texture.type = texture.type;
    this.texture.colorSpace = texture.colorSpace;
    this.texture.generateMipmaps = texture.generateMipmaps;
    this.texture.minFilter = texture.minFilter;
    this.texture.magFilter = texture.magFilter;
    const shader = {
      uniforms: {
        tEquirect: { value: null }
      },
      vertexShader: (
        /* glsl */
        `

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`
      )
    };
    const geometry = new BoxGeometry(5, 5, 5);
    const material = new ShaderMaterial({
      name: "CubemapFromEquirect",
      uniforms: cloneUniforms(shader.uniforms),
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      side: BackSide,
      blending: NoBlending
    });
    material.uniforms.tEquirect.value = texture;
    const mesh = new Mesh(geometry, material);
    const currentMinFilter = texture.minFilter;
    if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
    const camera = new CubeCamera(1, 10, this);
    camera.update(renderer, mesh);
    texture.minFilter = currentMinFilter;
    mesh.geometry.dispose();
    mesh.material.dispose();
    return this;
  }
  clear(renderer, color, depth, stencil) {
    const currentRenderTarget = renderer.getRenderTarget();
    for (let i2 = 0; i2 < 6; i2++) {
      renderer.setRenderTarget(this, i2);
      renderer.clear(color, depth, stencil);
    }
    renderer.setRenderTarget(currentRenderTarget);
  }
}
class FogExp2 {
  constructor(color, density = 25e-5) {
    this.isFogExp2 = true;
    this.name = "";
    this.color = new Color(color);
    this.density = density;
  }
  clone() {
    return new FogExp2(this.color, this.density);
  }
  toJSON() {
    return {
      type: "FogExp2",
      name: this.name,
      color: this.color.getHex(),
      density: this.density
    };
  }
}
class Fog {
  constructor(color, near = 1, far = 1e3) {
    this.isFog = true;
    this.name = "";
    this.color = new Color(color);
    this.near = near;
    this.far = far;
  }
  clone() {
    return new Fog(this.color, this.near, this.far);
  }
  toJSON() {
    return {
      type: "Fog",
      name: this.name,
      color: this.color.getHex(),
      near: this.near,
      far: this.far
    };
  }
}
class Scene extends Object3D {
  constructor() {
    super();
    this.isScene = true;
    this.type = "Scene";
    this.background = null;
    this.environment = null;
    this.fog = null;
    this.backgroundBlurriness = 0;
    this.backgroundIntensity = 1;
    this.backgroundRotation = new Euler();
    this.environmentIntensity = 1;
    this.environmentRotation = new Euler();
    this.overrideMaterial = null;
    if (typeof __THREE_DEVTOOLS__ !== "undefined") {
      __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
    }
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.background !== null) this.background = source.background.clone();
    if (source.environment !== null) this.environment = source.environment.clone();
    if (source.fog !== null) this.fog = source.fog.clone();
    this.backgroundBlurriness = source.backgroundBlurriness;
    this.backgroundIntensity = source.backgroundIntensity;
    this.backgroundRotation.copy(source.backgroundRotation);
    this.environmentIntensity = source.environmentIntensity;
    this.environmentRotation.copy(source.environmentRotation);
    if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
    this.matrixAutoUpdate = source.matrixAutoUpdate;
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    if (this.fog !== null) data.object.fog = this.fog.toJSON();
    if (this.backgroundBlurriness > 0) data.object.backgroundBlurriness = this.backgroundBlurriness;
    if (this.backgroundIntensity !== 1) data.object.backgroundIntensity = this.backgroundIntensity;
    data.object.backgroundRotation = this.backgroundRotation.toArray();
    if (this.environmentIntensity !== 1) data.object.environmentIntensity = this.environmentIntensity;
    data.object.environmentRotation = this.environmentRotation.toArray();
    return data;
  }
}
class InterleavedBuffer {
  constructor(array, stride) {
    this.isInterleavedBuffer = true;
    this.array = array;
    this.stride = stride;
    this.count = array !== void 0 ? array.length / stride : 0;
    this.usage = StaticDrawUsage;
    this.updateRanges = [];
    this.version = 0;
    this.uuid = generateUUID();
  }
  onUploadCallback() {
  }
  set needsUpdate(value) {
    if (value === true) this.version++;
  }
  setUsage(value) {
    this.usage = value;
    return this;
  }
  addUpdateRange(start, count) {
    this.updateRanges.push({ start, count });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(source) {
    this.array = new source.array.constructor(source.array);
    this.count = source.count;
    this.stride = source.stride;
    this.usage = source.usage;
    return this;
  }
  copyAt(index1, attribute, index2) {
    index1 *= this.stride;
    index2 *= attribute.stride;
    for (let i2 = 0, l2 = this.stride; i2 < l2; i2++) {
      this.array[index1 + i2] = attribute.array[index2 + i2];
    }
    return this;
  }
  set(value, offset = 0) {
    this.array.set(value, offset);
    return this;
  }
  clone(data) {
    if (data.arrayBuffers === void 0) {
      data.arrayBuffers = {};
    }
    if (this.array.buffer._uuid === void 0) {
      this.array.buffer._uuid = generateUUID();
    }
    if (data.arrayBuffers[this.array.buffer._uuid] === void 0) {
      data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
    }
    const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
    const ib = new this.constructor(array, this.stride);
    ib.setUsage(this.usage);
    return ib;
  }
  onUpload(callback) {
    this.onUploadCallback = callback;
    return this;
  }
  toJSON(data) {
    if (data.arrayBuffers === void 0) {
      data.arrayBuffers = {};
    }
    if (this.array.buffer._uuid === void 0) {
      this.array.buffer._uuid = generateUUID();
    }
    if (data.arrayBuffers[this.array.buffer._uuid] === void 0) {
      data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
    }
    return {
      uuid: this.uuid,
      buffer: this.array.buffer._uuid,
      type: this.array.constructor.name,
      stride: this.stride
    };
  }
}
const _vector$7 = /* @__PURE__ */ new Vector3();
class InterleavedBufferAttribute {
  constructor(interleavedBuffer, itemSize, offset, normalized = false) {
    this.isInterleavedBufferAttribute = true;
    this.name = "";
    this.data = interleavedBuffer;
    this.itemSize = itemSize;
    this.offset = offset;
    this.normalized = normalized;
  }
  get count() {
    return this.data.count;
  }
  get array() {
    return this.data.array;
  }
  set needsUpdate(value) {
    this.data.needsUpdate = value;
  }
  applyMatrix4(m2) {
    for (let i2 = 0, l2 = this.data.count; i2 < l2; i2++) {
      _vector$7.fromBufferAttribute(this, i2);
      _vector$7.applyMatrix4(m2);
      this.setXYZ(i2, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  applyNormalMatrix(m2) {
    for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
      _vector$7.fromBufferAttribute(this, i2);
      _vector$7.applyNormalMatrix(m2);
      this.setXYZ(i2, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  transformDirection(m2) {
    for (let i2 = 0, l2 = this.count; i2 < l2; i2++) {
      _vector$7.fromBufferAttribute(this, i2);
      _vector$7.transformDirection(m2);
      this.setXYZ(i2, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  getComponent(index, component) {
    let value = this.array[index * this.data.stride + this.offset + component];
    if (this.normalized) value = denormalize(value, this.array);
    return value;
  }
  setComponent(index, component, value) {
    if (this.normalized) value = normalize(value, this.array);
    this.data.array[index * this.data.stride + this.offset + component] = value;
    return this;
  }
  setX(index, x) {
    if (this.normalized) x = normalize(x, this.array);
    this.data.array[index * this.data.stride + this.offset] = x;
    return this;
  }
  setY(index, y2) {
    if (this.normalized) y2 = normalize(y2, this.array);
    this.data.array[index * this.data.stride + this.offset + 1] = y2;
    return this;
  }
  setZ(index, z2) {
    if (this.normalized) z2 = normalize(z2, this.array);
    this.data.array[index * this.data.stride + this.offset + 2] = z2;
    return this;
  }
  setW(index, w2) {
    if (this.normalized) w2 = normalize(w2, this.array);
    this.data.array[index * this.data.stride + this.offset + 3] = w2;
    return this;
  }
  getX(index) {
    let x = this.data.array[index * this.data.stride + this.offset];
    if (this.normalized) x = denormalize(x, this.array);
    return x;
  }
  getY(index) {
    let y2 = this.data.array[index * this.data.stride + this.offset + 1];
    if (this.normalized) y2 = denormalize(y2, this.array);
    return y2;
  }
  getZ(index) {
    let z2 = this.data.array[index * this.data.stride + this.offset + 2];
    if (this.normalized) z2 = denormalize(z2, this.array);
    return z2;
  }
  getW(index) {
    let w2 = this.data.array[index * this.data.stride + this.offset + 3];
    if (this.normalized) w2 = denormalize(w2, this.array);
    return w2;
  }
  setXY(index, x, y2) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
    }
    this.data.array[index + 0] = x;
    this.data.array[index + 1] = y2;
    return this;
  }
  setXYZ(index, x, y2, z2) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
    }
    this.data.array[index + 0] = x;
    this.data.array[index + 1] = y2;
    this.data.array[index + 2] = z2;
    return this;
  }
  setXYZW(index, x, y2, z2, w2) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x = normalize(x, this.array);
      y2 = normalize(y2, this.array);
      z2 = normalize(z2, this.array);
      w2 = normalize(w2, this.array);
    }
    this.data.array[index + 0] = x;
    this.data.array[index + 1] = y2;
    this.data.array[index + 2] = z2;
    this.data.array[index + 3] = w2;
    return this;
  }
  clone(data) {
    if (data === void 0) {
      console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const array = [];
      for (let i2 = 0; i2 < this.count; i2++) {
        const index = i2 * this.data.stride + this.offset;
        for (let j2 = 0; j2 < this.itemSize; j2++) {
          array.push(this.data.array[index + j2]);
        }
      }
      return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
    } else {
      if (data.interleavedBuffers === void 0) {
        data.interleavedBuffers = {};
      }
      if (data.interleavedBuffers[this.data.uuid] === void 0) {
        data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
      }
      return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
    }
  }
  toJSON(data) {
    if (data === void 0) {
      console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const array = [];
      for (let i2 = 0; i2 < this.count; i2++) {
        const index = i2 * this.data.stride + this.offset;
        for (let j2 = 0; j2 < this.itemSize; j2++) {
          array.push(this.data.array[index + j2]);
        }
      }
      return {
        itemSize: this.itemSize,
        type: this.array.constructor.name,
        array,
        normalized: this.normalized
      };
    } else {
      if (data.interleavedBuffers === void 0) {
        data.interleavedBuffers = {};
      }
      if (data.interleavedBuffers[this.data.uuid] === void 0) {
        data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
      }
      return {
        isInterleavedBufferAttribute: true,
        itemSize: this.itemSize,
        data: this.data.uuid,
        offset: this.offset,
        normalized: this.normalized
      };
    }
  }
}
class SpriteMaterial extends Material {
  constructor(parameters) {
    super();
    this.isSpriteMaterial = true;
    this.type = "SpriteMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.alphaMap = null;
    this.rotation = 0;
    this.sizeAttenuation = true;
    this.transparent = true;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.alphaMap = source.alphaMap;
    this.rotation = source.rotation;
    this.sizeAttenuation = source.sizeAttenuation;
    this.fog = source.fog;
    return this;
  }
}
let _geometry;
const _intersectPoint = /* @__PURE__ */ new Vector3();
const _worldScale = /* @__PURE__ */ new Vector3();
const _mvPosition = /* @__PURE__ */ new Vector3();
const _alignedPosition = /* @__PURE__ */ new Vector2();
const _rotatedPosition = /* @__PURE__ */ new Vector2();
const _viewWorldMatrix = /* @__PURE__ */ new Matrix4();
const _vA = /* @__PURE__ */ new Vector3();
const _vB = /* @__PURE__ */ new Vector3();
const _vC = /* @__PURE__ */ new Vector3();
const _uvA = /* @__PURE__ */ new Vector2();
const _uvB = /* @__PURE__ */ new Vector2();
const _uvC = /* @__PURE__ */ new Vector2();
class Sprite extends Object3D {
  constructor(material = new SpriteMaterial()) {
    super();
    this.isSprite = true;
    this.type = "Sprite";
    if (_geometry === void 0) {
      _geometry = new BufferGeometry();
      const float32Array = new Float32Array([
        -0.5,
        -0.5,
        0,
        0,
        0,
        0.5,
        -0.5,
        0,
        1,
        0,
        0.5,
        0.5,
        0,
        1,
        1,
        -0.5,
        0.5,
        0,
        0,
        1
      ]);
      const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
      _geometry.setIndex([0, 1, 2, 0, 2, 3]);
      _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
      _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
    }
    this.geometry = _geometry;
    this.material = material;
    this.center = new Vector2(0.5, 0.5);
  }
  raycast(raycaster, intersects2) {
    if (raycaster.camera === null) {
      console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
    }
    _worldScale.setFromMatrixScale(this.matrixWorld);
    _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
    this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
    _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
    if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
      _worldScale.multiplyScalar(-_mvPosition.z);
    }
    const rotation = this.material.rotation;
    let sin, cos;
    if (rotation !== 0) {
      cos = Math.cos(rotation);
      sin = Math.sin(rotation);
    }
    const center = this.center;
    transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
    transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
    transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
    _uvA.set(0, 0);
    _uvB.set(1, 0);
    _uvC.set(1, 1);
    let intersect2 = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
    if (intersect2 === null) {
      transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
      _uvB.set(0, 1);
      intersect2 = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
      if (intersect2 === null) {
        return;
      }
    }
    const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
    if (distance < raycaster.near || distance > raycaster.far) return;
    intersects2.push({
      distance,
      point: _intersectPoint.clone(),
      uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
      face: null,
      object: this
    });
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.center !== void 0) this.center.copy(source.center);
    this.material = source.material;
    return this;
  }
}
function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale);
  if (sin !== void 0) {
    _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
    _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  } else {
    _rotatedPosition.copy(_alignedPosition);
  }
  vertexPosition.copy(mvPosition);
  vertexPosition.x += _rotatedPosition.x;
  vertexPosition.y += _rotatedPosition.y;
  vertexPosition.applyMatrix4(_viewWorldMatrix);
}
const _v1$2 = /* @__PURE__ */ new Vector3();
const _v2$1 = /* @__PURE__ */ new Vector3();
class LOD extends Object3D {
  constructor() {
    super();
    this._currentLevel = 0;
    this.type = "LOD";
    Object.defineProperties(this, {
      levels: {
        enumerable: true,
        value: []
      },
      isLOD: {
        value: true
      }
    });
    this.autoUpdate = true;
  }
  copy(source) {
    super.copy(source, false);
    const levels = source.levels;
    for (let i2 = 0, l2 = levels.length; i2 < l2; i2++) {
      const level = levels[i2];
      this.addLevel(level.object.clone(), level.distance, level.hysteresis);
    }
    this.autoUpdate = source.autoUpdate;
    return this;
  }
  addLevel(object, distance = 0, hysteresis = 0) {
    distance = Math.abs(distance);
    const levels = this.levels;
    let l2;
    for (l2 = 0; l2 < levels.length; l2++) {
      if (distance < levels[l2].distance) {
        break;
      }
    }
    levels.splice(l2, 0, { distance, hysteresis, object });
    this.add(object);
    return this;
  }
  removeLevel(distance) {
    const levels = this.levels;
    for (let i2 = 0; i2 < levels.length; i2++) {
      if (levels[i2].distance === distance) {
        const removedElements = levels.splice(i2, 1);
        this.remove(removedElements[0].object);
        return true;
      }
    }
    return false;
  }
  getCurrentLevel() {
    return this._currentLevel;
  }
  getObjectForDistance(distance) {
    const levels = this.levels;
    if (levels.length > 0) {
      let i2, l2;
      for (i2 = 1, l2 = levels.length; i2 < l2; i2++) {
        let levelDistance = levels[i2].distance;
        if (levels[i2].object.visible) {
          levelDistance -= levelDistance * levels[i2].hysteresis;
        }
        if (distance < levelDistance) {
          break;
        }
      }
      return levels[i2 - 1].object;
    }
    return null;
  }
  raycast(raycaster, intersects2) {
    const levels = this.levels;
    if (levels.length > 0) {
      _v1$2.setFromMatrixPosition(this.matrixWorld);
      const distance = raycaster.ray.origin.distanceTo(_v1$2);
      this.getObjectForDistance(distance).raycast(raycaster, intersects2);
    }
  }
  update(camera) {
    const levels = this.levels;
    if (levels.length > 1) {
      _v1$2.setFromMatrixPosition(camera.matrixWorld);
      _v2$1.setFromMatrixPosition(this.matrixWorld);
      const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
      levels[0].object.visible = true;
      let i2, l2;
      for (i2 = 1, l2 = levels.length; i2 < l2; i2++) {
        let levelDistance = levels[i2].distance;
        if (levels[i2].object.visible) {
          levelDistance -= levelDistance * levels[i2].hysteresis;
        }
        if (distance >= levelDistance) {
          levels[i2 - 1].object.visible = false;
          levels[i2].object.visible = true;
        } else {
          break;
        }
      }
      this._currentLevel = i2 - 1;
      for (; i2 < l2; i2++) {
        levels[i2].object.visible = false;
      }
    }
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    if (this.autoUpdate === false) data.object.autoUpdate = false;
    data.object.levels = [];
    const levels = this.levels;
    for (let i2 = 0, l2 = levels.length; i2 < l2; i2++) {
      const level = levels[i2];
      data.object.levels.push({
        object: level.object.uuid,
        distance: level.distance,
        hysteresis: level.hysteresis
      });
    }
    return data;
  }
}
const _basePosition = /* @__PURE__ */ new Vector3();
const _skinIndex = /* @__PURE__ */ new Vector4();
const _skinWeight = /* @__PURE__ */ new Vector4();
const _vector3 = /* @__PURE__ */ new Vector3();
const _matrix4 = /* @__PURE__ */ new Matrix4();
const _vertex = /* @__PURE__ */ new Vector3();
const _sphere$5 = /* @__PURE__ */ new Sphere();
const _inverseMatrix$2 = /* @__PURE__ */ new Matrix4();
const _ray$2 = /* @__PURE__ */ new Ray();
class SkinnedMesh extends Mesh {
  constructor(geometry, material) {
    super(geometry, material);
    this.isSkinnedMesh = true;
    this.type = "SkinnedMesh";
    this.bindMode = AttachedBindMode;
    this.bindMatrix = new Matrix4();
    this.bindMatrixInverse = new Matrix4();
    this.boundingBox = null;
    this.boundingSphere = null;
  }
  computeBoundingBox() {
    const geometry = this.geometry;
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    this.boundingBox.makeEmpty();
    const positionAttribute = geometry.getAttribute("position");
    for (let i2 = 0; i2 < positionAttribute.count; i2++) {
      this.getVertexPosition(i2, _vertex);
      this.boundingBox.expandByPoint(_vertex);
    }
  }
  computeBoundingSphere() {
    const geometry = this.geometry;
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    this.boundingSphere.makeEmpty();
    const positionAttribute = geometry.getAttribute("position");
    for (let i2 = 0; i2 < positionAttribute.count; i2++) {
      this.getVertexPosition(i2, _vertex);
      this.boundingSphere.expandByPoint(_vertex);
    }
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.bindMode = source.bindMode;
    this.bindMatrix.copy(source.bindMatrix);
    this.bindMatrixInverse.copy(source.bindMatrixInverse);
    this.skeleton = source.skeleton;
    if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone();
    if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone();
    return this;
  }
  raycast(raycaster, intersects2) {
    const material = this.material;
    const matrixWorld = this.matrixWorld;
    if (material === void 0) return;
    if (this.boundingSphere === null) this.computeBoundingSphere();
    _sphere$5.copy(this.boundingSphere);
    _sphere$5.applyMatrix4(matrixWorld);
    if (raycaster.ray.intersectsSphere(_sphere$5) === false) return;
    _inverseMatrix$2.copy(matrixWorld).invert();
    _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
    if (this.boundingBox !== null) {
      if (_ray$2.intersectsBox(this.boundingBox) === false) return;
    }
    this._computeIntersections(raycaster, intersects2, _ray$2);
  }
  getVertexPosition(index, target) {
    super.getVertexPosition(index, target);
    this.applyBoneTransform(index, target);
    return target;
  }
  bind(skeleton, bindMatrix) {
    this.skeleton = skeleton;
    if (bindMatrix === void 0) {
      this.updateMatrixWorld(true);
      this.skeleton.calculateInverses();
      bindMatrix = this.matrixWorld;
    }
    this.bindMatrix.copy(bindMatrix);
    this.bindMatrixInverse.copy(bindMatrix).invert();
  }
  pose() {
    this.skeleton.pose();
  }
  normalizeSkinWeights() {
    const vector = new Vector4();
    const skinWeight = this.geometry.attributes.skinWeight;
    for (let i2 = 0, l2 = skinWeight.count; i2 < l2; i2++) {
      vector.fromBufferAttribute(skinWeight, i2);
      const scale = 1 / vector.manhattanLength();
      if (scale !== Infinity) {
        vector.multiplyScalar(scale);
      } else {
        vector.set(1, 0, 0, 0);
      }
      skinWeight.setXYZW(i2, vector.x, vector.y, vector.z, vector.w);
    }
  }
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (this.bindMode === AttachedBindMode) {
      this.bindMatrixInverse.copy(this.matrixWorld).invert();
    } else if (this.bindMode === DetachedBindMode) {
      this.bindMatrixInverse.copy(this.bindMatrix).invert();
    } else {
      console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
    }
  }
  applyBoneTransform(index, vector) {
    const skeleton = this.skeleton;
    const geometry = this.geometry;
    _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
    _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
    _basePosition.copy(vector).applyMatrix4(this.bindMatrix);
    vector.set(0, 0, 0);
    for (let i2 = 0; i2 < 4; i2++) {
      const weight = _skinWeight.getComponent(i2);
      if (weight !== 0) {
        const boneIndex = _skinIndex.getComponent(i2);
        _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
        vector.addScaledVector(_vector3.copy(_basePosition).applyMatrix4(_matrix4), weight);
      }
    }
    return vector.applyMatrix4(this.bindMatrixInverse);
  }
}
class Bone extends Object3D {
  constructor() {
    super();
    this.isBone = true;
    this.type = "Bone";
  }
}
class DataTexture extends Texture {
  constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) {
    super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace);
    this.isDataTexture = true;
    this.image = { data, width, height };
    this.generateMipmaps = false;
    this.flipY = false;
    this.unpackAlignment = 1;
  }
}
const _offsetMatrix = /* @__PURE__ */ new Matrix4();
const _identityMatrix = /* @__PURE__ */ new Matrix4();
class Skeleton {
  constructor(bones = [], boneInverses = []) {
    this.uuid = generateUUID();
    this.bones = bones.slice(0);
    this.boneInverses = boneInverses;
    this.boneMatrices = null;
    this.boneTexture = null;
    this.init();
  }
  init() {
    const bones = this.bones;
    const boneInverses = this.boneInverses;
    this.boneMatrices = new Float32Array(bones.length * 16);
    if (boneInverses.length === 0) {
      this.calculateInverses();
    } else {
      if (bones.length !== boneInverses.length) {
        console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.");
        this.boneInverses = [];
        for (let i2 = 0, il = this.bones.length; i2 < il; i2++) {
          this.boneInverses.push(new Matrix4());
        }
      }
    }
  }
  calculateInverses() {
    this.boneInverses.length = 0;
    for (let i2 = 0, il = this.bones.length; i2 < il; i2++) {
      const inverse = new Matrix4();
      if (this.bones[i2]) {
        inverse.copy(this.bones[i2].matrixWorld).invert();
      }
      this.boneInverses.push(inverse);
    }
  }
  pose() {
    for (let i2 = 0, il = this.bones.length; i2 < il; i2++) {
      const bone = this.bones[i2];
      if (bone) {
        bone.matrixWorld.copy(this.boneInverses[i2]).invert();
      }
    }
    for (let i2 = 0, il = this.bones.length; i2 < il; i2++) {
      const bone = this.bones[i2];
      if (bone) {
        if (bone.parent && bone.parent.isBone) {
          bone.matrix.copy(bone.parent.matrixWorld).invert();
          bone.matrix.multiply(bone.matrixWorld);
        } else {
          bone.matrix.copy(bone.matrixWorld);
        }
        bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
      }
    }
  }
  update() {
    const bones = this.bones;
    const boneInverses = this.boneInverses;
    const boneMatrices = this.boneMatrices;
    const boneTexture = this.boneTexture;
    for (let i2 = 0, il = bones.length; i2 < il; i2++) {
      const matrix = bones[i2] ? bones[i2].matrixWorld : _identityMatrix;
      _offsetMatrix.multiplyMatrices(matrix, boneInverses[i2]);
      _offsetMatrix.toArray(boneMatrices, i2 * 16);
    }
    if (boneTexture !== null) {
      boneTexture.needsUpdate = true;
    }
  }
  clone() {
    return new Skeleton(this.bones, this.boneInverses);
  }
  computeBoneTexture() {
    let size = Math.sqrt(this.bones.length * 4);
    size = Math.ceil(size / 4) * 4;
    size = Math.max(size, 4);
    const boneMatrices = new Float32Array(size * size * 4);
    boneMatrices.set(this.boneMatrices);
    const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
    boneTexture.needsUpdate = true;
    this.boneMatrices = boneMatrices;
    this.boneTexture = boneTexture;
    return this;
  }
  getBoneByName(name) {
    for (let i2 = 0, il = this.bones.length; i2 < il; i2++) {
      const bone = this.bones[i2];
      if (bone.name === name) {
        return bone;
      }
    }
    return void 0;
  }
  dispose() {
    if (this.boneTexture !== null) {
      this.boneTexture.dispose();
      this.boneTexture = null;
    }
  }
  fromJSON(json3, bones) {
    this.uuid = json3.uuid;
    for (let i2 = 0, l2 = json3.bones.length; i2 < l2; i2++) {
      const uuid = json3.bones[i2];
      let bone = bones[uuid];
      if (bone === void 0) {
        console.warn("THREE.Skeleton: No bone found with UUID:", uuid);
        bone = new Bone();
      }
      this.bones.push(bone);
      this.boneInverses.push(new Matrix4().fromArray(json3.boneInverses[i2]));
    }
    this.init();
    return this;
  }
  toJSON() {
    const data = {
      metadata: {
        version: 4.6,
        type: "Skeleton",
        generator: "Skeleton.toJSON"
      },
      bones: [],
      boneInverses: []
    };
    data.uuid = this.uuid;
    const bones = this.bones;
    const boneInverses = this.boneInverses;
    for (let i2 = 0, l2 = bones.length; i2 < l2; i2++) {
      const bone = bones[i2];
      data.bones.push(bone.uuid);
      const boneInverse = boneInverses[i2];
      data.boneInverses.push(boneInverse.toArray());
    }
    return data;
  }
}
class InstancedBufferAttribute extends BufferAttribute {
  constructor(array, itemSize, normalized, meshPerAttribute = 1) {
    super(array, itemSize, normalized);
    this.isInstancedBufferAttribute = true;
    this.meshPerAttribute = meshPerAttribute;
  }
  copy(source) {
    super.copy(source);
    this.meshPerAttribute = source.meshPerAttribute;
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.meshPerAttribute = this.meshPerAttribute;
    data.isInstancedBufferAttribute = true;
    return data;
  }
}
const _instanceLocalMatrix = /* @__PURE__ */ new Matrix4();
const _instanceWorldMatrix = /* @__PURE__ */ new Matrix4();
const _instanceIntersects = [];
const _box3 = /* @__PURE__ */ new Box3();
const _identity = /* @__PURE__ */ new Matrix4();
const _mesh$1 = /* @__PURE__ */ new Mesh();
const _sphere$4 = /* @__PURE__ */ new Sphere();
class InstancedMesh extends Mesh {
  constructor(geometry, material, count) {
    super(geometry, material);
    this.isInstancedMesh = true;
    this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
    this.instanceColor = null;
    this.morphTexture = null;
    this.count = count;
    this.boundingBox = null;
    this.boundingSphere = null;
    for (let i2 = 0; i2 < count; i2++) {
      this.setMatrixAt(i2, _identity);
    }
  }
  computeBoundingBox() {
    const geometry = this.geometry;
    const count = this.count;
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    if (geometry.boundingBox === null) {
      geometry.computeBoundingBox();
    }
    this.boundingBox.makeEmpty();
    for (let i2 = 0; i2 < count; i2++) {
      this.getMatrixAt(i2, _instanceLocalMatrix);
      _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix);
      this.boundingBox.union(_box3);
    }
  }
  computeBoundingSphere() {
    const geometry = this.geometry;
    const count = this.count;
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    if (geometry.boundingSphere === null) {
      geometry.computeBoundingSphere();
    }
    this.boundingSphere.makeEmpty();
    for (let i2 = 0; i2 < count; i2++) {
      this.getMatrixAt(i2, _instanceLocalMatrix);
      _sphere$4.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix);
      this.boundingSphere.union(_sphere$4);
    }
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.instanceMatrix.copy(source.instanceMatrix);
    if (source.morphTexture !== null) this.morphTexture = source.morphTexture.clone();
    if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
    this.count = source.count;
    if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone();
    if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone();
    return this;
  }
  getColorAt(index, color) {
    color.fromArray(this.instanceColor.array, index * 3);
  }
  getMatrixAt(index, matrix) {
    matrix.fromArray(this.instanceMatrix.array, index * 16);
  }
  getMorphAt(index, object) {
    const objectInfluences = object.morphTargetInfluences;
    const array = this.morphTexture.source.data.data;
    const len = objectInfluences.length + 1;
    const dataIndex = index * len + 1;
    for (let i2 = 0; i2 < objectInfluences.length; i2++) {
      objectInfluences[i2] = array[dataIndex + i2];
    }
  }
  raycast(raycaster, intersects2) {
    const matrixWorld = this.matrixWorld;
    const raycastTimes = this.count;
    _mesh$1.geometry = this.geometry;
    _mesh$1.material = this.material;
    if (_mesh$1.material === void 0) return;
    if (this.boundingSphere === null) this.computeBoundingSphere();
    _sphere$4.copy(this.boundingSphere);
    _sphere$4.applyMatrix4(matrixWorld);
    if (raycaster.ray.intersectsSphere(_sphere$4) === false) return;
    for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
      this.getMatrixAt(instanceId, _instanceLocalMatrix);
      _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix);
      _mesh$1.matrixWorld = _instanceWorldMatrix;
      _mesh$1.raycast(raycaster, _instanceIntersects);
      for (let i2 = 0, l2 = _instanceIntersects.length; i2 < l2; i2++) {
        const intersect2 = _instanceIntersects[i2];
        intersect2.instanceId = instanceId;
        intersect2.object = this;
        intersects2.push(intersect2);
      }
      _instanceIntersects.length = 0;
    }
  }
  setColorAt(index, color) {
    if (this.instanceColor === null) {
      this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3);
    }
    color.toArray(this.instanceColor.array, index * 3);
  }
  setMatrixAt(index, matrix) {
    matrix.toArray(this.instanceMatrix.array, index * 16);
  }
  setMorphAt(index, object) {
    const objectInfluences = object.morphTargetInfluences;
    const len = objectInfluences.length + 1;
    if (this.morphTexture === null) {
      this.morphTexture = new DataTexture(new Float32Array(len * this.count), len, this.count, RedFormat, FloatType);
    }
    const array = this.morphTexture.source.data.data;
    let morphInfluencesSum = 0;
    for (let i2 = 0; i2 < objectInfluences.length; i2++) {
      morphInfluencesSum += objectInfluences[i2];
    }
    const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
    const dataIndex = len * index;
    array[dataIndex] = morphBaseInfluence;
    array.set(objectInfluences, dataIndex + 1);
  }
  updateMorphTargets() {
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
    if (this.morphTexture !== null) {
      this.morphTexture.dispose();
      this.morphTexture = null;
    }
    return this;
  }
}
const _vector1 = /* @__PURE__ */ new Vector3();
const _vector2 = /* @__PURE__ */ new Vector3();
const _normalMatrix = /* @__PURE__ */ new Matrix3();
class Plane {
  constructor(normal = new Vector3(1, 0, 0), constant = 0) {
    this.isPlane = true;
    this.normal = normal;
    this.constant = constant;
  }
  set(normal, constant) {
    this.normal.copy(normal);
    this.constant = constant;
    return this;
  }
  setComponents(x, y2, z2, w2) {
    this.normal.set(x, y2, z2);
    this.constant = w2;
    return this;
  }
  setFromNormalAndCoplanarPoint(normal, point) {
    this.normal.copy(normal);
    this.constant = -point.dot(this.normal);
    return this;
  }
  setFromCoplanarPoints(a3, b2, c2) {
    const normal = _vector1.subVectors(c2, b2).cross(_vector2.subVectors(a3, b2)).normalize();
    this.setFromNormalAndCoplanarPoint(normal, a3);
    return this;
  }
  copy(plane) {
    this.normal.copy(plane.normal);
    this.constant = plane.constant;
    return this;
  }
  normalize() {
    const inverseNormalLength = 1 / this.normal.length();
    this.normal.multiplyScalar(inverseNormalLength);
    this.constant *= inverseNormalLength;
    return this;
  }
  negate() {
    this.constant *= -1;
    this.normal.negate();
    return this;
  }
  distanceToPoint(point) {
    return this.normal.dot(point) + this.constant;
  }
  distanceToSphere(sphere) {
    return this.distanceToPoint(sphere.center) - sphere.radius;
  }
  projectPoint(point, target) {
    return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point));
  }
  intersectLine(line, target) {
    const direction = line.delta(_vector1);
    const denominator = this.normal.dot(direction);
    if (denominator === 0) {
      if (this.distanceToPoint(line.start) === 0) {
        return target.copy(line.start);
      }
      return null;
    }
    const t2 = -(line.start.dot(this.normal) + this.constant) / denominator;
    if (t2 < 0 || t2 > 1) {
      return null;
    }
    return target.copy(line.start).addScaledVector(direction, t2);
  }
  intersectsLine(line) {
    const startSign = this.distanceToPoint(line.start);
    const endSign = this.distanceToPoint(line.end);
    return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  }
  intersectsBox(box) {
    return box.intersectsPlane(this);
  }
  intersectsSphere(sphere) {
    return sphere.intersectsPlane(this);
  }
  coplanarPoint(target) {
    return target.copy(this.normal).multiplyScalar(-this.constant);
  }
  applyMatrix4(matrix, optionalNormalMatrix) {
    const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
    const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
    const normal = this.normal.applyMatrix3(normalMatrix).normalize();
    this.constant = -referencePoint.dot(normal);
    return this;
  }
  translate(offset) {
    this.constant -= offset.dot(this.normal);
    return this;
  }
  equals(plane) {
    return plane.normal.equals(this.normal) && plane.constant === this.constant;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const _sphere$3 = /* @__PURE__ */ new Sphere();
const _vector$6 = /* @__PURE__ */ new Vector3();
class Frustum {
  constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
    this.planes = [p0, p1, p2, p3, p4, p5];
  }
  set(p0, p1, p2, p3, p4, p5) {
    const planes = this.planes;
    planes[0].copy(p0);
    planes[1].copy(p1);
    planes[2].copy(p2);
    planes[3].copy(p3);
    planes[4].copy(p4);
    planes[5].copy(p5);
    return this;
  }
  copy(frustum) {
    const planes = this.planes;
    for (let i2 = 0; i2 < 6; i2++) {
      planes[i2].copy(frustum.planes[i2]);
    }
    return this;
  }
  setFromProjectionMatrix(m2, coordinateSystem = WebGLCoordinateSystem) {
    const planes = this.planes;
    const me2 = m2.elements;
    const me0 = me2[0], me1 = me2[1], me22 = me2[2], me3 = me2[3];
    const me4 = me2[4], me5 = me2[5], me6 = me2[6], me7 = me2[7];
    const me8 = me2[8], me9 = me2[9], me10 = me2[10], me11 = me2[11];
    const me12 = me2[12], me13 = me2[13], me14 = me2[14], me15 = me2[15];
    planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
    planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
    planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
    planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
    planes[4].setComponents(me3 - me22, me7 - me6, me11 - me10, me15 - me14).normalize();
    if (coordinateSystem === WebGLCoordinateSystem) {
      planes[5].setComponents(me3 + me22, me7 + me6, me11 + me10, me15 + me14).normalize();
    } else if (coordinateSystem === WebGPUCoordinateSystem) {
      planes[5].setComponents(me22, me6, me10, me14).normalize();
    } else {
      throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem);
    }
    return this;
  }
  intersectsObject(object) {
    if (object.boundingSphere !== void 0) {
      if (object.boundingSphere === null) object.computeBoundingSphere();
      _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld);
    } else {
      const geometry = object.geometry;
      if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
      _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
    }
    return this.intersectsSphere(_sphere$3);
  }
  intersectsSprite(sprite) {
    _sphere$3.center.set(0, 0, 0);
    _sphere$3.radius = 0.7071067811865476;
    _sphere$3.applyMatrix4(sprite.matrixWorld);
    return this.intersectsSphere(_sphere$3);
  }
  intersectsSphere(sphere) {
    const planes = this.planes;
    const center = sphere.center;
    const negRadius = -sphere.radius;
    for (let i2 = 0; i2 < 6; i2++) {
      const distance = planes[i2].distanceToPoint(center);
      if (distance < negRadius) {
        return false;
      }
    }
    return true;
  }
  intersectsBox(box) {
    const planes = this.planes;
    for (let i2 = 0; i2 < 6; i2++) {
      const plane = planes[i2];
      _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
      _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
      _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
      if (plane.distanceToPoint(_vector$6) < 0) {
        return false;
      }
    }
    return true;
  }
  containsPoint(point) {
    const planes = this.planes;
    for (let i2 = 0; i2 < 6; i2++) {
      if (planes[i2].distanceToPoint(point) < 0) {
        return false;
      }
    }
    return true;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
function ascIdSort(a3, b2) {
  return a3 - b2;
}
function sortOpaque(a3, b2) {
  return a3.z - b2.z;
}
function sortTransparent(a3, b2) {
  return b2.z - a3.z;
}
class MultiDrawRenderList {
  constructor() {
    this.index = 0;
    this.pool = [];
    this.list = [];
  }
  push(start, count, z2, index) {
    const pool = this.pool;
    const list = this.list;
    if (this.index >= pool.length) {
      pool.push({
        start: -1,
        count: -1,
        z: -1,
        index: -1
      });
    }
    const item = pool[this.index];
    list.push(item);
    this.index++;
    item.start = start;
    item.count = count;
    item.z = z2;
    item.index = index;
  }
  reset() {
    this.list.length = 0;
    this.index = 0;
  }
}
const _matrix$1 = /* @__PURE__ */ new Matrix4();
const _whiteColor = /* @__PURE__ */ new Color(1, 1, 1);
const _frustum = /* @__PURE__ */ new Frustum();
const _box$1$1 = /* @__PURE__ */ new Box3();
const _sphere$2 = /* @__PURE__ */ new Sphere();
const _vector$5 = /* @__PURE__ */ new Vector3();
const _forward = /* @__PURE__ */ new Vector3();
const _temp = /* @__PURE__ */ new Vector3();
const _renderList = /* @__PURE__ */ new MultiDrawRenderList();
const _mesh = /* @__PURE__ */ new Mesh();
const _batchIntersects = [];
function copyAttributeData(src, target, targetOffset = 0) {
  const itemSize = target.itemSize;
  if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) {
    const vertexCount = src.count;
    for (let i2 = 0; i2 < vertexCount; i2++) {
      for (let c2 = 0; c2 < itemSize; c2++) {
        target.setComponent(i2 + targetOffset, c2, src.getComponent(i2, c2));
      }
    }
  } else {
    target.array.set(src.array, targetOffset * itemSize);
  }
  target.needsUpdate = true;
}
function copyArrayContents(src, target) {
  if (src.constructor !== target.constructor) {
    const len = Math.min(src.length, target.length);
    for (let i2 = 0; i2 < len; i2++) {
      target[i2] = src[i2];
    }
  } else {
    const len = Math.min(src.length, target.length);
    target.set(new src.constructor(src.buffer, 0, len));
  }
}
class BatchedMesh extends Mesh {
  get maxInstanceCount() {
    return this._maxInstanceCount;
  }
  get instanceCount() {
    return this._instanceInfo.length - this._availableInstanceIds.length;
  }
  get unusedVertexCount() {
    return this._maxVertexCount - this._nextVertexStart;
  }
  get unusedIndexCount() {
    return this._maxIndexCount - this._nextIndexStart;
  }
  constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) {
    super(new BufferGeometry(), material);
    this.isBatchedMesh = true;
    this.perObjectFrustumCulled = true;
    this.sortObjects = true;
    this.boundingBox = null;
    this.boundingSphere = null;
    this.customSort = null;
    this._instanceInfo = [];
    this._geometryInfo = [];
    this._availableInstanceIds = [];
    this._availableGeometryIds = [];
    this._nextIndexStart = 0;
    this._nextVertexStart = 0;
    this._geometryCount = 0;
    this._visibilityChanged = true;
    this._geometryInitialized = false;
    this._maxInstanceCount = maxInstanceCount;
    this._maxVertexCount = maxVertexCount;
    this._maxIndexCount = maxIndexCount;
    this._multiDrawCounts = new Int32Array(maxInstanceCount);
    this._multiDrawStarts = new Int32Array(maxInstanceCount);
    this._multiDrawCount = 0;
    this._multiDrawInstances = null;
    this._matricesTexture = null;
    this._indirectTexture = null;
    this._colorsTexture = null;
    this._initMatricesTexture();
    this._initIndirectTexture();
  }
  _initMatricesTexture() {
    let size = Math.sqrt(this._maxInstanceCount * 4);
    size = Math.ceil(size / 4) * 4;
    size = Math.max(size, 4);
    const matricesArray = new Float32Array(size * size * 4);
    const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType);
    this._matricesTexture = matricesTexture;
  }
  _initIndirectTexture() {
    let size = Math.sqrt(this._maxInstanceCount);
    size = Math.ceil(size);
    const indirectArray = new Uint32Array(size * size);
    const indirectTexture = new DataTexture(indirectArray, size, size, RedIntegerFormat, UnsignedIntType);
    this._indirectTexture = indirectTexture;
  }
  _initColorsTexture() {
    let size = Math.sqrt(this._maxInstanceCount);
    size = Math.ceil(size);
    const colorsArray = new Float32Array(size * size * 4).fill(1);
    const colorsTexture = new DataTexture(colorsArray, size, size, RGBAFormat, FloatType);
    colorsTexture.colorSpace = ColorManagement.workingColorSpace;
    this._colorsTexture = colorsTexture;
  }
  _initializeGeometry(reference) {
    const geometry = this.geometry;
    const maxVertexCount = this._maxVertexCount;
    const maxIndexCount = this._maxIndexCount;
    if (this._geometryInitialized === false) {
      for (const attributeName in reference.attributes) {
        const srcAttribute = reference.getAttribute(attributeName);
        const { array, itemSize, normalized } = srcAttribute;
        const dstArray = new array.constructor(maxVertexCount * itemSize);
        const dstAttribute = new BufferAttribute(dstArray, itemSize, normalized);
        geometry.setAttribute(attributeName, dstAttribute);
      }
      if (reference.getIndex() !== null) {
        const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount);
        geometry.setIndex(new BufferAttribute(indexArray, 1));
      }
      this._geometryInitialized = true;
    }
  }
  // Make sure the geometry is compatible with the existing combined geometry attributes
  _validateGeometry(geometry) {
    const batchGeometry = this.geometry;
    if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) {
      throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');
    }
    for (const attributeName in batchGeometry.attributes) {
      if (!geometry.hasAttribute(attributeName)) {
        throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`);
      }
      const srcAttribute = geometry.getAttribute(attributeName);
      const dstAttribute = batchGeometry.getAttribute(attributeName);
      if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) {
        throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.");
      }
    }
  }
  validateInstanceId(instanceId) {
    const instanceInfo = this._instanceInfo;
    if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) {
      throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`);
    }
  }
  validateGeometryId(geometryId) {
    const geometryInfoList = this._geometryInfo;
    if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) {
      throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`);
    }
  }
  setCustomSort(func) {
    this.customSort = func;
    return this;
  }
  computeBoundingBox() {
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    const boundingBox = this.boundingBox;
    const instanceInfo = this._instanceInfo;
    boundingBox.makeEmpty();
    for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
      if (instanceInfo[i2].active === false) continue;
      const geometryId = instanceInfo[i2].geometryIndex;
      this.getMatrixAt(i2, _matrix$1);
      this.getBoundingBoxAt(geometryId, _box$1$1).applyMatrix4(_matrix$1);
      boundingBox.union(_box$1$1);
    }
  }
  computeBoundingSphere() {
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    const boundingSphere = this.boundingSphere;
    const instanceInfo = this._instanceInfo;
    boundingSphere.makeEmpty();
    for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
      if (instanceInfo[i2].active === false) continue;
      const geometryId = instanceInfo[i2].geometryIndex;
      this.getMatrixAt(i2, _matrix$1);
      this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1);
      boundingSphere.union(_sphere$2);
    }
  }
  addInstance(geometryId) {
    const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
    if (atCapacity && this._availableInstanceIds.length === 0) {
      throw new Error("THREE.BatchedMesh: Maximum item count reached.");
    }
    const instanceInfo = {
      visible: true,
      active: true,
      geometryIndex: geometryId
    };
    let drawId = null;
    if (this._availableInstanceIds.length > 0) {
      this._availableInstanceIds.sort(ascIdSort);
      drawId = this._availableInstanceIds.shift();
      this._instanceInfo[drawId] = instanceInfo;
    } else {
      drawId = this._instanceInfo.length;
      this._instanceInfo.push(instanceInfo);
    }
    const matricesTexture = this._matricesTexture;
    _matrix$1.identity().toArray(matricesTexture.image.data, drawId * 16);
    matricesTexture.needsUpdate = true;
    const colorsTexture = this._colorsTexture;
    if (colorsTexture) {
      _whiteColor.toArray(colorsTexture.image.data, drawId * 4);
      colorsTexture.needsUpdate = true;
    }
    this._visibilityChanged = true;
    return drawId;
  }
  addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) {
    this._initializeGeometry(geometry);
    this._validateGeometry(geometry);
    const geometryInfo = {
      // geometry information
      vertexStart: -1,
      vertexCount: -1,
      reservedVertexCount: -1,
      indexStart: -1,
      indexCount: -1,
      reservedIndexCount: -1,
      // draw range information
      start: -1,
      count: -1,
      // state
      boundingBox: null,
      boundingSphere: null,
      active: true
    };
    const geometryInfoList = this._geometryInfo;
    geometryInfo.vertexStart = this._nextVertexStart;
    geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount;
    const index = geometry.getIndex();
    const hasIndex = index !== null;
    if (hasIndex) {
      geometryInfo.indexStart = this._nextIndexStart;
      geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
    }
    if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) {
      throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");
    }
    let geometryId;
    if (this._availableGeometryIds.length > 0) {
      this._availableGeometryIds.sort(ascIdSort);
      geometryId = this._availableGeometryIds.shift();
      geometryInfoList[geometryId] = geometryInfo;
    } else {
      geometryId = this._geometryCount;
      this._geometryCount++;
      geometryInfoList.push(geometryInfo);
    }
    this.setGeometryAt(geometryId, geometry);
    this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
    this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
    return geometryId;
  }
  setGeometryAt(geometryId, geometry) {
    if (geometryId >= this._geometryCount) {
      throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");
    }
    this._validateGeometry(geometry);
    const batchGeometry = this.geometry;
    const hasIndex = batchGeometry.getIndex() !== null;
    const dstIndex = batchGeometry.getIndex();
    const srcIndex = geometry.getIndex();
    const geometryInfo = this._geometryInfo[geometryId];
    if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) {
      throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");
    }
    const vertexStart = geometryInfo.vertexStart;
    const reservedVertexCount = geometryInfo.reservedVertexCount;
    geometryInfo.vertexCount = geometry.getAttribute("position").count;
    for (const attributeName in batchGeometry.attributes) {
      const srcAttribute = geometry.getAttribute(attributeName);
      const dstAttribute = batchGeometry.getAttribute(attributeName);
      copyAttributeData(srcAttribute, dstAttribute, vertexStart);
      const itemSize = srcAttribute.itemSize;
      for (let i2 = srcAttribute.count, l2 = reservedVertexCount; i2 < l2; i2++) {
        const index = vertexStart + i2;
        for (let c2 = 0; c2 < itemSize; c2++) {
          dstAttribute.setComponent(index, c2, 0);
        }
      }
      dstAttribute.needsUpdate = true;
      dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize);
    }
    if (hasIndex) {
      const indexStart = geometryInfo.indexStart;
      const reservedIndexCount = geometryInfo.reservedIndexCount;
      geometryInfo.indexCount = geometry.getIndex().count;
      for (let i2 = 0; i2 < srcIndex.count; i2++) {
        dstIndex.setX(indexStart + i2, vertexStart + srcIndex.getX(i2));
      }
      for (let i2 = srcIndex.count, l2 = reservedIndexCount; i2 < l2; i2++) {
        dstIndex.setX(indexStart + i2, vertexStart);
      }
      dstIndex.needsUpdate = true;
      dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount);
    }
    geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
    geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
    geometryInfo.boundingBox = null;
    if (geometry.boundingBox !== null) {
      geometryInfo.boundingBox = geometry.boundingBox.clone();
    }
    geometryInfo.boundingSphere = null;
    if (geometry.boundingSphere !== null) {
      geometryInfo.boundingSphere = geometry.boundingSphere.clone();
    }
    this._visibilityChanged = true;
    return geometryId;
  }
  deleteGeometry(geometryId) {
    const geometryInfoList = this._geometryInfo;
    if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) {
      return this;
    }
    const instanceInfo = this._instanceInfo;
    for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
      if (instanceInfo[i2].geometryIndex === geometryId) {
        this.deleteInstance(i2);
      }
    }
    geometryInfoList[geometryId].active = false;
    this._availableGeometryIds.push(geometryId);
    this._visibilityChanged = true;
    return this;
  }
  deleteInstance(instanceId) {
    this.validateInstanceId(instanceId);
    this._instanceInfo[instanceId].active = false;
    this._availableInstanceIds.push(instanceId);
    this._visibilityChanged = true;
    return this;
  }
  optimize() {
    let nextVertexStart = 0;
    let nextIndexStart = 0;
    const geometryInfoList = this._geometryInfo;
    const indices = geometryInfoList.map((e2, i2) => i2).sort((a3, b2) => {
      return geometryInfoList[a3].vertexStart - geometryInfoList[b2].vertexStart;
    });
    const geometry = this.geometry;
    for (let i2 = 0, l2 = geometryInfoList.length; i2 < l2; i2++) {
      const index = indices[i2];
      const geometryInfo = geometryInfoList[index];
      if (geometryInfo.active === false) {
        continue;
      }
      if (geometry.index !== null) {
        if (geometryInfo.indexStart !== nextIndexStart) {
          const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
          const index2 = geometry.index;
          const array = index2.array;
          const elementDelta = nextVertexStart - vertexStart;
          for (let j2 = indexStart; j2 < indexStart + reservedIndexCount; j2++) {
            array[j2] = array[j2] + elementDelta;
          }
          index2.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount);
          index2.addUpdateRange(nextIndexStart, reservedIndexCount);
          geometryInfo.indexStart = nextIndexStart;
        }
        nextIndexStart += geometryInfo.reservedIndexCount;
      }
      if (geometryInfo.vertexStart !== nextVertexStart) {
        const { vertexStart, reservedVertexCount } = geometryInfo;
        const attributes = geometry.attributes;
        for (const key in attributes) {
          const attribute = attributes[key];
          const { array, itemSize } = attribute;
          array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize);
          attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize);
        }
        geometryInfo.vertexStart = nextVertexStart;
      }
      nextVertexStart += geometryInfo.reservedVertexCount;
      geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
      this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
      this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
    }
    return this;
  }
  // get bounding box and compute it if it doesn't exist
  getBoundingBoxAt(geometryId, target) {
    if (geometryId >= this._geometryCount) {
      return null;
    }
    const geometry = this.geometry;
    const geometryInfo = this._geometryInfo[geometryId];
    if (geometryInfo.boundingBox === null) {
      const box = new Box3();
      const index = geometry.index;
      const position = geometry.attributes.position;
      for (let i2 = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count; i2 < l2; i2++) {
        let iv = i2;
        if (index) {
          iv = index.getX(iv);
        }
        box.expandByPoint(_vector$5.fromBufferAttribute(position, iv));
      }
      geometryInfo.boundingBox = box;
    }
    target.copy(geometryInfo.boundingBox);
    return target;
  }
  // get bounding sphere and compute it if it doesn't exist
  getBoundingSphereAt(geometryId, target) {
    if (geometryId >= this._geometryCount) {
      return null;
    }
    const geometry = this.geometry;
    const geometryInfo = this._geometryInfo[geometryId];
    if (geometryInfo.boundingSphere === null) {
      const sphere = new Sphere();
      this.getBoundingBoxAt(geometryId, _box$1$1);
      _box$1$1.getCenter(sphere.center);
      const index = geometry.index;
      const position = geometry.attributes.position;
      let maxRadiusSq = 0;
      for (let i2 = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count; i2 < l2; i2++) {
        let iv = i2;
        if (index) {
          iv = index.getX(iv);
        }
        _vector$5.fromBufferAttribute(position, iv);
        maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5));
      }
      sphere.radius = Math.sqrt(maxRadiusSq);
      geometryInfo.boundingSphere = sphere;
    }
    target.copy(geometryInfo.boundingSphere);
    return target;
  }
  setMatrixAt(instanceId, matrix) {
    this.validateInstanceId(instanceId);
    const matricesTexture = this._matricesTexture;
    const matricesArray = this._matricesTexture.image.data;
    matrix.toArray(matricesArray, instanceId * 16);
    matricesTexture.needsUpdate = true;
    return this;
  }
  getMatrixAt(instanceId, matrix) {
    this.validateInstanceId(instanceId);
    return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16);
  }
  setColorAt(instanceId, color) {
    this.validateInstanceId(instanceId);
    if (this._colorsTexture === null) {
      this._initColorsTexture();
    }
    color.toArray(this._colorsTexture.image.data, instanceId * 4);
    this._colorsTexture.needsUpdate = true;
    return this;
  }
  getColorAt(instanceId, color) {
    this.validateInstanceId(instanceId);
    return color.fromArray(this._colorsTexture.image.data, instanceId * 4);
  }
  setVisibleAt(instanceId, value) {
    this.validateInstanceId(instanceId);
    if (this._instanceInfo[instanceId].visible === value) {
      return this;
    }
    this._instanceInfo[instanceId].visible = value;
    this._visibilityChanged = true;
    return this;
  }
  getVisibleAt(instanceId) {
    this.validateInstanceId(instanceId);
    return this._instanceInfo[instanceId].visible;
  }
  setGeometryIdAt(instanceId, geometryId) {
    this.validateInstanceId(instanceId);
    this.validateGeometryId(geometryId);
    this._instanceInfo[instanceId].geometryIndex = geometryId;
    return this;
  }
  getGeometryIdAt(instanceId) {
    this.validateInstanceId(instanceId);
    return this._instanceInfo[instanceId].geometryIndex;
  }
  getGeometryRangeAt(geometryId, target = {}) {
    this.validateGeometryId(geometryId);
    const geometryInfo = this._geometryInfo[geometryId];
    target.vertexStart = geometryInfo.vertexStart;
    target.vertexCount = geometryInfo.vertexCount;
    target.reservedVertexCount = geometryInfo.reservedVertexCount;
    target.indexStart = geometryInfo.indexStart;
    target.indexCount = geometryInfo.indexCount;
    target.reservedIndexCount = geometryInfo.reservedIndexCount;
    target.start = geometryInfo.start;
    target.count = geometryInfo.count;
    return target;
  }
  setInstanceCount(maxInstanceCount) {
    const availableInstanceIds = this._availableInstanceIds;
    const instanceInfo = this._instanceInfo;
    availableInstanceIds.sort(ascIdSort);
    while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) {
      instanceInfo.pop();
      availableInstanceIds.pop();
    }
    if (maxInstanceCount < instanceInfo.length) {
      throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`);
    }
    const multiDrawCounts = new Int32Array(maxInstanceCount);
    const multiDrawStarts = new Int32Array(maxInstanceCount);
    copyArrayContents(this._multiDrawCounts, multiDrawCounts);
    copyArrayContents(this._multiDrawStarts, multiDrawStarts);
    this._multiDrawCounts = multiDrawCounts;
    this._multiDrawStarts = multiDrawStarts;
    this._maxInstanceCount = maxInstanceCount;
    const indirectTexture = this._indirectTexture;
    const matricesTexture = this._matricesTexture;
    const colorsTexture = this._colorsTexture;
    indirectTexture.dispose();
    this._initIndirectTexture();
    copyArrayContents(indirectTexture.image.data, this._indirectTexture.image.data);
    matricesTexture.dispose();
    this._initMatricesTexture();
    copyArrayContents(matricesTexture.image.data, this._matricesTexture.image.data);
    if (colorsTexture) {
      colorsTexture.dispose();
      this._initColorsTexture();
      copyArrayContents(colorsTexture.image.data, this._colorsTexture.image.data);
    }
  }
  setGeometrySize(maxVertexCount, maxIndexCount) {
    const validRanges = [...this._geometryInfo].filter((info) => info.active);
    const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount));
    if (requiredVertexLength > maxVertexCount) {
      throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`);
    }
    if (this.geometry.index) {
      const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount));
      if (requiredIndexLength > maxIndexCount) {
        throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`);
      }
    }
    const oldGeometry = this.geometry;
    oldGeometry.dispose();
    this._maxVertexCount = maxVertexCount;
    this._maxIndexCount = maxIndexCount;
    if (this._geometryInitialized) {
      this._geometryInitialized = false;
      this.geometry = new BufferGeometry();
      this._initializeGeometry(oldGeometry);
    }
    const geometry = this.geometry;
    if (oldGeometry.index) {
      copyArrayContents(oldGeometry.index.array, geometry.index.array);
    }
    for (const key in oldGeometry.attributes) {
      copyArrayContents(oldGeometry.attributes[key].array, geometry.attributes[key].array);
    }
  }
  raycast(raycaster, intersects2) {
    const instanceInfo = this._instanceInfo;
    const geometryInfoList = this._geometryInfo;
    const matrixWorld = this.matrixWorld;
    const batchGeometry = this.geometry;
    _mesh.material = this.material;
    _mesh.geometry.index = batchGeometry.index;
    _mesh.geometry.attributes = batchGeometry.attributes;
    if (_mesh.geometry.boundingBox === null) {
      _mesh.geometry.boundingBox = new Box3();
    }
    if (_mesh.geometry.boundingSphere === null) {
      _mesh.geometry.boundingSphere = new Sphere();
    }
    for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
      if (!instanceInfo[i2].visible || !instanceInfo[i2].active) {
        continue;
      }
      const geometryId = instanceInfo[i2].geometryIndex;
      const geometryInfo = geometryInfoList[geometryId];
      _mesh.geometry.setDrawRange(geometryInfo.start, geometryInfo.count);
      this.getMatrixAt(i2, _mesh.matrixWorld).premultiply(matrixWorld);
      this.getBoundingBoxAt(geometryId, _mesh.geometry.boundingBox);
      this.getBoundingSphereAt(geometryId, _mesh.geometry.boundingSphere);
      _mesh.raycast(raycaster, _batchIntersects);
      for (let j2 = 0, l3 = _batchIntersects.length; j2 < l3; j2++) {
        const intersect2 = _batchIntersects[j2];
        intersect2.object = this;
        intersect2.batchId = i2;
        intersects2.push(intersect2);
      }
      _batchIntersects.length = 0;
    }
    _mesh.material = null;
    _mesh.geometry.index = null;
    _mesh.geometry.attributes = {};
    _mesh.geometry.setDrawRange(0, Infinity);
  }
  copy(source) {
    super.copy(source);
    this.geometry = source.geometry.clone();
    this.perObjectFrustumCulled = source.perObjectFrustumCulled;
    this.sortObjects = source.sortObjects;
    this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
    this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
    this._geometryInfo = source._geometryInfo.map((info) => ({
      ...info,
      boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
      boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null
    }));
    this._instanceInfo = source._instanceInfo.map((info) => ({ ...info }));
    this._maxInstanceCount = source._maxInstanceCount;
    this._maxVertexCount = source._maxVertexCount;
    this._maxIndexCount = source._maxIndexCount;
    this._geometryInitialized = source._geometryInitialized;
    this._geometryCount = source._geometryCount;
    this._multiDrawCounts = source._multiDrawCounts.slice();
    this._multiDrawStarts = source._multiDrawStarts.slice();
    this._matricesTexture = source._matricesTexture.clone();
    this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
    if (this._colorsTexture !== null) {
      this._colorsTexture = source._colorsTexture.clone();
      this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
    }
    return this;
  }
  dispose() {
    this.geometry.dispose();
    this._matricesTexture.dispose();
    this._matricesTexture = null;
    this._indirectTexture.dispose();
    this._indirectTexture = null;
    if (this._colorsTexture !== null) {
      this._colorsTexture.dispose();
      this._colorsTexture = null;
    }
    return this;
  }
  onBeforeRender(renderer, scene, camera, geometry, material) {
    if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) {
      return;
    }
    const index = geometry.getIndex();
    const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
    const instanceInfo = this._instanceInfo;
    const multiDrawStarts = this._multiDrawStarts;
    const multiDrawCounts = this._multiDrawCounts;
    const geometryInfoList = this._geometryInfo;
    const perObjectFrustumCulled = this.perObjectFrustumCulled;
    const indirectTexture = this._indirectTexture;
    const indirectArray = indirectTexture.image.data;
    if (perObjectFrustumCulled) {
      _matrix$1.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld);
      _frustum.setFromProjectionMatrix(
        _matrix$1,
        renderer.coordinateSystem
      );
    }
    let multiDrawCount = 0;
    if (this.sortObjects) {
      _matrix$1.copy(this.matrixWorld).invert();
      _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$1);
      _forward.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$1);
      for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
        if (instanceInfo[i2].visible && instanceInfo[i2].active) {
          const geometryId = instanceInfo[i2].geometryIndex;
          this.getMatrixAt(i2, _matrix$1);
          this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1);
          let culled = false;
          if (perObjectFrustumCulled) {
            culled = !_frustum.intersectsSphere(_sphere$2);
          }
          if (!culled) {
            const geometryInfo = geometryInfoList[geometryId];
            const z2 = _temp.subVectors(_sphere$2.center, _vector$5).dot(_forward);
            _renderList.push(geometryInfo.start, geometryInfo.count, z2, i2);
          }
        }
      }
      const list = _renderList.list;
      const customSort = this.customSort;
      if (customSort === null) {
        list.sort(material.transparent ? sortTransparent : sortOpaque);
      } else {
        customSort.call(this, list, camera);
      }
      for (let i2 = 0, l2 = list.length; i2 < l2; i2++) {
        const item = list[i2];
        multiDrawStarts[multiDrawCount] = item.start * bytesPerElement;
        multiDrawCounts[multiDrawCount] = item.count;
        indirectArray[multiDrawCount] = item.index;
        multiDrawCount++;
      }
      _renderList.reset();
    } else {
      for (let i2 = 0, l2 = instanceInfo.length; i2 < l2; i2++) {
        if (instanceInfo[i2].visible && instanceInfo[i2].active) {
          const geometryId = instanceInfo[i2].geometryIndex;
          let culled = false;
          if (perObjectFrustumCulled) {
            this.getMatrixAt(i2, _matrix$1);
            this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1);
            culled = !_frustum.intersectsSphere(_sphere$2);
          }
          if (!culled) {
            const geometryInfo = geometryInfoList[geometryId];
            multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement;
            multiDrawCounts[multiDrawCount] = geometryInfo.count;
            indirectArray[multiDrawCount] = i2;
            multiDrawCount++;
          }
        }
      }
    }
    indirectTexture.needsUpdate = true;
    this._multiDrawCount = multiDrawCount;
    this._visibilityChanged = false;
  }
  onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial) {
    this.onBeforeRender(renderer, null, shadowCamera, geometry, depthMaterial);
  }
}
class LineBasicMaterial extends Material {
  constructor(parameters) {
    super();
    this.isLineBasicMaterial = true;
    this.type = "LineBasicMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.linewidth = 1;
    this.linecap = "round";
    this.linejoin = "round";
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.linewidth = source.linewidth;
    this.linecap = source.linecap;
    this.linejoin = source.linejoin;
    this.fog = source.fog;
    return this;
  }
}
const _vStart = /* @__PURE__ */ new Vector3();
const _vEnd = /* @__PURE__ */ new Vector3();
const _inverseMatrix$1 = /* @__PURE__ */ new Matrix4();
const _ray$1$1 = /* @__PURE__ */ new Ray();
const _sphere$1 = /* @__PURE__ */ new Sphere();
const _intersectPointOnRay = /* @__PURE__ */ new Vector3();
const _intersectPointOnSegment = /* @__PURE__ */ new Vector3();
let Line$1 = class Line extends Object3D {
  constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
    super();
    this.isLine = true;
    this.type = "Line";
    this.geometry = geometry;
    this.material = material;
    this.updateMorphTargets();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.material = Array.isArray(source.material) ? source.material.slice() : source.material;
    this.geometry = source.geometry;
    return this;
  }
  computeLineDistances() {
    const geometry = this.geometry;
    if (geometry.index === null) {
      const positionAttribute = geometry.attributes.position;
      const lineDistances = [0];
      for (let i2 = 1, l2 = positionAttribute.count; i2 < l2; i2++) {
        _vStart.fromBufferAttribute(positionAttribute, i2 - 1);
        _vEnd.fromBufferAttribute(positionAttribute, i2);
        lineDistances[i2] = lineDistances[i2 - 1];
        lineDistances[i2] += _vStart.distanceTo(_vEnd);
      }
      geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1));
    } else {
      console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    }
    return this;
  }
  raycast(raycaster, intersects2) {
    const geometry = this.geometry;
    const matrixWorld = this.matrixWorld;
    const threshold = raycaster.params.Line.threshold;
    const drawRange = geometry.drawRange;
    if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
    _sphere$1.copy(geometry.boundingSphere);
    _sphere$1.applyMatrix4(matrixWorld);
    _sphere$1.radius += threshold;
    if (raycaster.ray.intersectsSphere(_sphere$1) === false) return;
    _inverseMatrix$1.copy(matrixWorld).invert();
    _ray$1$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
    const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
    const localThresholdSq = localThreshold * localThreshold;
    const step = this.isLineSegments ? 2 : 1;
    const index = geometry.index;
    const attributes = geometry.attributes;
    const positionAttribute = attributes.position;
    if (index !== null) {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(index.count, drawRange.start + drawRange.count);
      for (let i2 = start, l2 = end - 1; i2 < l2; i2 += step) {
        const a3 = index.getX(i2);
        const b2 = index.getX(i2 + 1);
        const intersect2 = checkIntersection(this, raycaster, _ray$1$1, localThresholdSq, a3, b2);
        if (intersect2) {
          intersects2.push(intersect2);
        }
      }
      if (this.isLineLoop) {
        const a3 = index.getX(end - 1);
        const b2 = index.getX(start);
        const intersect2 = checkIntersection(this, raycaster, _ray$1$1, localThresholdSq, a3, b2);
        if (intersect2) {
          intersects2.push(intersect2);
        }
      }
    } else {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
      for (let i2 = start, l2 = end - 1; i2 < l2; i2 += step) {
        const intersect2 = checkIntersection(this, raycaster, _ray$1$1, localThresholdSq, i2, i2 + 1);
        if (intersect2) {
          intersects2.push(intersect2);
        }
      }
      if (this.isLineLoop) {
        const intersect2 = checkIntersection(this, raycaster, _ray$1$1, localThresholdSq, end - 1, start);
        if (intersect2) {
          intersects2.push(intersect2);
        }
      }
    }
  }
  updateMorphTargets() {
    const geometry = this.geometry;
    const morphAttributes = geometry.morphAttributes;
    const keys = Object.keys(morphAttributes);
    if (keys.length > 0) {
      const morphAttribute = morphAttributes[keys[0]];
      if (morphAttribute !== void 0) {
        this.morphTargetInfluences = [];
        this.morphTargetDictionary = {};
        for (let m2 = 0, ml = morphAttribute.length; m2 < ml; m2++) {
          const name = morphAttribute[m2].name || String(m2);
          this.morphTargetInfluences.push(0);
          this.morphTargetDictionary[name] = m2;
        }
      }
    }
  }
};
function checkIntersection(object, raycaster, ray, thresholdSq, a3, b2) {
  const positionAttribute = object.geometry.attributes.position;
  _vStart.fromBufferAttribute(positionAttribute, a3);
  _vEnd.fromBufferAttribute(positionAttribute, b2);
  const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment);
  if (distSq > thresholdSq) return;
  _intersectPointOnRay.applyMatrix4(object.matrixWorld);
  const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay);
  if (distance < raycaster.near || distance > raycaster.far) return;
  return {
    distance,
    // What do we want? intersection point on the ray or on the segment??
    // point: raycaster.ray.at( distance ),
    point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld),
    index: a3,
    face: null,
    faceIndex: null,
    barycoord: null,
    object
  };
}
const _start$1 = /* @__PURE__ */ new Vector3();
const _end$1 = /* @__PURE__ */ new Vector3();
class LineSegments extends Line$1 {
  constructor(geometry, material) {
    super(geometry, material);
    this.isLineSegments = true;
    this.type = "LineSegments";
  }
  computeLineDistances() {
    const geometry = this.geometry;
    if (geometry.index === null) {
      const positionAttribute = geometry.attributes.position;
      const lineDistances = [];
      for (let i2 = 0, l2 = positionAttribute.count; i2 < l2; i2 += 2) {
        _start$1.fromBufferAttribute(positionAttribute, i2);
        _end$1.fromBufferAttribute(positionAttribute, i2 + 1);
        lineDistances[i2] = i2 === 0 ? 0 : lineDistances[i2 - 1];
        lineDistances[i2 + 1] = lineDistances[i2] + _start$1.distanceTo(_end$1);
      }
      geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1));
    } else {
      console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    }
    return this;
  }
}
class LineLoop extends Line$1 {
  constructor(geometry, material) {
    super(geometry, material);
    this.isLineLoop = true;
    this.type = "LineLoop";
  }
}
class PointsMaterial extends Material {
  constructor(parameters) {
    super();
    this.isPointsMaterial = true;
    this.type = "PointsMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.alphaMap = null;
    this.size = 1;
    this.sizeAttenuation = true;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.alphaMap = source.alphaMap;
    this.size = source.size;
    this.sizeAttenuation = source.sizeAttenuation;
    this.fog = source.fog;
    return this;
  }
}
const _inverseMatrix = /* @__PURE__ */ new Matrix4();
const _ray$4 = /* @__PURE__ */ new Ray();
const _sphere$7 = /* @__PURE__ */ new Sphere();
const _position$2 = /* @__PURE__ */ new Vector3();
class Points extends Object3D {
  constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
    super();
    this.isPoints = true;
    this.type = "Points";
    this.geometry = geometry;
    this.material = material;
    this.updateMorphTargets();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.material = Array.isArray(source.material) ? source.material.slice() : source.material;
    this.geometry = source.geometry;
    return this;
  }
  raycast(raycaster, intersects2) {
    const geometry = this.geometry;
    const matrixWorld = this.matrixWorld;
    const threshold = raycaster.params.Points.threshold;
    const drawRange = geometry.drawRange;
    if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
    _sphere$7.copy(geometry.boundingSphere);
    _sphere$7.applyMatrix4(matrixWorld);
    _sphere$7.radius += threshold;
    if (raycaster.ray.intersectsSphere(_sphere$7) === false) return;
    _inverseMatrix.copy(matrixWorld).invert();
    _ray$4.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
    const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
    const localThresholdSq = localThreshold * localThreshold;
    const index = geometry.index;
    const attributes = geometry.attributes;
    const positionAttribute = attributes.position;
    if (index !== null) {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(index.count, drawRange.start + drawRange.count);
      for (let i2 = start, il = end; i2 < il; i2++) {
        const a3 = index.getX(i2);
        _position$2.fromBufferAttribute(positionAttribute, a3);
        testPoint(_position$2, a3, localThresholdSq, matrixWorld, raycaster, intersects2, this);
      }
    } else {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
      for (let i2 = start, l2 = end; i2 < l2; i2++) {
        _position$2.fromBufferAttribute(positionAttribute, i2);
        testPoint(_position$2, i2, localThresholdSq, matrixWorld, raycaster, intersects2, this);
      }
    }
  }
  updateMorphTargets() {
    const geometry = this.geometry;
    const morphAttributes = geometry.morphAttributes;
    const keys = Object.keys(morphAttributes);
    if (keys.length > 0) {
      const morphAttribute = morphAttributes[keys[0]];
      if (morphAttribute !== void 0) {
        this.morphTargetInfluences = [];
        this.morphTargetDictionary = {};
        for (let m2 = 0, ml = morphAttribute.length; m2 < ml; m2++) {
          const name = morphAttribute[m2].name || String(m2);
          this.morphTargetInfluences.push(0);
          this.morphTargetDictionary[name] = m2;
        }
      }
    }
  }
}
function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects2, object) {
  const rayPointDistanceSq = _ray$4.distanceSqToPoint(point);
  if (rayPointDistanceSq < localThresholdSq) {
    const intersectPoint = new Vector3();
    _ray$4.closestPointToPoint(point, intersectPoint);
    intersectPoint.applyMatrix4(matrixWorld);
    const distance = raycaster.ray.origin.distanceTo(intersectPoint);
    if (distance < raycaster.near || distance > raycaster.far) return;
    intersects2.push({
      distance,
      distanceToRay: Math.sqrt(rayPointDistanceSq),
      point: intersectPoint,
      index,
      face: null,
      faceIndex: null,
      barycoord: null,
      object
    });
  }
}
class Group extends Object3D {
  constructor() {
    super();
    this.isGroup = true;
    this.type = "Group";
  }
}
class VideoTexture extends Texture {
  constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
    super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
    this.isVideoTexture = true;
    this.minFilter = minFilter !== void 0 ? minFilter : LinearFilter;
    this.magFilter = magFilter !== void 0 ? magFilter : LinearFilter;
    this.generateMipmaps = false;
    const scope = this;
    function updateVideo() {
      scope.needsUpdate = true;
      video.requestVideoFrameCallback(updateVideo);
    }
    if ("requestVideoFrameCallback" in video) {
      video.requestVideoFrameCallback(updateVideo);
    }
  }
  clone() {
    return new this.constructor(this.image).copy(this);
  }
  update() {
    const video = this.image;
    const hasVideoFrameCallback = "requestVideoFrameCallback" in video;
    if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
      this.needsUpdate = true;
    }
  }
}
class FramebufferTexture extends Texture {
  constructor(width, height) {
    super({ width, height });
    this.isFramebufferTexture = true;
    this.magFilter = NearestFilter;
    this.minFilter = NearestFilter;
    this.generateMipmaps = false;
    this.needsUpdate = true;
  }
}
class CompressedTexture extends Texture {
  constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) {
    super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace);
    this.isCompressedTexture = true;
    this.image = { width, height };
    this.mipmaps = mipmaps;
    this.flipY = false;
    this.generateMipmaps = false;
  }
}
class CompressedArrayTexture extends CompressedTexture {
  constructor(mipmaps, width, height, depth, format, type) {
    super(mipmaps, width, height, format, type);
    this.isCompressedArrayTexture = true;
    this.image.depth = depth;
    this.wrapR = ClampToEdgeWrapping;
    this.layerUpdates = /* @__PURE__ */ new Set();
  }
  addLayerUpdate(layerIndex) {
    this.layerUpdates.add(layerIndex);
  }
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class CompressedCubeTexture extends CompressedTexture {
  constructor(images, format, type) {
    super(void 0, images[0].width, images[0].height, format, type, CubeReflectionMapping);
    this.isCompressedCubeTexture = true;
    this.isCubeTexture = true;
    this.image = images;
  }
}
class CanvasTexture extends Texture {
  constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
    super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
    this.isCanvasTexture = true;
    this.needsUpdate = true;
  }
}
class DepthTexture extends Texture {
  constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat) {
    if (format !== DepthFormat && format !== DepthStencilFormat) {
      throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");
    }
    if (type === void 0 && format === DepthFormat) type = UnsignedIntType;
    if (type === void 0 && format === DepthStencilFormat) type = UnsignedInt248Type;
    super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
    this.isDepthTexture = true;
    this.image = { width, height };
    this.magFilter = magFilter !== void 0 ? magFilter : NearestFilter;
    this.minFilter = minFilter !== void 0 ? minFilter : NearestFilter;
    this.flipY = false;
    this.generateMipmaps = false;
    this.compareFunction = null;
  }
  copy(source) {
    super.copy(source);
    this.compareFunction = source.compareFunction;
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    if (this.compareFunction !== null) data.compareFunction = this.compareFunction;
    return data;
  }
}
class Curve {
  constructor() {
    this.type = "Curve";
    this.arcLengthDivisions = 200;
  }
  // Virtual base class method to overwrite and implement in subclasses
  //	- t [0 .. 1]
  getPoint() {
    console.warn("THREE.Curve: .getPoint() not implemented.");
    return null;
  }
  // Get point at relative position in curve according to arc length
  // - u [0 .. 1]
  getPointAt(u2, optionalTarget) {
    const t2 = this.getUtoTmapping(u2);
    return this.getPoint(t2, optionalTarget);
  }
  // Get sequence of points using getPoint( t )
  getPoints(divisions = 5) {
    const points = [];
    for (let d2 = 0; d2 <= divisions; d2++) {
      points.push(this.getPoint(d2 / divisions));
    }
    return points;
  }
  // Get sequence of points using getPointAt( u )
  getSpacedPoints(divisions = 5) {
    const points = [];
    for (let d2 = 0; d2 <= divisions; d2++) {
      points.push(this.getPointAt(d2 / divisions));
    }
    return points;
  }
  // Get total curve arc length
  getLength() {
    const lengths = this.getLengths();
    return lengths[lengths.length - 1];
  }
  // Get list of cumulative segment lengths
  getLengths(divisions = this.arcLengthDivisions) {
    if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
      return this.cacheArcLengths;
    }
    this.needsUpdate = false;
    const cache = [];
    let current, last = this.getPoint(0);
    let sum = 0;
    cache.push(0);
    for (let p2 = 1; p2 <= divisions; p2++) {
      current = this.getPoint(p2 / divisions);
      sum += current.distanceTo(last);
      cache.push(sum);
      last = current;
    }
    this.cacheArcLengths = cache;
    return cache;
  }
  updateArcLengths() {
    this.needsUpdate = true;
    this.getLengths();
  }
  // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  getUtoTmapping(u2, distance) {
    const arcLengths = this.getLengths();
    let i2 = 0;
    const il = arcLengths.length;
    let targetArcLength;
    if (distance) {
      targetArcLength = distance;
    } else {
      targetArcLength = u2 * arcLengths[il - 1];
    }
    let low = 0, high = il - 1, comparison;
    while (low <= high) {
      i2 = Math.floor(low + (high - low) / 2);
      comparison = arcLengths[i2] - targetArcLength;
      if (comparison < 0) {
        low = i2 + 1;
      } else if (comparison > 0) {
        high = i2 - 1;
      } else {
        high = i2;
        break;
      }
    }
    i2 = high;
    if (arcLengths[i2] === targetArcLength) {
      return i2 / (il - 1);
    }
    const lengthBefore = arcLengths[i2];
    const lengthAfter = arcLengths[i2 + 1];
    const segmentLength = lengthAfter - lengthBefore;
    const segmentFraction = (targetArcLength - lengthBefore) / segmentLength;
    const t2 = (i2 + segmentFraction) / (il - 1);
    return t2;
  }
  // Returns a unit vector tangent at t
  // In case any sub curve does not implement its tangent derivation,
  // 2 points a small delta apart will be used to find its gradient
  // which seems to give a reasonable approximation
  getTangent(t2, optionalTarget) {
    const delta = 1e-4;
    let t1 = t2 - delta;
    let t22 = t2 + delta;
    if (t1 < 0) t1 = 0;
    if (t22 > 1) t22 = 1;
    const pt1 = this.getPoint(t1);
    const pt2 = this.getPoint(t22);
    const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
    tangent.copy(pt2).sub(pt1).normalize();
    return tangent;
  }
  getTangentAt(u2, optionalTarget) {
    const t2 = this.getUtoTmapping(u2);
    return this.getTangent(t2, optionalTarget);
  }
  computeFrenetFrames(segments, closed) {
    const normal = new Vector3();
    const tangents = [];
    const normals = [];
    const binormals = [];
    const vec = new Vector3();
    const mat = new Matrix4();
    for (let i2 = 0; i2 <= segments; i2++) {
      const u2 = i2 / segments;
      tangents[i2] = this.getTangentAt(u2, new Vector3());
    }
    normals[0] = new Vector3();
    binormals[0] = new Vector3();
    let min = Number.MAX_VALUE;
    const tx = Math.abs(tangents[0].x);
    const ty = Math.abs(tangents[0].y);
    const tz = Math.abs(tangents[0].z);
    if (tx <= min) {
      min = tx;
      normal.set(1, 0, 0);
    }
    if (ty <= min) {
      min = ty;
      normal.set(0, 1, 0);
    }
    if (tz <= min) {
      normal.set(0, 0, 1);
    }
    vec.crossVectors(tangents[0], normal).normalize();
    normals[0].crossVectors(tangents[0], vec);
    binormals[0].crossVectors(tangents[0], normals[0]);
    for (let i2 = 1; i2 <= segments; i2++) {
      normals[i2] = normals[i2 - 1].clone();
      binormals[i2] = binormals[i2 - 1].clone();
      vec.crossVectors(tangents[i2 - 1], tangents[i2]);
      if (vec.length() > Number.EPSILON) {
        vec.normalize();
        const theta = Math.acos(clamp(tangents[i2 - 1].dot(tangents[i2]), -1, 1));
        normals[i2].applyMatrix4(mat.makeRotationAxis(vec, theta));
      }
      binormals[i2].crossVectors(tangents[i2], normals[i2]);
    }
    if (closed === true) {
      let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
      theta /= segments;
      if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
        theta = -theta;
      }
      for (let i2 = 1; i2 <= segments; i2++) {
        normals[i2].applyMatrix4(mat.makeRotationAxis(tangents[i2], theta * i2));
        binormals[i2].crossVectors(tangents[i2], normals[i2]);
      }
    }
    return {
      tangents,
      normals,
      binormals
    };
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.arcLengthDivisions = source.arcLengthDivisions;
    return this;
  }
  toJSON() {
    const data = {
      metadata: {
        version: 4.6,
        type: "Curve",
        generator: "Curve.toJSON"
      }
    };
    data.arcLengthDivisions = this.arcLengthDivisions;
    data.type = this.type;
    return data;
  }
  fromJSON(json3) {
    this.arcLengthDivisions = json3.arcLengthDivisions;
    return this;
  }
}
class EllipseCurve extends Curve {
  constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
    super();
    this.isEllipseCurve = true;
    this.type = "EllipseCurve";
    this.aX = aX;
    this.aY = aY;
    this.xRadius = xRadius;
    this.yRadius = yRadius;
    this.aStartAngle = aStartAngle;
    this.aEndAngle = aEndAngle;
    this.aClockwise = aClockwise;
    this.aRotation = aRotation;
  }
  getPoint(t2, optionalTarget = new Vector2()) {
    const point = optionalTarget;
    const twoPi = Math.PI * 2;
    let deltaAngle = this.aEndAngle - this.aStartAngle;
    const samePoints = Math.abs(deltaAngle) < Number.EPSILON;
    while (deltaAngle < 0) deltaAngle += twoPi;
    while (deltaAngle > twoPi) deltaAngle -= twoPi;
    if (deltaAngle < Number.EPSILON) {
      if (samePoints) {
        deltaAngle = 0;
      } else {
        deltaAngle = twoPi;
      }
    }
    if (this.aClockwise === true && !samePoints) {
      if (deltaAngle === twoPi) {
        deltaAngle = -twoPi;
      } else {
        deltaAngle = deltaAngle - twoPi;
      }
    }
    const angle = this.aStartAngle + t2 * deltaAngle;
    let x = this.aX + this.xRadius * Math.cos(angle);
    let y2 = this.aY + this.yRadius * Math.sin(angle);
    if (this.aRotation !== 0) {
      const cos = Math.cos(this.aRotation);
      const sin = Math.sin(this.aRotation);
      const tx = x - this.aX;
      const ty = y2 - this.aY;
      x = tx * cos - ty * sin + this.aX;
      y2 = tx * sin + ty * cos + this.aY;
    }
    return point.set(x, y2);
  }
  copy(source) {
    super.copy(source);
    this.aX = source.aX;
    this.aY = source.aY;
    this.xRadius = source.xRadius;
    this.yRadius = source.yRadius;
    this.aStartAngle = source.aStartAngle;
    this.aEndAngle = source.aEndAngle;
    this.aClockwise = source.aClockwise;
    this.aRotation = source.aRotation;
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.aX = this.aX;
    data.aY = this.aY;
    data.xRadius = this.xRadius;
    data.yRadius = this.yRadius;
    data.aStartAngle = this.aStartAngle;
    data.aEndAngle = this.aEndAngle;
    data.aClockwise = this.aClockwise;
    data.aRotation = this.aRotation;
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.aX = json3.aX;
    this.aY = json3.aY;
    this.xRadius = json3.xRadius;
    this.yRadius = json3.yRadius;
    this.aStartAngle = json3.aStartAngle;
    this.aEndAngle = json3.aEndAngle;
    this.aClockwise = json3.aClockwise;
    this.aRotation = json3.aRotation;
    return this;
  }
}
class ArcCurve extends EllipseCurve {
  constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
    super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
    this.isArcCurve = true;
    this.type = "ArcCurve";
  }
}
function CubicPoly() {
  let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  function init(x0, x1, t0, t1) {
    c0 = x0;
    c1 = t0;
    c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
    c3 = 2 * x0 - 2 * x1 + t0 + t1;
  }
  return {
    initCatmullRom: function(x0, x1, x2, x3, tension) {
      init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
    },
    initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) {
      let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
      let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2;
      t1 *= dt1;
      t2 *= dt1;
      init(x1, x2, t1, t2);
    },
    calc: function(t2) {
      const t22 = t2 * t2;
      const t3 = t22 * t2;
      return c0 + c1 * t2 + c2 * t22 + c3 * t3;
    }
  };
}
const tmp = /* @__PURE__ */ new Vector3();
const px = /* @__PURE__ */ new CubicPoly();
const py = /* @__PURE__ */ new CubicPoly();
const pz = /* @__PURE__ */ new CubicPoly();
class CatmullRomCurve3 extends Curve {
  constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) {
    super();
    this.isCatmullRomCurve3 = true;
    this.type = "CatmullRomCurve3";
    this.points = points;
    this.closed = closed;
    this.curveType = curveType;
    this.tension = tension;
  }
  getPoint(t2, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const points = this.points;
    const l2 = points.length;
    const p2 = (l2 - (this.closed ? 0 : 1)) * t2;
    let intPoint = Math.floor(p2);
    let weight = p2 - intPoint;
    if (this.closed) {
      intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l2) + 1) * l2;
    } else if (weight === 0 && intPoint === l2 - 1) {
      intPoint = l2 - 2;
      weight = 1;
    }
    let p0, p3;
    if (this.closed || intPoint > 0) {
      p0 = points[(intPoint - 1) % l2];
    } else {
      tmp.subVectors(points[0], points[1]).add(points[0]);
      p0 = tmp;
    }
    const p1 = points[intPoint % l2];
    const p22 = points[(intPoint + 1) % l2];
    if (this.closed || intPoint + 2 < l2) {
      p3 = points[(intPoint + 2) % l2];
    } else {
      tmp.subVectors(points[l2 - 1], points[l2 - 2]).add(points[l2 - 1]);
      p3 = tmp;
    }
    if (this.curveType === "centripetal" || this.curveType === "chordal") {
      const pow = this.curveType === "chordal" ? 0.5 : 0.25;
      let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
      let dt1 = Math.pow(p1.distanceToSquared(p22), pow);
      let dt2 = Math.pow(p22.distanceToSquared(p3), pow);
      if (dt1 < 1e-4) dt1 = 1;
      if (dt0 < 1e-4) dt0 = dt1;
      if (dt2 < 1e-4) dt2 = dt1;
      px.initNonuniformCatmullRom(p0.x, p1.x, p22.x, p3.x, dt0, dt1, dt2);
      py.initNonuniformCatmullRom(p0.y, p1.y, p22.y, p3.y, dt0, dt1, dt2);
      pz.initNonuniformCatmullRom(p0.z, p1.z, p22.z, p3.z, dt0, dt1, dt2);
    } else if (this.curveType === "catmullrom") {
      px.initCatmullRom(p0.x, p1.x, p22.x, p3.x, this.tension);
      py.initCatmullRom(p0.y, p1.y, p22.y, p3.y, this.tension);
      pz.initCatmullRom(p0.z, p1.z, p22.z, p3.z, this.tension);
    }
    point.set(
      px.calc(weight),
      py.calc(weight),
      pz.calc(weight)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.points = [];
    for (let i2 = 0, l2 = source.points.length; i2 < l2; i2++) {
      const point = source.points[i2];
      this.points.push(point.clone());
    }
    this.closed = source.closed;
    this.curveType = source.curveType;
    this.tension = source.tension;
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.points = [];
    for (let i2 = 0, l2 = this.points.length; i2 < l2; i2++) {
      const point = this.points[i2];
      data.points.push(point.toArray());
    }
    data.closed = this.closed;
    data.curveType = this.curveType;
    data.tension = this.tension;
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.points = [];
    for (let i2 = 0, l2 = json3.points.length; i2 < l2; i2++) {
      const point = json3.points[i2];
      this.points.push(new Vector3().fromArray(point));
    }
    this.closed = json3.closed;
    this.curveType = json3.curveType;
    this.tension = json3.tension;
    return this;
  }
}
function CatmullRom(t2, p0, p1, p2, p3) {
  const v0 = (p2 - p0) * 0.5;
  const v12 = (p3 - p1) * 0.5;
  const t22 = t2 * t2;
  const t3 = t2 * t22;
  return (2 * p1 - 2 * p2 + v0 + v12) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v12) * t22 + v0 * t2 + p1;
}
function QuadraticBezierP0(t2, p2) {
  const k2 = 1 - t2;
  return k2 * k2 * p2;
}
function QuadraticBezierP1(t2, p2) {
  return 2 * (1 - t2) * t2 * p2;
}
function QuadraticBezierP2(t2, p2) {
  return t2 * t2 * p2;
}
function QuadraticBezier(t2, p0, p1, p2) {
  return QuadraticBezierP0(t2, p0) + QuadraticBezierP1(t2, p1) + QuadraticBezierP2(t2, p2);
}
function CubicBezierP0(t2, p2) {
  const k2 = 1 - t2;
  return k2 * k2 * k2 * p2;
}
function CubicBezierP1(t2, p2) {
  const k2 = 1 - t2;
  return 3 * k2 * k2 * t2 * p2;
}
function CubicBezierP2(t2, p2) {
  return 3 * (1 - t2) * t2 * t2 * p2;
}
function CubicBezierP3(t2, p2) {
  return t2 * t2 * t2 * p2;
}
function CubicBezier(t2, p0, p1, p2, p3) {
  return CubicBezierP0(t2, p0) + CubicBezierP1(t2, p1) + CubicBezierP2(t2, p2) + CubicBezierP3(t2, p3);
}
class CubicBezierCurve extends Curve {
  constructor(v0 = new Vector2(), v12 = new Vector2(), v22 = new Vector2(), v32 = new Vector2()) {
    super();
    this.isCubicBezierCurve = true;
    this.type = "CubicBezierCurve";
    this.v0 = v0;
    this.v1 = v12;
    this.v2 = v22;
    this.v3 = v32;
  }
  getPoint(t2, optionalTarget = new Vector2()) {
    const point = optionalTarget;
    const v0 = this.v0, v12 = this.v1, v22 = this.v2, v32 = this.v3;
    point.set(
      CubicBezier(t2, v0.x, v12.x, v22.x, v32.x),
      CubicBezier(t2, v0.y, v12.y, v22.y, v32.y)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.v0.copy(source.v0);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    this.v3.copy(source.v3);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v0 = this.v0.toArray();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    data.v3 = this.v3.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v0.fromArray(json3.v0);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    this.v3.fromArray(json3.v3);
    return this;
  }
}
class CubicBezierCurve3 extends Curve {
  constructor(v0 = new Vector3(), v12 = new Vector3(), v22 = new Vector3(), v32 = new Vector3()) {
    super();
    this.isCubicBezierCurve3 = true;
    this.type = "CubicBezierCurve3";
    this.v0 = v0;
    this.v1 = v12;
    this.v2 = v22;
    this.v3 = v32;
  }
  getPoint(t2, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const v0 = this.v0, v12 = this.v1, v22 = this.v2, v32 = this.v3;
    point.set(
      CubicBezier(t2, v0.x, v12.x, v22.x, v32.x),
      CubicBezier(t2, v0.y, v12.y, v22.y, v32.y),
      CubicBezier(t2, v0.z, v12.z, v22.z, v32.z)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.v0.copy(source.v0);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    this.v3.copy(source.v3);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v0 = this.v0.toArray();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    data.v3 = this.v3.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v0.fromArray(json3.v0);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    this.v3.fromArray(json3.v3);
    return this;
  }
}
class LineCurve extends Curve {
  constructor(v12 = new Vector2(), v22 = new Vector2()) {
    super();
    this.isLineCurve = true;
    this.type = "LineCurve";
    this.v1 = v12;
    this.v2 = v22;
  }
  getPoint(t2, optionalTarget = new Vector2()) {
    const point = optionalTarget;
    if (t2 === 1) {
      point.copy(this.v2);
    } else {
      point.copy(this.v2).sub(this.v1);
      point.multiplyScalar(t2).add(this.v1);
    }
    return point;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(u2, optionalTarget) {
    return this.getPoint(u2, optionalTarget);
  }
  getTangent(t2, optionalTarget = new Vector2()) {
    return optionalTarget.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(u2, optionalTarget) {
    return this.getTangent(u2, optionalTarget);
  }
  copy(source) {
    super.copy(source);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    return this;
  }
}
class LineCurve3 extends Curve {
  constructor(v12 = new Vector3(), v22 = new Vector3()) {
    super();
    this.isLineCurve3 = true;
    this.type = "LineCurve3";
    this.v1 = v12;
    this.v2 = v22;
  }
  getPoint(t2, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    if (t2 === 1) {
      point.copy(this.v2);
    } else {
      point.copy(this.v2).sub(this.v1);
      point.multiplyScalar(t2).add(this.v1);
    }
    return point;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(u2, optionalTarget) {
    return this.getPoint(u2, optionalTarget);
  }
  getTangent(t2, optionalTarget = new Vector3()) {
    return optionalTarget.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(u2, optionalTarget) {
    return this.getTangent(u2, optionalTarget);
  }
  copy(source) {
    super.copy(source);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    return this;
  }
}
class QuadraticBezierCurve extends Curve {
  constructor(v0 = new Vector2(), v12 = new Vector2(), v22 = new Vector2()) {
    super();
    this.isQuadraticBezierCurve = true;
    this.type = "QuadraticBezierCurve";
    this.v0 = v0;
    this.v1 = v12;
    this.v2 = v22;
  }
  getPoint(t2, optionalTarget = new Vector2()) {
    const point = optionalTarget;
    const v0 = this.v0, v12 = this.v1, v22 = this.v2;
    point.set(
      QuadraticBezier(t2, v0.x, v12.x, v22.x),
      QuadraticBezier(t2, v0.y, v12.y, v22.y)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.v0.copy(source.v0);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v0 = this.v0.toArray();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v0.fromArray(json3.v0);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    return this;
  }
}
class QuadraticBezierCurve3 extends Curve {
  constructor(v0 = new Vector3(), v12 = new Vector3(), v22 = new Vector3()) {
    super();
    this.isQuadraticBezierCurve3 = true;
    this.type = "QuadraticBezierCurve3";
    this.v0 = v0;
    this.v1 = v12;
    this.v2 = v22;
  }
  getPoint(t2, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const v0 = this.v0, v12 = this.v1, v22 = this.v2;
    point.set(
      QuadraticBezier(t2, v0.x, v12.x, v22.x),
      QuadraticBezier(t2, v0.y, v12.y, v22.y),
      QuadraticBezier(t2, v0.z, v12.z, v22.z)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.v0.copy(source.v0);
    this.v1.copy(source.v1);
    this.v2.copy(source.v2);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.v0 = this.v0.toArray();
    data.v1 = this.v1.toArray();
    data.v2 = this.v2.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.v0.fromArray(json3.v0);
    this.v1.fromArray(json3.v1);
    this.v2.fromArray(json3.v2);
    return this;
  }
}
class SplineCurve extends Curve {
  constructor(points = []) {
    super();
    this.isSplineCurve = true;
    this.type = "SplineCurve";
    this.points = points;
  }
  getPoint(t2, optionalTarget = new Vector2()) {
    const point = optionalTarget;
    const points = this.points;
    const p2 = (points.length - 1) * t2;
    const intPoint = Math.floor(p2);
    const weight = p2 - intPoint;
    const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
    const p1 = points[intPoint];
    const p22 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
    const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
    point.set(
      CatmullRom(weight, p0.x, p1.x, p22.x, p3.x),
      CatmullRom(weight, p0.y, p1.y, p22.y, p3.y)
    );
    return point;
  }
  copy(source) {
    super.copy(source);
    this.points = [];
    for (let i2 = 0, l2 = source.points.length; i2 < l2; i2++) {
      const point = source.points[i2];
      this.points.push(point.clone());
    }
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.points = [];
    for (let i2 = 0, l2 = this.points.length; i2 < l2; i2++) {
      const point = this.points[i2];
      data.points.push(point.toArray());
    }
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.points = [];
    for (let i2 = 0, l2 = json3.points.length; i2 < l2; i2++) {
      const point = json3.points[i2];
      this.points.push(new Vector2().fromArray(point));
    }
    return this;
  }
}
var Curves = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ArcCurve,
  CatmullRomCurve3,
  CubicBezierCurve,
  CubicBezierCurve3,
  EllipseCurve,
  LineCurve,
  LineCurve3,
  QuadraticBezierCurve,
  QuadraticBezierCurve3,
  SplineCurve
});
class CurvePath extends Curve {
  constructor() {
    super();
    this.type = "CurvePath";
    this.curves = [];
    this.autoClose = false;
  }
  add(curve) {
    this.curves.push(curve);
  }
  closePath() {
    const startPoint = this.curves[0].getPoint(0);
    const endPoint = this.curves[this.curves.length - 1].getPoint(1);
    if (!startPoint.equals(endPoint)) {
      const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3";
      this.curves.push(new Curves[lineType](endPoint, startPoint));
    }
    return this;
  }
  // To get accurate point with reference to
  // entire path distance at time t,
  // following has to be done:
  // 1. Length of each sub path have to be known
  // 2. Locate and identify type of curve
  // 3. Get t for the curve
  // 4. Return curve.getPointAt(t')
  getPoint(t2, optionalTarget) {
    const d2 = t2 * this.getLength();
    const curveLengths = this.getCurveLengths();
    let i2 = 0;
    while (i2 < curveLengths.length) {
      if (curveLengths[i2] >= d2) {
        const diff = curveLengths[i2] - d2;
        const curve = this.curves[i2];
        const segmentLength = curve.getLength();
        const u2 = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
        return curve.getPointAt(u2, optionalTarget);
      }
      i2++;
    }
    return null;
  }
  // We cannot use the default THREE.Curve getPoint() with getLength() because in
  // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  // getPoint() depends on getLength
  getLength() {
    const lens = this.getCurveLengths();
    return lens[lens.length - 1];
  }
  // cacheLengths must be recalculated.
  updateArcLengths() {
    this.needsUpdate = true;
    this.cacheLengths = null;
    this.getCurveLengths();
  }
  // Compute lengths and cache them
  // We cannot overwrite getLengths() because UtoT mapping uses it.
  getCurveLengths() {
    if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
      return this.cacheLengths;
    }
    const lengths = [];
    let sums = 0;
    for (let i2 = 0, l2 = this.curves.length; i2 < l2; i2++) {
      sums += this.curves[i2].getLength();
      lengths.push(sums);
    }
    this.cacheLengths = lengths;
    return lengths;
  }
  getSpacedPoints(divisions = 40) {
    const points = [];
    for (let i2 = 0; i2 <= divisions; i2++) {
      points.push(this.getPoint(i2 / divisions));
    }
    if (this.autoClose) {
      points.push(points[0]);
    }
    return points;
  }
  getPoints(divisions = 12) {
    const points = [];
    let last;
    for (let i2 = 0, curves = this.curves; i2 < curves.length; i2++) {
      const curve = curves[i2];
      const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
      const pts = curve.getPoints(resolution);
      for (let j2 = 0; j2 < pts.length; j2++) {
        const point = pts[j2];
        if (last && last.equals(point)) continue;
        points.push(point);
        last = point;
      }
    }
    if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
      points.push(points[0]);
    }
    return points;
  }
  copy(source) {
    super.copy(source);
    this.curves = [];
    for (let i2 = 0, l2 = source.curves.length; i2 < l2; i2++) {
      const curve = source.curves[i2];
      this.curves.push(curve.clone());
    }
    this.autoClose = source.autoClose;
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.autoClose = this.autoClose;
    data.curves = [];
    for (let i2 = 0, l2 = this.curves.length; i2 < l2; i2++) {
      const curve = this.curves[i2];
      data.curves.push(curve.toJSON());
    }
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.autoClose = json3.autoClose;
    this.curves = [];
    for (let i2 = 0, l2 = json3.curves.length; i2 < l2; i2++) {
      const curve = json3.curves[i2];
      this.curves.push(new Curves[curve.type]().fromJSON(curve));
    }
    return this;
  }
}
class Path extends CurvePath {
  constructor(points) {
    super();
    this.type = "Path";
    this.currentPoint = new Vector2();
    if (points) {
      this.setFromPoints(points);
    }
  }
  setFromPoints(points) {
    this.moveTo(points[0].x, points[0].y);
    for (let i2 = 1, l2 = points.length; i2 < l2; i2++) {
      this.lineTo(points[i2].x, points[i2].y);
    }
    return this;
  }
  moveTo(x, y2) {
    this.currentPoint.set(x, y2);
    return this;
  }
  lineTo(x, y2) {
    const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y2));
    this.curves.push(curve);
    this.currentPoint.set(x, y2);
    return this;
  }
  quadraticCurveTo(aCPx, aCPy, aX, aY) {
    const curve = new QuadraticBezierCurve(
      this.currentPoint.clone(),
      new Vector2(aCPx, aCPy),
      new Vector2(aX, aY)
    );
    this.curves.push(curve);
    this.currentPoint.set(aX, aY);
    return this;
  }
  bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
    const curve = new CubicBezierCurve(
      this.currentPoint.clone(),
      new Vector2(aCP1x, aCP1y),
      new Vector2(aCP2x, aCP2y),
      new Vector2(aX, aY)
    );
    this.curves.push(curve);
    this.currentPoint.set(aX, aY);
    return this;
  }
  splineThru(pts) {
    const npts = [this.currentPoint.clone()].concat(pts);
    const curve = new SplineCurve(npts);
    this.curves.push(curve);
    this.currentPoint.copy(pts[pts.length - 1]);
    return this;
  }
  arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
    const x0 = this.currentPoint.x;
    const y0 = this.currentPoint.y;
    this.absarc(
      aX + x0,
      aY + y0,
      aRadius,
      aStartAngle,
      aEndAngle,
      aClockwise
    );
    return this;
  }
  absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
    this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
    return this;
  }
  ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
    const x0 = this.currentPoint.x;
    const y0 = this.currentPoint.y;
    this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
    return this;
  }
  absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
    const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
    if (this.curves.length > 0) {
      const firstPoint = curve.getPoint(0);
      if (!firstPoint.equals(this.currentPoint)) {
        this.lineTo(firstPoint.x, firstPoint.y);
      }
    }
    this.curves.push(curve);
    const lastPoint = curve.getPoint(1);
    this.currentPoint.copy(lastPoint);
    return this;
  }
  copy(source) {
    super.copy(source);
    this.currentPoint.copy(source.currentPoint);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.currentPoint = this.currentPoint.toArray();
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.currentPoint.fromArray(json3.currentPoint);
    return this;
  }
}
class LatheGeometry extends BufferGeometry {
  constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
    super();
    this.type = "LatheGeometry";
    this.parameters = {
      points,
      segments,
      phiStart,
      phiLength
    };
    segments = Math.floor(segments);
    phiLength = clamp(phiLength, 0, Math.PI * 2);
    const indices = [];
    const vertices = [];
    const uvs = [];
    const initNormals = [];
    const normals = [];
    const inverseSegments = 1 / segments;
    const vertex2 = new Vector3();
    const uv = new Vector2();
    const normal = new Vector3();
    const curNormal = new Vector3();
    const prevNormal = new Vector3();
    let dx = 0;
    let dy = 0;
    for (let j2 = 0; j2 <= points.length - 1; j2++) {
      switch (j2) {
        case 0:
          dx = points[j2 + 1].x - points[j2].x;
          dy = points[j2 + 1].y - points[j2].y;
          normal.x = dy * 1;
          normal.y = -dx;
          normal.z = dy * 0;
          prevNormal.copy(normal);
          normal.normalize();
          initNormals.push(normal.x, normal.y, normal.z);
          break;
        case points.length - 1:
          initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
          break;
        default:
          dx = points[j2 + 1].x - points[j2].x;
          dy = points[j2 + 1].y - points[j2].y;
          normal.x = dy * 1;
          normal.y = -dx;
          normal.z = dy * 0;
          curNormal.copy(normal);
          normal.x += prevNormal.x;
          normal.y += prevNormal.y;
          normal.z += prevNormal.z;
          normal.normalize();
          initNormals.push(normal.x, normal.y, normal.z);
          prevNormal.copy(curNormal);
      }
    }
    for (let i2 = 0; i2 <= segments; i2++) {
      const phi = phiStart + i2 * inverseSegments * phiLength;
      const sin = Math.sin(phi);
      const cos = Math.cos(phi);
      for (let j2 = 0; j2 <= points.length - 1; j2++) {
        vertex2.x = points[j2].x * sin;
        vertex2.y = points[j2].y;
        vertex2.z = points[j2].x * cos;
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        uv.x = i2 / segments;
        uv.y = j2 / (points.length - 1);
        uvs.push(uv.x, uv.y);
        const x = initNormals[3 * j2 + 0] * sin;
        const y2 = initNormals[3 * j2 + 1];
        const z2 = initNormals[3 * j2 + 0] * cos;
        normals.push(x, y2, z2);
      }
    }
    for (let i2 = 0; i2 < segments; i2++) {
      for (let j2 = 0; j2 < points.length - 1; j2++) {
        const base = j2 + i2 * points.length;
        const a3 = base;
        const b2 = base + points.length;
        const c2 = base + points.length + 1;
        const d2 = base + 1;
        indices.push(a3, b2, d2);
        indices.push(c2, d2, b2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  }
}
class CapsuleGeometry extends LatheGeometry {
  constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
    const path = new Path();
    path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
    path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
    super(path.getPoints(capSegments), radialSegments);
    this.type = "CapsuleGeometry";
    this.parameters = {
      radius,
      length,
      capSegments,
      radialSegments
    };
  }
  static fromJSON(data) {
    return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  }
}
class CircleGeometry extends BufferGeometry {
  constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) {
    super();
    this.type = "CircleGeometry";
    this.parameters = {
      radius,
      segments,
      thetaStart,
      thetaLength
    };
    segments = Math.max(3, segments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    const vertex2 = new Vector3();
    const uv = new Vector2();
    vertices.push(0, 0, 0);
    normals.push(0, 0, 1);
    uvs.push(0.5, 0.5);
    for (let s2 = 0, i2 = 3; s2 <= segments; s2++, i2 += 3) {
      const segment = thetaStart + s2 / segments * thetaLength;
      vertex2.x = radius * Math.cos(segment);
      vertex2.y = radius * Math.sin(segment);
      vertices.push(vertex2.x, vertex2.y, vertex2.z);
      normals.push(0, 0, 1);
      uv.x = (vertices[i2] / radius + 1) / 2;
      uv.y = (vertices[i2 + 1] / radius + 1) / 2;
      uvs.push(uv.x, uv.y);
    }
    for (let i2 = 1; i2 <= segments; i2++) {
      indices.push(i2, i2 + 1, 0);
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  }
}
class CylinderGeometry extends BufferGeometry {
  constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
    super();
    this.type = "CylinderGeometry";
    this.parameters = {
      radiusTop,
      radiusBottom,
      height,
      radialSegments,
      heightSegments,
      openEnded,
      thetaStart,
      thetaLength
    };
    const scope = this;
    radialSegments = Math.floor(radialSegments);
    heightSegments = Math.floor(heightSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let index = 0;
    const indexArray = [];
    const halfHeight = height / 2;
    let groupStart = 0;
    generateTorso();
    if (openEnded === false) {
      if (radiusTop > 0) generateCap(true);
      if (radiusBottom > 0) generateCap(false);
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function generateTorso() {
      const normal = new Vector3();
      const vertex2 = new Vector3();
      let groupCount = 0;
      const slope = (radiusBottom - radiusTop) / height;
      for (let y2 = 0; y2 <= heightSegments; y2++) {
        const indexRow = [];
        const v5 = y2 / heightSegments;
        const radius = v5 * (radiusBottom - radiusTop) + radiusTop;
        for (let x = 0; x <= radialSegments; x++) {
          const u2 = x / radialSegments;
          const theta = u2 * thetaLength + thetaStart;
          const sinTheta = Math.sin(theta);
          const cosTheta = Math.cos(theta);
          vertex2.x = radius * sinTheta;
          vertex2.y = -v5 * height + halfHeight;
          vertex2.z = radius * cosTheta;
          vertices.push(vertex2.x, vertex2.y, vertex2.z);
          normal.set(sinTheta, slope, cosTheta).normalize();
          normals.push(normal.x, normal.y, normal.z);
          uvs.push(u2, 1 - v5);
          indexRow.push(index++);
        }
        indexArray.push(indexRow);
      }
      for (let x = 0; x < radialSegments; x++) {
        for (let y2 = 0; y2 < heightSegments; y2++) {
          const a3 = indexArray[y2][x];
          const b2 = indexArray[y2 + 1][x];
          const c2 = indexArray[y2 + 1][x + 1];
          const d2 = indexArray[y2][x + 1];
          if (radiusTop > 0 || y2 !== 0) {
            indices.push(a3, b2, d2);
            groupCount += 3;
          }
          if (radiusBottom > 0 || y2 !== heightSegments - 1) {
            indices.push(b2, c2, d2);
            groupCount += 3;
          }
        }
      }
      scope.addGroup(groupStart, groupCount, 0);
      groupStart += groupCount;
    }
    function generateCap(top) {
      const centerIndexStart = index;
      const uv = new Vector2();
      const vertex2 = new Vector3();
      let groupCount = 0;
      const radius = top === true ? radiusTop : radiusBottom;
      const sign2 = top === true ? 1 : -1;
      for (let x = 1; x <= radialSegments; x++) {
        vertices.push(0, halfHeight * sign2, 0);
        normals.push(0, sign2, 0);
        uvs.push(0.5, 0.5);
        index++;
      }
      const centerIndexEnd = index;
      for (let x = 0; x <= radialSegments; x++) {
        const u2 = x / radialSegments;
        const theta = u2 * thetaLength + thetaStart;
        const cosTheta = Math.cos(theta);
        const sinTheta = Math.sin(theta);
        vertex2.x = radius * sinTheta;
        vertex2.y = halfHeight * sign2;
        vertex2.z = radius * cosTheta;
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        normals.push(0, sign2, 0);
        uv.x = cosTheta * 0.5 + 0.5;
        uv.y = sinTheta * 0.5 * sign2 + 0.5;
        uvs.push(uv.x, uv.y);
        index++;
      }
      for (let x = 0; x < radialSegments; x++) {
        const c2 = centerIndexStart + x;
        const i2 = centerIndexEnd + x;
        if (top === true) {
          indices.push(i2, i2 + 1, c2);
        } else {
          indices.push(i2 + 1, i2, c2);
        }
        groupCount += 3;
      }
      scope.addGroup(groupStart, groupCount, top === true ? 1 : 2);
      groupStart += groupCount;
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  }
}
class ConeGeometry extends CylinderGeometry {
  constructor(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
    super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
    this.type = "ConeGeometry";
    this.parameters = {
      radius,
      height,
      radialSegments,
      heightSegments,
      openEnded,
      thetaStart,
      thetaLength
    };
  }
  static fromJSON(data) {
    return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  }
}
class PolyhedronGeometry extends BufferGeometry {
  constructor(vertices = [], indices = [], radius = 1, detail = 0) {
    super();
    this.type = "PolyhedronGeometry";
    this.parameters = {
      vertices,
      indices,
      radius,
      detail
    };
    const vertexBuffer = [];
    const uvBuffer = [];
    subdivide(detail);
    applyRadius(radius);
    generateUVs();
    this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3));
    this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2));
    if (detail === 0) {
      this.computeVertexNormals();
    } else {
      this.normalizeNormals();
    }
    function subdivide(detail2) {
      const a3 = new Vector3();
      const b2 = new Vector3();
      const c2 = new Vector3();
      for (let i2 = 0; i2 < indices.length; i2 += 3) {
        getVertexByIndex(indices[i2 + 0], a3);
        getVertexByIndex(indices[i2 + 1], b2);
        getVertexByIndex(indices[i2 + 2], c2);
        subdivideFace(a3, b2, c2, detail2);
      }
    }
    function subdivideFace(a3, b2, c2, detail2) {
      const cols = detail2 + 1;
      const v5 = [];
      for (let i2 = 0; i2 <= cols; i2++) {
        v5[i2] = [];
        const aj = a3.clone().lerp(c2, i2 / cols);
        const bj = b2.clone().lerp(c2, i2 / cols);
        const rows = cols - i2;
        for (let j2 = 0; j2 <= rows; j2++) {
          if (j2 === 0 && i2 === cols) {
            v5[i2][j2] = aj;
          } else {
            v5[i2][j2] = aj.clone().lerp(bj, j2 / rows);
          }
        }
      }
      for (let i2 = 0; i2 < cols; i2++) {
        for (let j2 = 0; j2 < 2 * (cols - i2) - 1; j2++) {
          const k2 = Math.floor(j2 / 2);
          if (j2 % 2 === 0) {
            pushVertex(v5[i2][k2 + 1]);
            pushVertex(v5[i2 + 1][k2]);
            pushVertex(v5[i2][k2]);
          } else {
            pushVertex(v5[i2][k2 + 1]);
            pushVertex(v5[i2 + 1][k2 + 1]);
            pushVertex(v5[i2 + 1][k2]);
          }
        }
      }
    }
    function applyRadius(radius2) {
      const vertex2 = new Vector3();
      for (let i2 = 0; i2 < vertexBuffer.length; i2 += 3) {
        vertex2.x = vertexBuffer[i2 + 0];
        vertex2.y = vertexBuffer[i2 + 1];
        vertex2.z = vertexBuffer[i2 + 2];
        vertex2.normalize().multiplyScalar(radius2);
        vertexBuffer[i2 + 0] = vertex2.x;
        vertexBuffer[i2 + 1] = vertex2.y;
        vertexBuffer[i2 + 2] = vertex2.z;
      }
    }
    function generateUVs() {
      const vertex2 = new Vector3();
      for (let i2 = 0; i2 < vertexBuffer.length; i2 += 3) {
        vertex2.x = vertexBuffer[i2 + 0];
        vertex2.y = vertexBuffer[i2 + 1];
        vertex2.z = vertexBuffer[i2 + 2];
        const u2 = azimuth(vertex2) / 2 / Math.PI + 0.5;
        const v5 = inclination(vertex2) / Math.PI + 0.5;
        uvBuffer.push(u2, 1 - v5);
      }
      correctUVs();
      correctSeam();
    }
    function correctSeam() {
      for (let i2 = 0; i2 < uvBuffer.length; i2 += 6) {
        const x0 = uvBuffer[i2 + 0];
        const x1 = uvBuffer[i2 + 2];
        const x2 = uvBuffer[i2 + 4];
        const max2 = Math.max(x0, x1, x2);
        const min = Math.min(x0, x1, x2);
        if (max2 > 0.9 && min < 0.1) {
          if (x0 < 0.2) uvBuffer[i2 + 0] += 1;
          if (x1 < 0.2) uvBuffer[i2 + 2] += 1;
          if (x2 < 0.2) uvBuffer[i2 + 4] += 1;
        }
      }
    }
    function pushVertex(vertex2) {
      vertexBuffer.push(vertex2.x, vertex2.y, vertex2.z);
    }
    function getVertexByIndex(index, vertex2) {
      const stride = index * 3;
      vertex2.x = vertices[stride + 0];
      vertex2.y = vertices[stride + 1];
      vertex2.z = vertices[stride + 2];
    }
    function correctUVs() {
      const a3 = new Vector3();
      const b2 = new Vector3();
      const c2 = new Vector3();
      const centroid = new Vector3();
      const uvA = new Vector2();
      const uvB = new Vector2();
      const uvC = new Vector2();
      for (let i2 = 0, j2 = 0; i2 < vertexBuffer.length; i2 += 9, j2 += 6) {
        a3.set(vertexBuffer[i2 + 0], vertexBuffer[i2 + 1], vertexBuffer[i2 + 2]);
        b2.set(vertexBuffer[i2 + 3], vertexBuffer[i2 + 4], vertexBuffer[i2 + 5]);
        c2.set(vertexBuffer[i2 + 6], vertexBuffer[i2 + 7], vertexBuffer[i2 + 8]);
        uvA.set(uvBuffer[j2 + 0], uvBuffer[j2 + 1]);
        uvB.set(uvBuffer[j2 + 2], uvBuffer[j2 + 3]);
        uvC.set(uvBuffer[j2 + 4], uvBuffer[j2 + 5]);
        centroid.copy(a3).add(b2).add(c2).divideScalar(3);
        const azi = azimuth(centroid);
        correctUV(uvA, j2 + 0, a3, azi);
        correctUV(uvB, j2 + 2, b2, azi);
        correctUV(uvC, j2 + 4, c2, azi);
      }
    }
    function correctUV(uv, stride, vector, azimuth2) {
      if (azimuth2 < 0 && uv.x === 1) {
        uvBuffer[stride] = uv.x - 1;
      }
      if (vector.x === 0 && vector.z === 0) {
        uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5;
      }
    }
    function azimuth(vector) {
      return Math.atan2(vector.z, -vector.x);
    }
    function inclination(vector) {
      return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  }
}
class DodecahedronGeometry extends PolyhedronGeometry {
  constructor(radius = 1, detail = 0) {
    const t2 = (1 + Math.sqrt(5)) / 2;
    const r2 = 1 / t2;
    const vertices = [
      // (±1, ±1, ±1)
      -1,
      -1,
      -1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      1,
      1,
      -1,
      1,
      1,
      1,
      // (0, ±1/φ, ±φ)
      0,
      -r2,
      -t2,
      0,
      -r2,
      t2,
      0,
      r2,
      -t2,
      0,
      r2,
      t2,
      // (±1/φ, ±φ, 0)
      -r2,
      -t2,
      0,
      -r2,
      t2,
      0,
      r2,
      -t2,
      0,
      r2,
      t2,
      0,
      // (±φ, 0, ±1/φ)
      -t2,
      0,
      -r2,
      t2,
      0,
      -r2,
      -t2,
      0,
      r2,
      t2,
      0,
      r2
    ];
    const indices = [
      3,
      11,
      7,
      3,
      7,
      15,
      3,
      15,
      13,
      7,
      19,
      17,
      7,
      17,
      6,
      7,
      6,
      15,
      17,
      4,
      8,
      17,
      8,
      10,
      17,
      10,
      6,
      8,
      0,
      16,
      8,
      16,
      2,
      8,
      2,
      10,
      0,
      12,
      1,
      0,
      1,
      18,
      0,
      18,
      16,
      6,
      10,
      2,
      6,
      2,
      13,
      6,
      13,
      15,
      2,
      16,
      18,
      2,
      18,
      3,
      2,
      3,
      13,
      18,
      1,
      9,
      18,
      9,
      11,
      18,
      11,
      3,
      4,
      14,
      12,
      4,
      12,
      0,
      4,
      0,
      8,
      11,
      9,
      5,
      11,
      5,
      19,
      11,
      19,
      7,
      19,
      5,
      14,
      19,
      14,
      4,
      19,
      4,
      17,
      1,
      12,
      14,
      1,
      14,
      5,
      1,
      5,
      9
    ];
    super(vertices, indices, radius, detail);
    this.type = "DodecahedronGeometry";
    this.parameters = {
      radius,
      detail
    };
  }
  static fromJSON(data) {
    return new DodecahedronGeometry(data.radius, data.detail);
  }
}
const _v0$3 = /* @__PURE__ */ new Vector3();
const _v1$1 = /* @__PURE__ */ new Vector3();
const _normal = /* @__PURE__ */ new Vector3();
const _triangle = /* @__PURE__ */ new Triangle();
class EdgesGeometry extends BufferGeometry {
  constructor(geometry = null, thresholdAngle = 1) {
    super();
    this.type = "EdgesGeometry";
    this.parameters = {
      geometry,
      thresholdAngle
    };
    if (geometry !== null) {
      const precisionPoints = 4;
      const precision = Math.pow(10, precisionPoints);
      const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
      const indexAttr = geometry.getIndex();
      const positionAttr = geometry.getAttribute("position");
      const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
      const indexArr = [0, 0, 0];
      const vertKeys = ["a", "b", "c"];
      const hashes = new Array(3);
      const edgeData = {};
      const vertices = [];
      for (let i2 = 0; i2 < indexCount; i2 += 3) {
        if (indexAttr) {
          indexArr[0] = indexAttr.getX(i2);
          indexArr[1] = indexAttr.getX(i2 + 1);
          indexArr[2] = indexAttr.getX(i2 + 2);
        } else {
          indexArr[0] = i2;
          indexArr[1] = i2 + 1;
          indexArr[2] = i2 + 2;
        }
        const { a: a3, b: b2, c: c2 } = _triangle;
        a3.fromBufferAttribute(positionAttr, indexArr[0]);
        b2.fromBufferAttribute(positionAttr, indexArr[1]);
        c2.fromBufferAttribute(positionAttr, indexArr[2]);
        _triangle.getNormal(_normal);
        hashes[0] = `${Math.round(a3.x * precision)},${Math.round(a3.y * precision)},${Math.round(a3.z * precision)}`;
        hashes[1] = `${Math.round(b2.x * precision)},${Math.round(b2.y * precision)},${Math.round(b2.z * precision)}`;
        hashes[2] = `${Math.round(c2.x * precision)},${Math.round(c2.y * precision)},${Math.round(c2.z * precision)}`;
        if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
          continue;
        }
        for (let j2 = 0; j2 < 3; j2++) {
          const jNext = (j2 + 1) % 3;
          const vecHash0 = hashes[j2];
          const vecHash1 = hashes[jNext];
          const v0 = _triangle[vertKeys[j2]];
          const v12 = _triangle[vertKeys[jNext]];
          const hash = `${vecHash0}_${vecHash1}`;
          const reverseHash = `${vecHash1}_${vecHash0}`;
          if (reverseHash in edgeData && edgeData[reverseHash]) {
            if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
              vertices.push(v0.x, v0.y, v0.z);
              vertices.push(v12.x, v12.y, v12.z);
            }
            edgeData[reverseHash] = null;
          } else if (!(hash in edgeData)) {
            edgeData[hash] = {
              index0: indexArr[j2],
              index1: indexArr[jNext],
              normal: _normal.clone()
            };
          }
        }
      }
      for (const key in edgeData) {
        if (edgeData[key]) {
          const { index0, index1 } = edgeData[key];
          _v0$3.fromBufferAttribute(positionAttr, index0);
          _v1$1.fromBufferAttribute(positionAttr, index1);
          vertices.push(_v0$3.x, _v0$3.y, _v0$3.z);
          vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
        }
      }
      this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
}
class Shape extends Path {
  constructor(points) {
    super(points);
    this.uuid = generateUUID();
    this.type = "Shape";
    this.holes = [];
  }
  getPointsHoles(divisions) {
    const holesPts = [];
    for (let i2 = 0, l2 = this.holes.length; i2 < l2; i2++) {
      holesPts[i2] = this.holes[i2].getPoints(divisions);
    }
    return holesPts;
  }
  // get points of shape and holes (keypoints based on segments parameter)
  extractPoints(divisions) {
    return {
      shape: this.getPoints(divisions),
      holes: this.getPointsHoles(divisions)
    };
  }
  copy(source) {
    super.copy(source);
    this.holes = [];
    for (let i2 = 0, l2 = source.holes.length; i2 < l2; i2++) {
      const hole = source.holes[i2];
      this.holes.push(hole.clone());
    }
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.uuid = this.uuid;
    data.holes = [];
    for (let i2 = 0, l2 = this.holes.length; i2 < l2; i2++) {
      const hole = this.holes[i2];
      data.holes.push(hole.toJSON());
    }
    return data;
  }
  fromJSON(json3) {
    super.fromJSON(json3);
    this.uuid = json3.uuid;
    this.holes = [];
    for (let i2 = 0, l2 = json3.holes.length; i2 < l2; i2++) {
      const hole = json3.holes[i2];
      this.holes.push(new Path().fromJSON(hole));
    }
    return this;
  }
}
const Earcut = {
  triangulate: function(data, holeIndices, dim = 2) {
    const hasHoles = holeIndices && holeIndices.length;
    const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
    let outerNode = linkedList(data, 0, outerLen, dim, true);
    const triangles = [];
    if (!outerNode || outerNode.next === outerNode.prev) return triangles;
    let minX, minY, maxX, maxY, x, y2, invSize;
    if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
    if (data.length > 80 * dim) {
      minX = maxX = data[0];
      minY = maxY = data[1];
      for (let i2 = dim; i2 < outerLen; i2 += dim) {
        x = data[i2];
        y2 = data[i2 + 1];
        if (x < minX) minX = x;
        if (y2 < minY) minY = y2;
        if (x > maxX) maxX = x;
        if (y2 > maxY) maxY = y2;
      }
      invSize = Math.max(maxX - minX, maxY - minY);
      invSize = invSize !== 0 ? 32767 / invSize : 0;
    }
    earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
    return triangles;
  }
};
function linkedList(data, start, end, dim, clockwise) {
  let i2, last;
  if (clockwise === signedArea(data, start, end, dim) > 0) {
    for (i2 = start; i2 < end; i2 += dim) last = insertNode(i2, data[i2], data[i2 + 1], last);
  } else {
    for (i2 = end - dim; i2 >= start; i2 -= dim) last = insertNode(i2, data[i2], data[i2 + 1], last);
  }
  if (last && equals(last, last.next)) {
    removeNode(last);
    last = last.next;
  }
  return last;
}
function filterPoints(start, end) {
  if (!start) return start;
  if (!end) end = start;
  let p2 = start, again;
  do {
    again = false;
    if (!p2.steiner && (equals(p2, p2.next) || area(p2.prev, p2, p2.next) === 0)) {
      removeNode(p2);
      p2 = end = p2.prev;
      if (p2 === p2.next) break;
      again = true;
    } else {
      p2 = p2.next;
    }
  } while (again || p2 !== end);
  return end;
}
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  if (!ear) return;
  if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  let stop = ear, prev, next;
  while (ear.prev !== ear.next) {
    prev = ear.prev;
    next = ear.next;
    if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
      triangles.push(prev.i / dim | 0);
      triangles.push(ear.i / dim | 0);
      triangles.push(next.i / dim | 0);
      removeNode(ear);
      ear = next.next;
      stop = next.next;
      continue;
    }
    ear = next;
    if (ear === stop) {
      if (!pass) {
        earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
      } else if (pass === 1) {
        ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
        earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
      } else if (pass === 2) {
        splitEarcut(ear, triangles, dim, minX, minY, invSize);
      }
      break;
    }
  }
}
function isEar(ear) {
  const a3 = ear.prev, b2 = ear, c2 = ear.next;
  if (area(a3, b2, c2) >= 0) return false;
  const ax = a3.x, bx = b2.x, cx = c2.x, ay = a3.y, by = b2.y, cy = c2.y;
  const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  let p2 = c2.next;
  while (p2 !== a3) {
    if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false;
    p2 = p2.next;
  }
  return true;
}
function isEarHashed(ear, minX, minY, invSize) {
  const a3 = ear.prev, b2 = ear, c2 = ear.next;
  if (area(a3, b2, c2) >= 0) return false;
  const ax = a3.x, bx = b2.x, cx = c2.x, ay = a3.y, by = b2.y, cy = c2.y;
  const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize);
  let p2 = ear.prevZ, n2 = ear.nextZ;
  while (p2 && p2.z >= minZ && n2 && n2.z <= maxZ) {
    if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a3 && p2 !== c2 && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false;
    p2 = p2.prevZ;
    if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a3 && n2 !== c2 && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false;
    n2 = n2.nextZ;
  }
  while (p2 && p2.z >= minZ) {
    if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a3 && p2 !== c2 && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false;
    p2 = p2.prevZ;
  }
  while (n2 && n2.z <= maxZ) {
    if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a3 && n2 !== c2 && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false;
    n2 = n2.nextZ;
  }
  return true;
}
function cureLocalIntersections(start, triangles, dim) {
  let p2 = start;
  do {
    const a3 = p2.prev, b2 = p2.next.next;
    if (!equals(a3, b2) && intersects(a3, p2, p2.next, b2) && locallyInside(a3, b2) && locallyInside(b2, a3)) {
      triangles.push(a3.i / dim | 0);
      triangles.push(p2.i / dim | 0);
      triangles.push(b2.i / dim | 0);
      removeNode(p2);
      removeNode(p2.next);
      p2 = start = b2;
    }
    p2 = p2.next;
  } while (p2 !== start);
  return filterPoints(p2);
}
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  let a3 = start;
  do {
    let b2 = a3.next.next;
    while (b2 !== a3.prev) {
      if (a3.i !== b2.i && isValidDiagonal(a3, b2)) {
        let c2 = splitPolygon(a3, b2);
        a3 = filterPoints(a3, a3.next);
        c2 = filterPoints(c2, c2.next);
        earcutLinked(a3, triangles, dim, minX, minY, invSize, 0);
        earcutLinked(c2, triangles, dim, minX, minY, invSize, 0);
        return;
      }
      b2 = b2.next;
    }
    a3 = a3.next;
  } while (a3 !== start);
}
function eliminateHoles(data, holeIndices, outerNode, dim) {
  const queue = [];
  let i2, len, start, end, list;
  for (i2 = 0, len = holeIndices.length; i2 < len; i2++) {
    start = holeIndices[i2] * dim;
    end = i2 < len - 1 ? holeIndices[i2 + 1] * dim : data.length;
    list = linkedList(data, start, end, dim, false);
    if (list === list.next) list.steiner = true;
    queue.push(getLeftmost(list));
  }
  queue.sort(compareX);
  for (i2 = 0; i2 < queue.length; i2++) {
    outerNode = eliminateHole(queue[i2], outerNode);
  }
  return outerNode;
}
function compareX(a3, b2) {
  return a3.x - b2.x;
}
function eliminateHole(hole, outerNode) {
  const bridge = findHoleBridge(hole, outerNode);
  if (!bridge) {
    return outerNode;
  }
  const bridgeReverse = splitPolygon(bridge, hole);
  filterPoints(bridgeReverse, bridgeReverse.next);
  return filterPoints(bridge, bridge.next);
}
function findHoleBridge(hole, outerNode) {
  let p2 = outerNode, qx = -Infinity, m2;
  const hx = hole.x, hy = hole.y;
  do {
    if (hy <= p2.y && hy >= p2.next.y && p2.next.y !== p2.y) {
      const x = p2.x + (hy - p2.y) * (p2.next.x - p2.x) / (p2.next.y - p2.y);
      if (x <= hx && x > qx) {
        qx = x;
        m2 = p2.x < p2.next.x ? p2 : p2.next;
        if (x === hx) return m2;
      }
    }
    p2 = p2.next;
  } while (p2 !== outerNode);
  if (!m2) return null;
  const stop = m2, mx = m2.x, my = m2.y;
  let tanMin = Infinity, tan;
  p2 = m2;
  do {
    if (hx >= p2.x && p2.x >= mx && hx !== p2.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p2.x, p2.y)) {
      tan = Math.abs(hy - p2.y) / (hx - p2.x);
      if (locallyInside(p2, hole) && (tan < tanMin || tan === tanMin && (p2.x > m2.x || p2.x === m2.x && sectorContainsSector(m2, p2)))) {
        m2 = p2;
        tanMin = tan;
      }
    }
    p2 = p2.next;
  } while (p2 !== stop);
  return m2;
}
function sectorContainsSector(m2, p2) {
  return area(m2.prev, m2, p2.prev) < 0 && area(p2.next, m2, m2.next) < 0;
}
function indexCurve(start, minX, minY, invSize) {
  let p2 = start;
  do {
    if (p2.z === 0) p2.z = zOrder(p2.x, p2.y, minX, minY, invSize);
    p2.prevZ = p2.prev;
    p2.nextZ = p2.next;
    p2 = p2.next;
  } while (p2 !== start);
  p2.prevZ.nextZ = null;
  p2.prevZ = null;
  sortLinked(p2);
}
function sortLinked(list) {
  let i2, p2, q3, e2, tail, numMerges, pSize, qSize, inSize = 1;
  do {
    p2 = list;
    list = null;
    tail = null;
    numMerges = 0;
    while (p2) {
      numMerges++;
      q3 = p2;
      pSize = 0;
      for (i2 = 0; i2 < inSize; i2++) {
        pSize++;
        q3 = q3.nextZ;
        if (!q3) break;
      }
      qSize = inSize;
      while (pSize > 0 || qSize > 0 && q3) {
        if (pSize !== 0 && (qSize === 0 || !q3 || p2.z <= q3.z)) {
          e2 = p2;
          p2 = p2.nextZ;
          pSize--;
        } else {
          e2 = q3;
          q3 = q3.nextZ;
          qSize--;
        }
        if (tail) tail.nextZ = e2;
        else list = e2;
        e2.prevZ = tail;
        tail = e2;
      }
      p2 = q3;
    }
    tail.nextZ = null;
    inSize *= 2;
  } while (numMerges > 1);
  return list;
}
function zOrder(x, y2, minX, minY, invSize) {
  x = (x - minX) * invSize | 0;
  y2 = (y2 - minY) * invSize | 0;
  x = (x | x << 8) & 16711935;
  x = (x | x << 4) & 252645135;
  x = (x | x << 2) & 858993459;
  x = (x | x << 1) & 1431655765;
  y2 = (y2 | y2 << 8) & 16711935;
  y2 = (y2 | y2 << 4) & 252645135;
  y2 = (y2 | y2 << 2) & 858993459;
  y2 = (y2 | y2 << 1) & 1431655765;
  return x | y2 << 1;
}
function getLeftmost(start) {
  let p2 = start, leftmost = start;
  do {
    if (p2.x < leftmost.x || p2.x === leftmost.x && p2.y < leftmost.y) leftmost = p2;
    p2 = p2.next;
  } while (p2 !== start);
  return leftmost;
}
function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) {
  return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2);
}
function isValidDiagonal(a3, b2) {
  return a3.next.i !== b2.i && a3.prev.i !== b2.i && !intersectsPolygon(a3, b2) && // dones't intersect other edges
  (locallyInside(a3, b2) && locallyInside(b2, a3) && middleInside(a3, b2) && // locally visible
  (area(a3.prev, a3, b2.prev) || area(a3, b2.prev, b2)) || // does not create opposite-facing sectors
  equals(a3, b2) && area(a3.prev, a3, a3.next) > 0 && area(b2.prev, b2, b2.next) > 0);
}
function area(p2, q3, r2) {
  return (q3.y - p2.y) * (r2.x - q3.x) - (q3.x - p2.x) * (r2.y - q3.y);
}
function equals(p1, p2) {
  return p1.x === p2.x && p1.y === p2.y;
}
function intersects(p1, q1, p2, q22) {
  const o1 = sign(area(p1, q1, p2));
  const o22 = sign(area(p1, q1, q22));
  const o32 = sign(area(p2, q22, p1));
  const o4 = sign(area(p2, q22, q1));
  if (o1 !== o22 && o32 !== o4) return true;
  if (o1 === 0 && onSegment(p1, p2, q1)) return true;
  if (o22 === 0 && onSegment(p1, q22, q1)) return true;
  if (o32 === 0 && onSegment(p2, p1, q22)) return true;
  if (o4 === 0 && onSegment(p2, q1, q22)) return true;
  return false;
}
function onSegment(p2, q3, r2) {
  return q3.x <= Math.max(p2.x, r2.x) && q3.x >= Math.min(p2.x, r2.x) && q3.y <= Math.max(p2.y, r2.y) && q3.y >= Math.min(p2.y, r2.y);
}
function sign(num) {
  return num > 0 ? 1 : num < 0 ? -1 : 0;
}
function intersectsPolygon(a3, b2) {
  let p2 = a3;
  do {
    if (p2.i !== a3.i && p2.next.i !== a3.i && p2.i !== b2.i && p2.next.i !== b2.i && intersects(p2, p2.next, a3, b2)) return true;
    p2 = p2.next;
  } while (p2 !== a3);
  return false;
}
function locallyInside(a3, b2) {
  return area(a3.prev, a3, a3.next) < 0 ? area(a3, b2, a3.next) >= 0 && area(a3, a3.prev, b2) >= 0 : area(a3, b2, a3.prev) < 0 || area(a3, a3.next, b2) < 0;
}
function middleInside(a3, b2) {
  let p2 = a3, inside = false;
  const px2 = (a3.x + b2.x) / 2, py2 = (a3.y + b2.y) / 2;
  do {
    if (p2.y > py2 !== p2.next.y > py2 && p2.next.y !== p2.y && px2 < (p2.next.x - p2.x) * (py2 - p2.y) / (p2.next.y - p2.y) + p2.x)
      inside = !inside;
    p2 = p2.next;
  } while (p2 !== a3);
  return inside;
}
function splitPolygon(a3, b2) {
  const a22 = new Node$1(a3.i, a3.x, a3.y), b22 = new Node$1(b2.i, b2.x, b2.y), an = a3.next, bp = b2.prev;
  a3.next = b2;
  b2.prev = a3;
  a22.next = an;
  an.prev = a22;
  b22.next = a22;
  a22.prev = b22;
  bp.next = b22;
  b22.prev = bp;
  return b22;
}
function insertNode(i2, x, y2, last) {
  const p2 = new Node$1(i2, x, y2);
  if (!last) {
    p2.prev = p2;
    p2.next = p2;
  } else {
    p2.next = last.next;
    p2.prev = last;
    last.next.prev = p2;
    last.next = p2;
  }
  return p2;
}
function removeNode(p2) {
  p2.next.prev = p2.prev;
  p2.prev.next = p2.next;
  if (p2.prevZ) p2.prevZ.nextZ = p2.nextZ;
  if (p2.nextZ) p2.nextZ.prevZ = p2.prevZ;
}
function Node$1(i2, x, y2) {
  this.i = i2;
  this.x = x;
  this.y = y2;
  this.prev = null;
  this.next = null;
  this.z = 0;
  this.prevZ = null;
  this.nextZ = null;
  this.steiner = false;
}
function signedArea(data, start, end, dim) {
  let sum = 0;
  for (let i2 = start, j2 = end - dim; i2 < end; i2 += dim) {
    sum += (data[j2] - data[i2]) * (data[i2 + 1] + data[j2 + 1]);
    j2 = i2;
  }
  return sum;
}
class ShapeUtils {
  // calculate area of the contour polygon
  static area(contour) {
    const n2 = contour.length;
    let a3 = 0;
    for (let p2 = n2 - 1, q3 = 0; q3 < n2; p2 = q3++) {
      a3 += contour[p2].x * contour[q3].y - contour[q3].x * contour[p2].y;
    }
    return a3 * 0.5;
  }
  static isClockWise(pts) {
    return ShapeUtils.area(pts) < 0;
  }
  static triangulateShape(contour, holes) {
    const vertices = [];
    const holeIndices = [];
    const faces = [];
    removeDupEndPts(contour);
    addContour(vertices, contour);
    let holeIndex = contour.length;
    holes.forEach(removeDupEndPts);
    for (let i2 = 0; i2 < holes.length; i2++) {
      holeIndices.push(holeIndex);
      holeIndex += holes[i2].length;
      addContour(vertices, holes[i2]);
    }
    const triangles = Earcut.triangulate(vertices, holeIndices);
    for (let i2 = 0; i2 < triangles.length; i2 += 3) {
      faces.push(triangles.slice(i2, i2 + 3));
    }
    return faces;
  }
}
function removeDupEndPts(points) {
  const l2 = points.length;
  if (l2 > 2 && points[l2 - 1].equals(points[0])) {
    points.pop();
  }
}
function addContour(vertices, contour) {
  for (let i2 = 0; i2 < contour.length; i2++) {
    vertices.push(contour[i2].x);
    vertices.push(contour[i2].y);
  }
}
class ExtrudeGeometry extends BufferGeometry {
  constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
    super();
    this.type = "ExtrudeGeometry";
    this.parameters = {
      shapes,
      options
    };
    shapes = Array.isArray(shapes) ? shapes : [shapes];
    const scope = this;
    const verticesArray = [];
    const uvArray = [];
    for (let i2 = 0, l2 = shapes.length; i2 < l2; i2++) {
      const shape = shapes[i2];
      addShape(shape);
    }
    this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2));
    this.computeVertexNormals();
    function addShape(shape) {
      const placeholder = [];
      const curveSegments = options.curveSegments !== void 0 ? options.curveSegments : 12;
      const steps = options.steps !== void 0 ? options.steps : 1;
      const depth = options.depth !== void 0 ? options.depth : 1;
      let bevelEnabled = options.bevelEnabled !== void 0 ? options.bevelEnabled : true;
      let bevelThickness = options.bevelThickness !== void 0 ? options.bevelThickness : 0.2;
      let bevelSize = options.bevelSize !== void 0 ? options.bevelSize : bevelThickness - 0.1;
      let bevelOffset = options.bevelOffset !== void 0 ? options.bevelOffset : 0;
      let bevelSegments = options.bevelSegments !== void 0 ? options.bevelSegments : 3;
      const extrudePath = options.extrudePath;
      const uvgen = options.UVGenerator !== void 0 ? options.UVGenerator : WorldUVGenerator;
      let extrudePts, extrudeByPath = false;
      let splineTube, binormal, normal, position2;
      if (extrudePath) {
        extrudePts = extrudePath.getSpacedPoints(steps);
        extrudeByPath = true;
        bevelEnabled = false;
        splineTube = extrudePath.computeFrenetFrames(steps, false);
        binormal = new Vector3();
        normal = new Vector3();
        position2 = new Vector3();
      }
      if (!bevelEnabled) {
        bevelSegments = 0;
        bevelThickness = 0;
        bevelSize = 0;
        bevelOffset = 0;
      }
      const shapePoints = shape.extractPoints(curveSegments);
      let vertices = shapePoints.shape;
      const holes = shapePoints.holes;
      const reverse = !ShapeUtils.isClockWise(vertices);
      if (reverse) {
        vertices = vertices.reverse();
        for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
          const ahole = holes[h2];
          if (ShapeUtils.isClockWise(ahole)) {
            holes[h2] = ahole.reverse();
          }
        }
      }
      const faces = ShapeUtils.triangulateShape(vertices, holes);
      const contour = vertices;
      for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
        const ahole = holes[h2];
        vertices = vertices.concat(ahole);
      }
      function scalePt2(pt2, vec, size) {
        if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
        return pt2.clone().addScaledVector(vec, size);
      }
      const vlen = vertices.length, flen = faces.length;
      function getBevelVec(inPt, inPrev, inNext) {
        let v_trans_x, v_trans_y, shrink_by;
        const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
        const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
        const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y;
        const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
        if (Math.abs(collinear0) > Number.EPSILON) {
          const v_prev_len = Math.sqrt(v_prev_lensq);
          const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y);
          const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
          const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
          const ptNextShift_x = inNext.x - v_next_y / v_next_len;
          const ptNextShift_y = inNext.y + v_next_x / v_next_len;
          const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x);
          v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
          v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y;
          const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
          if (v_trans_lensq <= 2) {
            return new Vector2(v_trans_x, v_trans_y);
          } else {
            shrink_by = Math.sqrt(v_trans_lensq / 2);
          }
        } else {
          let direction_eq = false;
          if (v_prev_x > Number.EPSILON) {
            if (v_next_x > Number.EPSILON) {
              direction_eq = true;
            }
          } else {
            if (v_prev_x < -Number.EPSILON) {
              if (v_next_x < -Number.EPSILON) {
                direction_eq = true;
              }
            } else {
              if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
                direction_eq = true;
              }
            }
          }
          if (direction_eq) {
            v_trans_x = -v_prev_y;
            v_trans_y = v_prev_x;
            shrink_by = Math.sqrt(v_prev_lensq);
          } else {
            v_trans_x = v_prev_x;
            v_trans_y = v_prev_y;
            shrink_by = Math.sqrt(v_prev_lensq / 2);
          }
        }
        return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
      }
      const contourMovements = [];
      for (let i2 = 0, il = contour.length, j2 = il - 1, k2 = i2 + 1; i2 < il; i2++, j2++, k2++) {
        if (j2 === il) j2 = 0;
        if (k2 === il) k2 = 0;
        contourMovements[i2] = getBevelVec(contour[i2], contour[j2], contour[k2]);
      }
      const holesMovements = [];
      let oneHoleMovements, verticesMovements = contourMovements.concat();
      for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
        const ahole = holes[h2];
        oneHoleMovements = [];
        for (let i2 = 0, il = ahole.length, j2 = il - 1, k2 = i2 + 1; i2 < il; i2++, j2++, k2++) {
          if (j2 === il) j2 = 0;
          if (k2 === il) k2 = 0;
          oneHoleMovements[i2] = getBevelVec(ahole[i2], ahole[j2], ahole[k2]);
        }
        holesMovements.push(oneHoleMovements);
        verticesMovements = verticesMovements.concat(oneHoleMovements);
      }
      for (let b2 = 0; b2 < bevelSegments; b2++) {
        const t2 = b2 / bevelSegments;
        const z2 = bevelThickness * Math.cos(t2 * Math.PI / 2);
        const bs2 = bevelSize * Math.sin(t2 * Math.PI / 2) + bevelOffset;
        for (let i2 = 0, il = contour.length; i2 < il; i2++) {
          const vert = scalePt2(contour[i2], contourMovements[i2], bs2);
          v5(vert.x, vert.y, -z2);
        }
        for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
          const ahole = holes[h2];
          oneHoleMovements = holesMovements[h2];
          for (let i2 = 0, il = ahole.length; i2 < il; i2++) {
            const vert = scalePt2(ahole[i2], oneHoleMovements[i2], bs2);
            v5(vert.x, vert.y, -z2);
          }
        }
      }
      const bs = bevelSize + bevelOffset;
      for (let i2 = 0; i2 < vlen; i2++) {
        const vert = bevelEnabled ? scalePt2(vertices[i2], verticesMovements[i2], bs) : vertices[i2];
        if (!extrudeByPath) {
          v5(vert.x, vert.y, 0);
        } else {
          normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
          binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
          position2.copy(extrudePts[0]).add(normal).add(binormal);
          v5(position2.x, position2.y, position2.z);
        }
      }
      for (let s2 = 1; s2 <= steps; s2++) {
        for (let i2 = 0; i2 < vlen; i2++) {
          const vert = bevelEnabled ? scalePt2(vertices[i2], verticesMovements[i2], bs) : vertices[i2];
          if (!extrudeByPath) {
            v5(vert.x, vert.y, depth / steps * s2);
          } else {
            normal.copy(splineTube.normals[s2]).multiplyScalar(vert.x);
            binormal.copy(splineTube.binormals[s2]).multiplyScalar(vert.y);
            position2.copy(extrudePts[s2]).add(normal).add(binormal);
            v5(position2.x, position2.y, position2.z);
          }
        }
      }
      for (let b2 = bevelSegments - 1; b2 >= 0; b2--) {
        const t2 = b2 / bevelSegments;
        const z2 = bevelThickness * Math.cos(t2 * Math.PI / 2);
        const bs2 = bevelSize * Math.sin(t2 * Math.PI / 2) + bevelOffset;
        for (let i2 = 0, il = contour.length; i2 < il; i2++) {
          const vert = scalePt2(contour[i2], contourMovements[i2], bs2);
          v5(vert.x, vert.y, depth + z2);
        }
        for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
          const ahole = holes[h2];
          oneHoleMovements = holesMovements[h2];
          for (let i2 = 0, il = ahole.length; i2 < il; i2++) {
            const vert = scalePt2(ahole[i2], oneHoleMovements[i2], bs2);
            if (!extrudeByPath) {
              v5(vert.x, vert.y, depth + z2);
            } else {
              v5(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z2);
            }
          }
        }
      }
      buildLidFaces();
      buildSideFaces();
      function buildLidFaces() {
        const start = verticesArray.length / 3;
        if (bevelEnabled) {
          let layer = 0;
          let offset = vlen * layer;
          for (let i2 = 0; i2 < flen; i2++) {
            const face = faces[i2];
            f3(face[2] + offset, face[1] + offset, face[0] + offset);
          }
          layer = steps + bevelSegments * 2;
          offset = vlen * layer;
          for (let i2 = 0; i2 < flen; i2++) {
            const face = faces[i2];
            f3(face[0] + offset, face[1] + offset, face[2] + offset);
          }
        } else {
          for (let i2 = 0; i2 < flen; i2++) {
            const face = faces[i2];
            f3(face[2], face[1], face[0]);
          }
          for (let i2 = 0; i2 < flen; i2++) {
            const face = faces[i2];
            f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
          }
        }
        scope.addGroup(start, verticesArray.length / 3 - start, 0);
      }
      function buildSideFaces() {
        const start = verticesArray.length / 3;
        let layeroffset = 0;
        sidewalls(contour, layeroffset);
        layeroffset += contour.length;
        for (let h2 = 0, hl = holes.length; h2 < hl; h2++) {
          const ahole = holes[h2];
          sidewalls(ahole, layeroffset);
          layeroffset += ahole.length;
        }
        scope.addGroup(start, verticesArray.length / 3 - start, 1);
      }
      function sidewalls(contour2, layeroffset) {
        let i2 = contour2.length;
        while (--i2 >= 0) {
          const j2 = i2;
          let k2 = i2 - 1;
          if (k2 < 0) k2 = contour2.length - 1;
          for (let s2 = 0, sl = steps + bevelSegments * 2; s2 < sl; s2++) {
            const slen1 = vlen * s2;
            const slen2 = vlen * (s2 + 1);
            const a3 = layeroffset + j2 + slen1, b2 = layeroffset + k2 + slen1, c2 = layeroffset + k2 + slen2, d2 = layeroffset + j2 + slen2;
            f4(a3, b2, c2, d2);
          }
        }
      }
      function v5(x, y2, z2) {
        placeholder.push(x);
        placeholder.push(y2);
        placeholder.push(z2);
      }
      function f3(a3, b2, c2) {
        addVertex(a3);
        addVertex(b2);
        addVertex(c2);
        const nextIndex = verticesArray.length / 3;
        const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
        addUV(uvs[0]);
        addUV(uvs[1]);
        addUV(uvs[2]);
      }
      function f4(a3, b2, c2, d2) {
        addVertex(a3);
        addVertex(b2);
        addVertex(d2);
        addVertex(b2);
        addVertex(c2);
        addVertex(d2);
        const nextIndex = verticesArray.length / 3;
        const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
        addUV(uvs[0]);
        addUV(uvs[1]);
        addUV(uvs[3]);
        addUV(uvs[1]);
        addUV(uvs[2]);
        addUV(uvs[3]);
      }
      function addVertex(index) {
        verticesArray.push(placeholder[index * 3 + 0]);
        verticesArray.push(placeholder[index * 3 + 1]);
        verticesArray.push(placeholder[index * 3 + 2]);
      }
      function addUV(vector2) {
        uvArray.push(vector2.x);
        uvArray.push(vector2.y);
      }
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    const shapes = this.parameters.shapes;
    const options = this.parameters.options;
    return toJSON$1(shapes, options, data);
  }
  static fromJSON(data, shapes) {
    const geometryShapes = [];
    for (let j2 = 0, jl = data.shapes.length; j2 < jl; j2++) {
      const shape = shapes[data.shapes[j2]];
      geometryShapes.push(shape);
    }
    const extrudePath = data.options.extrudePath;
    if (extrudePath !== void 0) {
      data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
    }
    return new ExtrudeGeometry(geometryShapes, data.options);
  }
}
const WorldUVGenerator = {
  generateTopUV: function(geometry, vertices, indexA, indexB, indexC) {
    const a_x = vertices[indexA * 3];
    const a_y = vertices[indexA * 3 + 1];
    const b_x = vertices[indexB * 3];
    const b_y = vertices[indexB * 3 + 1];
    const c_x = vertices[indexC * 3];
    const c_y = vertices[indexC * 3 + 1];
    return [
      new Vector2(a_x, a_y),
      new Vector2(b_x, b_y),
      new Vector2(c_x, c_y)
    ];
  },
  generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) {
    const a_x = vertices[indexA * 3];
    const a_y = vertices[indexA * 3 + 1];
    const a_z = vertices[indexA * 3 + 2];
    const b_x = vertices[indexB * 3];
    const b_y = vertices[indexB * 3 + 1];
    const b_z = vertices[indexB * 3 + 2];
    const c_x = vertices[indexC * 3];
    const c_y = vertices[indexC * 3 + 1];
    const c_z = vertices[indexC * 3 + 2];
    const d_x = vertices[indexD * 3];
    const d_y = vertices[indexD * 3 + 1];
    const d_z = vertices[indexD * 3 + 2];
    if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
      return [
        new Vector2(a_x, 1 - a_z),
        new Vector2(b_x, 1 - b_z),
        new Vector2(c_x, 1 - c_z),
        new Vector2(d_x, 1 - d_z)
      ];
    } else {
      return [
        new Vector2(a_y, 1 - a_z),
        new Vector2(b_y, 1 - b_z),
        new Vector2(c_y, 1 - c_z),
        new Vector2(d_y, 1 - d_z)
      ];
    }
  }
};
function toJSON$1(shapes, options, data) {
  data.shapes = [];
  if (Array.isArray(shapes)) {
    for (let i2 = 0, l2 = shapes.length; i2 < l2; i2++) {
      const shape = shapes[i2];
      data.shapes.push(shape.uuid);
    }
  } else {
    data.shapes.push(shapes.uuid);
  }
  data.options = Object.assign({}, options);
  if (options.extrudePath !== void 0) data.options.extrudePath = options.extrudePath.toJSON();
  return data;
}
class IcosahedronGeometry extends PolyhedronGeometry {
  constructor(radius = 1, detail = 0) {
    const t2 = (1 + Math.sqrt(5)) / 2;
    const vertices = [
      -1,
      t2,
      0,
      1,
      t2,
      0,
      -1,
      -t2,
      0,
      1,
      -t2,
      0,
      0,
      -1,
      t2,
      0,
      1,
      t2,
      0,
      -1,
      -t2,
      0,
      1,
      -t2,
      t2,
      0,
      -1,
      t2,
      0,
      1,
      -t2,
      0,
      -1,
      -t2,
      0,
      1
    ];
    const indices = [
      0,
      11,
      5,
      0,
      5,
      1,
      0,
      1,
      7,
      0,
      7,
      10,
      0,
      10,
      11,
      1,
      5,
      9,
      5,
      11,
      4,
      11,
      10,
      2,
      10,
      7,
      6,
      7,
      1,
      8,
      3,
      9,
      4,
      3,
      4,
      2,
      3,
      2,
      6,
      3,
      6,
      8,
      3,
      8,
      9,
      4,
      9,
      5,
      2,
      4,
      11,
      6,
      2,
      10,
      8,
      6,
      7,
      9,
      8,
      1
    ];
    super(vertices, indices, radius, detail);
    this.type = "IcosahedronGeometry";
    this.parameters = {
      radius,
      detail
    };
  }
  static fromJSON(data) {
    return new IcosahedronGeometry(data.radius, data.detail);
  }
}
class OctahedronGeometry extends PolyhedronGeometry {
  constructor(radius = 1, detail = 0) {
    const vertices = [
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1
    ];
    const indices = [
      0,
      2,
      4,
      0,
      4,
      3,
      0,
      3,
      5,
      0,
      5,
      2,
      1,
      2,
      5,
      1,
      5,
      3,
      1,
      3,
      4,
      1,
      4,
      2
    ];
    super(vertices, indices, radius, detail);
    this.type = "OctahedronGeometry";
    this.parameters = {
      radius,
      detail
    };
  }
  static fromJSON(data) {
    return new OctahedronGeometry(data.radius, data.detail);
  }
}
class PlaneGeometry extends BufferGeometry {
  constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
    super();
    this.type = "PlaneGeometry";
    this.parameters = {
      width,
      height,
      widthSegments,
      heightSegments
    };
    const width_half = width / 2;
    const height_half = height / 2;
    const gridX = Math.floor(widthSegments);
    const gridY = Math.floor(heightSegments);
    const gridX1 = gridX + 1;
    const gridY1 = gridY + 1;
    const segment_width = width / gridX;
    const segment_height = height / gridY;
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    for (let iy = 0; iy < gridY1; iy++) {
      const y2 = iy * segment_height - height_half;
      for (let ix = 0; ix < gridX1; ix++) {
        const x = ix * segment_width - width_half;
        vertices.push(x, -y2, 0);
        normals.push(0, 0, 1);
        uvs.push(ix / gridX);
        uvs.push(1 - iy / gridY);
      }
    }
    for (let iy = 0; iy < gridY; iy++) {
      for (let ix = 0; ix < gridX; ix++) {
        const a3 = ix + gridX1 * iy;
        const b2 = ix + gridX1 * (iy + 1);
        const c2 = ix + 1 + gridX1 * (iy + 1);
        const d2 = ix + 1 + gridX1 * iy;
        indices.push(a3, b2, d2);
        indices.push(b2, c2, d2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  }
}
class RingGeometry extends BufferGeometry {
  constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
    super();
    this.type = "RingGeometry";
    this.parameters = {
      innerRadius,
      outerRadius,
      thetaSegments,
      phiSegments,
      thetaStart,
      thetaLength
    };
    thetaSegments = Math.max(3, thetaSegments);
    phiSegments = Math.max(1, phiSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let radius = innerRadius;
    const radiusStep = (outerRadius - innerRadius) / phiSegments;
    const vertex2 = new Vector3();
    const uv = new Vector2();
    for (let j2 = 0; j2 <= phiSegments; j2++) {
      for (let i2 = 0; i2 <= thetaSegments; i2++) {
        const segment = thetaStart + i2 / thetaSegments * thetaLength;
        vertex2.x = radius * Math.cos(segment);
        vertex2.y = radius * Math.sin(segment);
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        normals.push(0, 0, 1);
        uv.x = (vertex2.x / outerRadius + 1) / 2;
        uv.y = (vertex2.y / outerRadius + 1) / 2;
        uvs.push(uv.x, uv.y);
      }
      radius += radiusStep;
    }
    for (let j2 = 0; j2 < phiSegments; j2++) {
      const thetaSegmentLevel = j2 * (thetaSegments + 1);
      for (let i2 = 0; i2 < thetaSegments; i2++) {
        const segment = i2 + thetaSegmentLevel;
        const a3 = segment;
        const b2 = segment + thetaSegments + 1;
        const c2 = segment + thetaSegments + 2;
        const d2 = segment + 1;
        indices.push(a3, b2, d2);
        indices.push(b2, c2, d2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  }
}
class ShapeGeometry extends BufferGeometry {
  constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
    super();
    this.type = "ShapeGeometry";
    this.parameters = {
      shapes,
      curveSegments
    };
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let groupStart = 0;
    let groupCount = 0;
    if (Array.isArray(shapes) === false) {
      addShape(shapes);
    } else {
      for (let i2 = 0; i2 < shapes.length; i2++) {
        addShape(shapes[i2]);
        this.addGroup(groupStart, groupCount, i2);
        groupStart += groupCount;
        groupCount = 0;
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function addShape(shape) {
      const indexOffset = vertices.length / 3;
      const points = shape.extractPoints(curveSegments);
      let shapeVertices = points.shape;
      const shapeHoles = points.holes;
      if (ShapeUtils.isClockWise(shapeVertices) === false) {
        shapeVertices = shapeVertices.reverse();
      }
      for (let i2 = 0, l2 = shapeHoles.length; i2 < l2; i2++) {
        const shapeHole = shapeHoles[i2];
        if (ShapeUtils.isClockWise(shapeHole) === true) {
          shapeHoles[i2] = shapeHole.reverse();
        }
      }
      const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles);
      for (let i2 = 0, l2 = shapeHoles.length; i2 < l2; i2++) {
        const shapeHole = shapeHoles[i2];
        shapeVertices = shapeVertices.concat(shapeHole);
      }
      for (let i2 = 0, l2 = shapeVertices.length; i2 < l2; i2++) {
        const vertex2 = shapeVertices[i2];
        vertices.push(vertex2.x, vertex2.y, 0);
        normals.push(0, 0, 1);
        uvs.push(vertex2.x, vertex2.y);
      }
      for (let i2 = 0, l2 = faces.length; i2 < l2; i2++) {
        const face = faces[i2];
        const a3 = face[0] + indexOffset;
        const b2 = face[1] + indexOffset;
        const c2 = face[2] + indexOffset;
        indices.push(a3, b2, c2);
        groupCount += 3;
      }
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    const shapes = this.parameters.shapes;
    return toJSON(shapes, data);
  }
  static fromJSON(data, shapes) {
    const geometryShapes = [];
    for (let j2 = 0, jl = data.shapes.length; j2 < jl; j2++) {
      const shape = shapes[data.shapes[j2]];
      geometryShapes.push(shape);
    }
    return new ShapeGeometry(geometryShapes, data.curveSegments);
  }
}
function toJSON(shapes, data) {
  data.shapes = [];
  if (Array.isArray(shapes)) {
    for (let i2 = 0, l2 = shapes.length; i2 < l2; i2++) {
      const shape = shapes[i2];
      data.shapes.push(shape.uuid);
    }
  } else {
    data.shapes.push(shapes.uuid);
  }
  return data;
}
class SphereGeometry extends BufferGeometry {
  constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
    super();
    this.type = "SphereGeometry";
    this.parameters = {
      radius,
      widthSegments,
      heightSegments,
      phiStart,
      phiLength,
      thetaStart,
      thetaLength
    };
    widthSegments = Math.max(3, Math.floor(widthSegments));
    heightSegments = Math.max(2, Math.floor(heightSegments));
    const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
    let index = 0;
    const grid = [];
    const vertex2 = new Vector3();
    const normal = new Vector3();
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    for (let iy = 0; iy <= heightSegments; iy++) {
      const verticesRow = [];
      const v5 = iy / heightSegments;
      let uOffset = 0;
      if (iy === 0 && thetaStart === 0) {
        uOffset = 0.5 / widthSegments;
      } else if (iy === heightSegments && thetaEnd === Math.PI) {
        uOffset = -0.5 / widthSegments;
      }
      for (let ix = 0; ix <= widthSegments; ix++) {
        const u2 = ix / widthSegments;
        vertex2.x = -radius * Math.cos(phiStart + u2 * phiLength) * Math.sin(thetaStart + v5 * thetaLength);
        vertex2.y = radius * Math.cos(thetaStart + v5 * thetaLength);
        vertex2.z = radius * Math.sin(phiStart + u2 * phiLength) * Math.sin(thetaStart + v5 * thetaLength);
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        normal.copy(vertex2).normalize();
        normals.push(normal.x, normal.y, normal.z);
        uvs.push(u2 + uOffset, 1 - v5);
        verticesRow.push(index++);
      }
      grid.push(verticesRow);
    }
    for (let iy = 0; iy < heightSegments; iy++) {
      for (let ix = 0; ix < widthSegments; ix++) {
        const a3 = grid[iy][ix + 1];
        const b2 = grid[iy][ix];
        const c2 = grid[iy + 1][ix];
        const d2 = grid[iy + 1][ix + 1];
        if (iy !== 0 || thetaStart > 0) indices.push(a3, b2, d2);
        if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b2, c2, d2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  }
}
class TetrahedronGeometry extends PolyhedronGeometry {
  constructor(radius = 1, detail = 0) {
    const vertices = [
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      1,
      -1,
      -1
    ];
    const indices = [
      2,
      1,
      0,
      0,
      3,
      2,
      1,
      3,
      0,
      2,
      3,
      1
    ];
    super(vertices, indices, radius, detail);
    this.type = "TetrahedronGeometry";
    this.parameters = {
      radius,
      detail
    };
  }
  static fromJSON(data) {
    return new TetrahedronGeometry(data.radius, data.detail);
  }
}
class TorusGeometry extends BufferGeometry {
  constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) {
    super();
    this.type = "TorusGeometry";
    this.parameters = {
      radius,
      tube,
      radialSegments,
      tubularSegments,
      arc
    };
    radialSegments = Math.floor(radialSegments);
    tubularSegments = Math.floor(tubularSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    const center = new Vector3();
    const vertex2 = new Vector3();
    const normal = new Vector3();
    for (let j2 = 0; j2 <= radialSegments; j2++) {
      for (let i2 = 0; i2 <= tubularSegments; i2++) {
        const u2 = i2 / tubularSegments * arc;
        const v5 = j2 / radialSegments * Math.PI * 2;
        vertex2.x = (radius + tube * Math.cos(v5)) * Math.cos(u2);
        vertex2.y = (radius + tube * Math.cos(v5)) * Math.sin(u2);
        vertex2.z = tube * Math.sin(v5);
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        center.x = radius * Math.cos(u2);
        center.y = radius * Math.sin(u2);
        normal.subVectors(vertex2, center).normalize();
        normals.push(normal.x, normal.y, normal.z);
        uvs.push(i2 / tubularSegments);
        uvs.push(j2 / radialSegments);
      }
    }
    for (let j2 = 1; j2 <= radialSegments; j2++) {
      for (let i2 = 1; i2 <= tubularSegments; i2++) {
        const a3 = (tubularSegments + 1) * j2 + i2 - 1;
        const b2 = (tubularSegments + 1) * (j2 - 1) + i2 - 1;
        const c2 = (tubularSegments + 1) * (j2 - 1) + i2;
        const d2 = (tubularSegments + 1) * j2 + i2;
        indices.push(a3, b2, d2);
        indices.push(b2, c2, d2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  }
}
class TorusKnotGeometry extends BufferGeometry {
  constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p2 = 2, q3 = 3) {
    super();
    this.type = "TorusKnotGeometry";
    this.parameters = {
      radius,
      tube,
      tubularSegments,
      radialSegments,
      p: p2,
      q: q3
    };
    tubularSegments = Math.floor(tubularSegments);
    radialSegments = Math.floor(radialSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    const vertex2 = new Vector3();
    const normal = new Vector3();
    const P1 = new Vector3();
    const P2 = new Vector3();
    const B = new Vector3();
    const T3 = new Vector3();
    const N2 = new Vector3();
    for (let i2 = 0; i2 <= tubularSegments; ++i2) {
      const u2 = i2 / tubularSegments * p2 * Math.PI * 2;
      calculatePositionOnCurve(u2, p2, q3, radius, P1);
      calculatePositionOnCurve(u2 + 0.01, p2, q3, radius, P2);
      T3.subVectors(P2, P1);
      N2.addVectors(P2, P1);
      B.crossVectors(T3, N2);
      N2.crossVectors(B, T3);
      B.normalize();
      N2.normalize();
      for (let j2 = 0; j2 <= radialSegments; ++j2) {
        const v5 = j2 / radialSegments * Math.PI * 2;
        const cx = -tube * Math.cos(v5);
        const cy = tube * Math.sin(v5);
        vertex2.x = P1.x + (cx * N2.x + cy * B.x);
        vertex2.y = P1.y + (cx * N2.y + cy * B.y);
        vertex2.z = P1.z + (cx * N2.z + cy * B.z);
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
        normal.subVectors(vertex2, P1).normalize();
        normals.push(normal.x, normal.y, normal.z);
        uvs.push(i2 / tubularSegments);
        uvs.push(j2 / radialSegments);
      }
    }
    for (let j2 = 1; j2 <= tubularSegments; j2++) {
      for (let i2 = 1; i2 <= radialSegments; i2++) {
        const a3 = (radialSegments + 1) * (j2 - 1) + (i2 - 1);
        const b2 = (radialSegments + 1) * j2 + (i2 - 1);
        const c2 = (radialSegments + 1) * j2 + i2;
        const d2 = (radialSegments + 1) * (j2 - 1) + i2;
        indices.push(a3, b2, d2);
        indices.push(b2, c2, d2);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function calculatePositionOnCurve(u2, p3, q4, radius2, position) {
      const cu = Math.cos(u2);
      const su = Math.sin(u2);
      const quOverP = q4 / p3 * u2;
      const cs = Math.cos(quOverP);
      position.x = radius2 * (2 + cs) * 0.5 * cu;
      position.y = radius2 * (2 + cs) * su * 0.5;
      position.z = radius2 * Math.sin(quOverP) * 0.5;
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  }
}
class TubeGeometry extends BufferGeometry {
  constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
    super();
    this.type = "TubeGeometry";
    this.parameters = {
      path,
      tubularSegments,
      radius,
      radialSegments,
      closed
    };
    const frames = path.computeFrenetFrames(tubularSegments, closed);
    this.tangents = frames.tangents;
    this.normals = frames.normals;
    this.binormals = frames.binormals;
    const vertex2 = new Vector3();
    const normal = new Vector3();
    const uv = new Vector2();
    let P2 = new Vector3();
    const vertices = [];
    const normals = [];
    const uvs = [];
    const indices = [];
    generateBufferData();
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function generateBufferData() {
      for (let i2 = 0; i2 < tubularSegments; i2++) {
        generateSegment(i2);
      }
      generateSegment(closed === false ? tubularSegments : 0);
      generateUVs();
      generateIndices();
    }
    function generateSegment(i2) {
      P2 = path.getPointAt(i2 / tubularSegments, P2);
      const N2 = frames.normals[i2];
      const B = frames.binormals[i2];
      for (let j2 = 0; j2 <= radialSegments; j2++) {
        const v5 = j2 / radialSegments * Math.PI * 2;
        const sin = Math.sin(v5);
        const cos = -Math.cos(v5);
        normal.x = cos * N2.x + sin * B.x;
        normal.y = cos * N2.y + sin * B.y;
        normal.z = cos * N2.z + sin * B.z;
        normal.normalize();
        normals.push(normal.x, normal.y, normal.z);
        vertex2.x = P2.x + radius * normal.x;
        vertex2.y = P2.y + radius * normal.y;
        vertex2.z = P2.z + radius * normal.z;
        vertices.push(vertex2.x, vertex2.y, vertex2.z);
      }
    }
    function generateIndices() {
      for (let j2 = 1; j2 <= tubularSegments; j2++) {
        for (let i2 = 1; i2 <= radialSegments; i2++) {
          const a3 = (radialSegments + 1) * (j2 - 1) + (i2 - 1);
          const b2 = (radialSegments + 1) * j2 + (i2 - 1);
          const c2 = (radialSegments + 1) * j2 + i2;
          const d2 = (radialSegments + 1) * (j2 - 1) + i2;
          indices.push(a3, b2, d2);
          indices.push(b2, c2, d2);
        }
      }
    }
    function generateUVs() {
      for (let i2 = 0; i2 <= tubularSegments; i2++) {
        for (let j2 = 0; j2 <= radialSegments; j2++) {
          uv.x = i2 / tubularSegments;
          uv.y = j2 / radialSegments;
          uvs.push(uv.x, uv.y);
        }
      }
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.path = this.parameters.path.toJSON();
    return data;
  }
  static fromJSON(data) {
    return new TubeGeometry(
      new Curves[data.path.type]().fromJSON(data.path),
      data.tubularSegments,
      data.radius,
      data.radialSegments,
      data.closed
    );
  }
}
class WireframeGeometry extends BufferGeometry {
  constructor(geometry = null) {
    super();
    this.type = "WireframeGeometry";
    this.parameters = {
      geometry
    };
    if (geometry !== null) {
      const vertices = [];
      const edges = /* @__PURE__ */ new Set();
      const start = new Vector3();
      const end = new Vector3();
      if (geometry.index !== null) {
        const position = geometry.attributes.position;
        const indices = geometry.index;
        let groups = geometry.groups;
        if (groups.length === 0) {
          groups = [{ start: 0, count: indices.count, materialIndex: 0 }];
        }
        for (let o4 = 0, ol = groups.length; o4 < ol; ++o4) {
          const group = groups[o4];
          const groupStart = group.start;
          const groupCount = group.count;
          for (let i2 = groupStart, l2 = groupStart + groupCount; i2 < l2; i2 += 3) {
            for (let j2 = 0; j2 < 3; j2++) {
              const index1 = indices.getX(i2 + j2);
              const index2 = indices.getX(i2 + (j2 + 1) % 3);
              start.fromBufferAttribute(position, index1);
              end.fromBufferAttribute(position, index2);
              if (isUniqueEdge(start, end, edges) === true) {
                vertices.push(start.x, start.y, start.z);
                vertices.push(end.x, end.y, end.z);
              }
            }
          }
        }
      } else {
        const position = geometry.attributes.position;
        for (let i2 = 0, l2 = position.count / 3; i2 < l2; i2++) {
          for (let j2 = 0; j2 < 3; j2++) {
            const index1 = 3 * i2 + j2;
            const index2 = 3 * i2 + (j2 + 1) % 3;
            start.fromBufferAttribute(position, index1);
            end.fromBufferAttribute(position, index2);
            if (isUniqueEdge(start, end, edges) === true) {
              vertices.push(start.x, start.y, start.z);
              vertices.push(end.x, end.y, end.z);
            }
          }
        }
      }
      this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
}
function isUniqueEdge(start, end, edges) {
  const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`;
  if (edges.has(hash1) === true || edges.has(hash2) === true) {
    return false;
  } else {
    edges.add(hash1);
    edges.add(hash2);
    return true;
  }
}
var Geometries = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  BoxGeometry,
  CapsuleGeometry,
  CircleGeometry,
  ConeGeometry,
  CylinderGeometry,
  DodecahedronGeometry,
  EdgesGeometry,
  ExtrudeGeometry,
  IcosahedronGeometry,
  LatheGeometry,
  OctahedronGeometry,
  PlaneGeometry,
  PolyhedronGeometry,
  RingGeometry,
  ShapeGeometry,
  SphereGeometry,
  TetrahedronGeometry,
  TorusGeometry,
  TorusKnotGeometry,
  TubeGeometry,
  WireframeGeometry
});
class ShadowMaterial extends Material {
  constructor(parameters) {
    super();
    this.isShadowMaterial = true;
    this.type = "ShadowMaterial";
    this.color = new Color(0);
    this.transparent = true;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.fog = source.fog;
    return this;
  }
}
class RawShaderMaterial extends ShaderMaterial {
  constructor(parameters) {
    super(parameters);
    this.isRawShaderMaterial = true;
    this.type = "RawShaderMaterial";
  }
}
class MeshStandardMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshStandardMaterial = true;
    this.type = "MeshStandardMaterial";
    this.defines = { "STANDARD": "" };
    this.color = new Color(16777215);
    this.roughness = 1;
    this.metalness = 0;
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.emissive = new Color(0);
    this.emissiveIntensity = 1;
    this.emissiveMap = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.roughnessMap = null;
    this.metalnessMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler();
    this.envMapIntensity = 1;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.flatShading = false;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.defines = { "STANDARD": "" };
    this.color.copy(source.color);
    this.roughness = source.roughness;
    this.metalness = source.metalness;
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.roughnessMap = source.roughnessMap;
    this.metalnessMap = source.metalnessMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.envMapIntensity = source.envMapIntensity;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.flatShading = source.flatShading;
    this.fog = source.fog;
    return this;
  }
}
class MeshPhysicalMaterial extends MeshStandardMaterial {
  constructor(parameters) {
    super();
    this.isMeshPhysicalMaterial = true;
    this.defines = {
      "STANDARD": "",
      "PHYSICAL": ""
    };
    this.type = "MeshPhysicalMaterial";
    this.anisotropyRotation = 0;
    this.anisotropyMap = null;
    this.clearcoatMap = null;
    this.clearcoatRoughness = 0;
    this.clearcoatRoughnessMap = null;
    this.clearcoatNormalScale = new Vector2(1, 1);
    this.clearcoatNormalMap = null;
    this.ior = 1.5;
    Object.defineProperty(this, "reflectivity", {
      get: function() {
        return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
      },
      set: function(reflectivity) {
        this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
      }
    });
    this.iridescenceMap = null;
    this.iridescenceIOR = 1.3;
    this.iridescenceThicknessRange = [100, 400];
    this.iridescenceThicknessMap = null;
    this.sheenColor = new Color(0);
    this.sheenColorMap = null;
    this.sheenRoughness = 1;
    this.sheenRoughnessMap = null;
    this.transmissionMap = null;
    this.thickness = 0;
    this.thicknessMap = null;
    this.attenuationDistance = Infinity;
    this.attenuationColor = new Color(1, 1, 1);
    this.specularIntensity = 1;
    this.specularIntensityMap = null;
    this.specularColor = new Color(1, 1, 1);
    this.specularColorMap = null;
    this._anisotropy = 0;
    this._clearcoat = 0;
    this._dispersion = 0;
    this._iridescence = 0;
    this._sheen = 0;
    this._transmission = 0;
    this.setValues(parameters);
  }
  get anisotropy() {
    return this._anisotropy;
  }
  set anisotropy(value) {
    if (this._anisotropy > 0 !== value > 0) {
      this.version++;
    }
    this._anisotropy = value;
  }
  get clearcoat() {
    return this._clearcoat;
  }
  set clearcoat(value) {
    if (this._clearcoat > 0 !== value > 0) {
      this.version++;
    }
    this._clearcoat = value;
  }
  get iridescence() {
    return this._iridescence;
  }
  set iridescence(value) {
    if (this._iridescence > 0 !== value > 0) {
      this.version++;
    }
    this._iridescence = value;
  }
  get dispersion() {
    return this._dispersion;
  }
  set dispersion(value) {
    if (this._dispersion > 0 !== value > 0) {
      this.version++;
    }
    this._dispersion = value;
  }
  get sheen() {
    return this._sheen;
  }
  set sheen(value) {
    if (this._sheen > 0 !== value > 0) {
      this.version++;
    }
    this._sheen = value;
  }
  get transmission() {
    return this._transmission;
  }
  set transmission(value) {
    if (this._transmission > 0 !== value > 0) {
      this.version++;
    }
    this._transmission = value;
  }
  copy(source) {
    super.copy(source);
    this.defines = {
      "STANDARD": "",
      "PHYSICAL": ""
    };
    this.anisotropy = source.anisotropy;
    this.anisotropyRotation = source.anisotropyRotation;
    this.anisotropyMap = source.anisotropyMap;
    this.clearcoat = source.clearcoat;
    this.clearcoatMap = source.clearcoatMap;
    this.clearcoatRoughness = source.clearcoatRoughness;
    this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
    this.clearcoatNormalMap = source.clearcoatNormalMap;
    this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
    this.dispersion = source.dispersion;
    this.ior = source.ior;
    this.iridescence = source.iridescence;
    this.iridescenceMap = source.iridescenceMap;
    this.iridescenceIOR = source.iridescenceIOR;
    this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
    this.iridescenceThicknessMap = source.iridescenceThicknessMap;
    this.sheen = source.sheen;
    this.sheenColor.copy(source.sheenColor);
    this.sheenColorMap = source.sheenColorMap;
    this.sheenRoughness = source.sheenRoughness;
    this.sheenRoughnessMap = source.sheenRoughnessMap;
    this.transmission = source.transmission;
    this.transmissionMap = source.transmissionMap;
    this.thickness = source.thickness;
    this.thicknessMap = source.thicknessMap;
    this.attenuationDistance = source.attenuationDistance;
    this.attenuationColor.copy(source.attenuationColor);
    this.specularIntensity = source.specularIntensity;
    this.specularIntensityMap = source.specularIntensityMap;
    this.specularColor.copy(source.specularColor);
    this.specularColorMap = source.specularColorMap;
    return this;
  }
}
class MeshPhongMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshPhongMaterial = true;
    this.type = "MeshPhongMaterial";
    this.color = new Color(16777215);
    this.specular = new Color(1118481);
    this.shininess = 30;
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.emissive = new Color(0);
    this.emissiveIntensity = 1;
    this.emissiveMap = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.specularMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler();
    this.combine = MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.flatShading = false;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.specular.copy(source.specular);
    this.shininess = source.shininess;
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.specularMap = source.specularMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.combine = source.combine;
    this.reflectivity = source.reflectivity;
    this.refractionRatio = source.refractionRatio;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.flatShading = source.flatShading;
    this.fog = source.fog;
    return this;
  }
}
class MeshToonMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshToonMaterial = true;
    this.defines = { "TOON": "" };
    this.type = "MeshToonMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.gradientMap = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.emissive = new Color(0);
    this.emissiveIntensity = 1;
    this.emissiveMap = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.alphaMap = null;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.gradientMap = source.gradientMap;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.alphaMap = source.alphaMap;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.fog = source.fog;
    return this;
  }
}
class MeshNormalMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshNormalMaterial = true;
    this.type = "MeshNormalMaterial";
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.flatShading = false;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.flatShading = source.flatShading;
    return this;
  }
}
class MeshLambertMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshLambertMaterial = true;
    this.type = "MeshLambertMaterial";
    this.color = new Color(16777215);
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.emissive = new Color(0);
    this.emissiveIntensity = 1;
    this.emissiveMap = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.specularMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler();
    this.combine = MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.flatShading = false;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.specularMap = source.specularMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.combine = source.combine;
    this.reflectivity = source.reflectivity;
    this.refractionRatio = source.refractionRatio;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.flatShading = source.flatShading;
    this.fog = source.fog;
    return this;
  }
}
class MeshDepthMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshDepthMaterial = true;
    this.type = "MeshDepthMaterial";
    this.depthPacking = BasicDepthPacking;
    this.map = null;
    this.alphaMap = null;
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.depthPacking = source.depthPacking;
    this.map = source.map;
    this.alphaMap = source.alphaMap;
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    return this;
  }
}
class MeshDistanceMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshDistanceMaterial = true;
    this.type = "MeshDistanceMaterial";
    this.map = null;
    this.alphaMap = null;
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.map = source.map;
    this.alphaMap = source.alphaMap;
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    return this;
  }
}
class MeshMatcapMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshMatcapMaterial = true;
    this.defines = { "MATCAP": "" };
    this.type = "MeshMatcapMaterial";
    this.color = new Color(16777215);
    this.matcap = null;
    this.map = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.alphaMap = null;
    this.flatShading = false;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.defines = { "MATCAP": "" };
    this.color.copy(source.color);
    this.matcap = source.matcap;
    this.map = source.map;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.alphaMap = source.alphaMap;
    this.flatShading = source.flatShading;
    this.fog = source.fog;
    return this;
  }
}
class LineDashedMaterial extends LineBasicMaterial {
  constructor(parameters) {
    super();
    this.isLineDashedMaterial = true;
    this.type = "LineDashedMaterial";
    this.scale = 1;
    this.dashSize = 3;
    this.gapSize = 1;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.scale = source.scale;
    this.dashSize = source.dashSize;
    this.gapSize = source.gapSize;
    return this;
  }
}
function convertArray(array, type, forceClone) {
  if (!array || // let 'undefined' and 'null' pass
  !forceClone && array.constructor === type) return array;
  if (typeof type.BYTES_PER_ELEMENT === "number") {
    return new type(array);
  }
  return Array.prototype.slice.call(array);
}
function isTypedArray(object) {
  return ArrayBuffer.isView(object) && !(object instanceof DataView);
}
function getKeyframeOrder(times) {
  function compareTime(i2, j2) {
    return times[i2] - times[j2];
  }
  const n2 = times.length;
  const result = new Array(n2);
  for (let i2 = 0; i2 !== n2; ++i2) result[i2] = i2;
  result.sort(compareTime);
  return result;
}
function sortedArray(values, stride, order) {
  const nValues = values.length;
  const result = new values.constructor(nValues);
  for (let i2 = 0, dstOffset = 0; dstOffset !== nValues; ++i2) {
    const srcOffset = order[i2] * stride;
    for (let j2 = 0; j2 !== stride; ++j2) {
      result[dstOffset++] = values[srcOffset + j2];
    }
  }
  return result;
}
function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  let i2 = 1, key = jsonKeys[0];
  while (key !== void 0 && key[valuePropertyName] === void 0) {
    key = jsonKeys[i2++];
  }
  if (key === void 0) return;
  let value = key[valuePropertyName];
  if (value === void 0) return;
  if (Array.isArray(value)) {
    do {
      value = key[valuePropertyName];
      if (value !== void 0) {
        times.push(key.time);
        values.push.apply(values, value);
      }
      key = jsonKeys[i2++];
    } while (key !== void 0);
  } else if (value.toArray !== void 0) {
    do {
      value = key[valuePropertyName];
      if (value !== void 0) {
        times.push(key.time);
        value.toArray(values, values.length);
      }
      key = jsonKeys[i2++];
    } while (key !== void 0);
  } else {
    do {
      value = key[valuePropertyName];
      if (value !== void 0) {
        times.push(key.time);
        values.push(value);
      }
      key = jsonKeys[i2++];
    } while (key !== void 0);
  }
}
function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  const clip = sourceClip.clone();
  clip.name = name;
  const tracks = [];
  for (let i2 = 0; i2 < clip.tracks.length; ++i2) {
    const track = clip.tracks[i2];
    const valueSize = track.getValueSize();
    const times = [];
    const values = [];
    for (let j2 = 0; j2 < track.times.length; ++j2) {
      const frame = track.times[j2] * fps;
      if (frame < startFrame || frame >= endFrame) continue;
      times.push(track.times[j2]);
      for (let k2 = 0; k2 < valueSize; ++k2) {
        values.push(track.values[j2 * valueSize + k2]);
      }
    }
    if (times.length === 0) continue;
    track.times = convertArray(times, track.times.constructor);
    track.values = convertArray(values, track.values.constructor);
    tracks.push(track);
  }
  clip.tracks = tracks;
  let minStartTime = Infinity;
  for (let i2 = 0; i2 < clip.tracks.length; ++i2) {
    if (minStartTime > clip.tracks[i2].times[0]) {
      minStartTime = clip.tracks[i2].times[0];
    }
  }
  for (let i2 = 0; i2 < clip.tracks.length; ++i2) {
    clip.tracks[i2].shift(-1 * minStartTime);
  }
  clip.resetDuration();
  return clip;
}
function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  if (fps <= 0) fps = 30;
  const numTracks = referenceClip.tracks.length;
  const referenceTime = referenceFrame / fps;
  for (let i2 = 0; i2 < numTracks; ++i2) {
    const referenceTrack = referenceClip.tracks[i2];
    const referenceTrackType = referenceTrack.ValueTypeName;
    if (referenceTrackType === "bool" || referenceTrackType === "string") continue;
    const targetTrack = targetClip.tracks.find(function(track) {
      return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
    });
    if (targetTrack === void 0) continue;
    let referenceOffset = 0;
    const referenceValueSize = referenceTrack.getValueSize();
    if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
      referenceOffset = referenceValueSize / 3;
    }
    let targetOffset = 0;
    const targetValueSize = targetTrack.getValueSize();
    if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
      targetOffset = targetValueSize / 3;
    }
    const lastIndex = referenceTrack.times.length - 1;
    let referenceValue;
    if (referenceTime <= referenceTrack.times[0]) {
      const startIndex = referenceOffset;
      const endIndex = referenceValueSize - referenceOffset;
      referenceValue = referenceTrack.values.slice(startIndex, endIndex);
    } else if (referenceTime >= referenceTrack.times[lastIndex]) {
      const startIndex = lastIndex * referenceValueSize + referenceOffset;
      const endIndex = startIndex + referenceValueSize - referenceOffset;
      referenceValue = referenceTrack.values.slice(startIndex, endIndex);
    } else {
      const interpolant = referenceTrack.createInterpolant();
      const startIndex = referenceOffset;
      const endIndex = referenceValueSize - referenceOffset;
      interpolant.evaluate(referenceTime);
      referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex);
    }
    if (referenceTrackType === "quaternion") {
      const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
      referenceQuat.toArray(referenceValue);
    }
    const numTimes = targetTrack.times.length;
    for (let j2 = 0; j2 < numTimes; ++j2) {
      const valueStart = j2 * targetValueSize + targetOffset;
      if (referenceTrackType === "quaternion") {
        Quaternion.multiplyQuaternionsFlat(
          targetTrack.values,
          valueStart,
          referenceValue,
          0,
          targetTrack.values,
          valueStart
        );
      } else {
        const valueEnd = targetValueSize - targetOffset * 2;
        for (let k2 = 0; k2 < valueEnd; ++k2) {
          targetTrack.values[valueStart + k2] -= referenceValue[k2];
        }
      }
    }
  }
  targetClip.blendMode = AdditiveAnimationBlendMode;
  return targetClip;
}
const AnimationUtils = {
  convertArray,
  isTypedArray,
  getKeyframeOrder,
  sortedArray,
  flattenJSON,
  subclip,
  makeClipAdditive
};
class Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    this.parameterPositions = parameterPositions;
    this._cachedIndex = 0;
    this.resultBuffer = resultBuffer !== void 0 ? resultBuffer : new sampleValues.constructor(sampleSize);
    this.sampleValues = sampleValues;
    this.valueSize = sampleSize;
    this.settings = null;
    this.DefaultSettings_ = {};
  }
  evaluate(t2) {
    const pp = this.parameterPositions;
    let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1];
    validate_interval: {
      seek: {
        let right;
        linear_scan: {
          forward_scan: if (!(t2 < t1)) {
            for (let giveUpAt = i1 + 2; ; ) {
              if (t1 === void 0) {
                if (t2 < t0) break forward_scan;
                i1 = pp.length;
                this._cachedIndex = i1;
                return this.copySampleValue_(i1 - 1);
              }
              if (i1 === giveUpAt) break;
              t0 = t1;
              t1 = pp[++i1];
              if (t2 < t1) {
                break seek;
              }
            }
            right = pp.length;
            break linear_scan;
          }
          if (!(t2 >= t0)) {
            const t1global = pp[1];
            if (t2 < t1global) {
              i1 = 2;
              t0 = t1global;
            }
            for (let giveUpAt = i1 - 2; ; ) {
              if (t0 === void 0) {
                this._cachedIndex = 0;
                return this.copySampleValue_(0);
              }
              if (i1 === giveUpAt) break;
              t1 = t0;
              t0 = pp[--i1 - 1];
              if (t2 >= t0) {
                break seek;
              }
            }
            right = i1;
            i1 = 0;
            break linear_scan;
          }
          break validate_interval;
        }
        while (i1 < right) {
          const mid = i1 + right >>> 1;
          if (t2 < pp[mid]) {
            right = mid;
          } else {
            i1 = mid + 1;
          }
        }
        t1 = pp[i1];
        t0 = pp[i1 - 1];
        if (t0 === void 0) {
          this._cachedIndex = 0;
          return this.copySampleValue_(0);
        }
        if (t1 === void 0) {
          i1 = pp.length;
          this._cachedIndex = i1;
          return this.copySampleValue_(i1 - 1);
        }
      }
      this._cachedIndex = i1;
      this.intervalChanged_(i1, t0, t1);
    }
    return this.interpolate_(i1, t0, t2, t1);
  }
  getSettings_() {
    return this.settings || this.DefaultSettings_;
  }
  copySampleValue_(index) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride;
    for (let i2 = 0; i2 !== stride; ++i2) {
      result[i2] = values[offset + i2];
    }
    return result;
  }
  // Template methods for derived classes:
  interpolate_() {
    throw new Error("call to abstract method");
  }
  intervalChanged_() {
  }
}
class CubicInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
    this._weightPrev = -0;
    this._offsetPrev = -0;
    this._weightNext = -0;
    this._offsetNext = -0;
    this.DefaultSettings_ = {
      endingStart: ZeroCurvatureEnding,
      endingEnd: ZeroCurvatureEnding
    };
  }
  intervalChanged_(i1, t0, t1) {
    const pp = this.parameterPositions;
    let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext];
    if (tPrev === void 0) {
      switch (this.getSettings_().endingStart) {
        case ZeroSlopeEnding:
          iPrev = i1;
          tPrev = 2 * t0 - t1;
          break;
        case WrapAroundEnding:
          iPrev = pp.length - 2;
          tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
          break;
        default:
          iPrev = i1;
          tPrev = t1;
      }
    }
    if (tNext === void 0) {
      switch (this.getSettings_().endingEnd) {
        case ZeroSlopeEnding:
          iNext = i1;
          tNext = 2 * t1 - t0;
          break;
        case WrapAroundEnding:
          iNext = 1;
          tNext = t1 + pp[1] - pp[0];
          break;
        default:
          iNext = i1 - 1;
          tNext = t0;
      }
    }
    const halfDt = (t1 - t0) * 0.5, stride = this.valueSize;
    this._weightPrev = halfDt / (t0 - tPrev);
    this._weightNext = halfDt / (tNext - t1);
    this._offsetPrev = iPrev * stride;
    this._offsetNext = iNext * stride;
  }
  interpolate_(i1, t0, t2, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p2 = (t2 - t0) / (t1 - t0), pp = p2 * p2, ppp = pp * p2;
    const sP = -wP * ppp + 2 * wP * pp - wP * p2;
    const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p2 + 1;
    const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p2;
    const sN = wN * ppp - wN * pp;
    for (let i2 = 0; i2 !== stride; ++i2) {
      result[i2] = sP * values[oP + i2] + s0 * values[o0 + i2] + s1 * values[o1 + i2] + sN * values[oN + i2];
    }
    return result;
  }
}
class LinearInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1, t0, t2, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t2 - t0) / (t1 - t0), weight0 = 1 - weight1;
    for (let i2 = 0; i2 !== stride; ++i2) {
      result[i2] = values[offset0 + i2] * weight0 + values[offset1 + i2] * weight1;
    }
    return result;
  }
}
class DiscreteInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1) {
    return this.copySampleValue_(i1 - 1);
  }
}
class KeyframeTrack {
  constructor(name, times, values, interpolation) {
    if (name === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined");
    if (times === void 0 || times.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name);
    this.name = name;
    this.times = convertArray(times, this.TimeBufferType);
    this.values = convertArray(values, this.ValueBufferType);
    this.setInterpolation(interpolation || this.DefaultInterpolation);
  }
  // Serialization (in static context, because of constructor invocation
  // and automatic invocation of .toJSON):
  static toJSON(track) {
    const trackType = track.constructor;
    let json3;
    if (trackType.toJSON !== this.toJSON) {
      json3 = trackType.toJSON(track);
    } else {
      json3 = {
        "name": track.name,
        "times": convertArray(track.times, Array),
        "values": convertArray(track.values, Array)
      };
      const interpolation = track.getInterpolation();
      if (interpolation !== track.DefaultInterpolation) {
        json3.interpolation = interpolation;
      }
    }
    json3.type = track.ValueTypeName;
    return json3;
  }
  InterpolantFactoryMethodDiscrete(result) {
    return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  InterpolantFactoryMethodLinear(result) {
    return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  InterpolantFactoryMethodSmooth(result) {
    return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  setInterpolation(interpolation) {
    let factoryMethod;
    switch (interpolation) {
      case InterpolateDiscrete:
        factoryMethod = this.InterpolantFactoryMethodDiscrete;
        break;
      case InterpolateLinear:
        factoryMethod = this.InterpolantFactoryMethodLinear;
        break;
      case InterpolateSmooth:
        factoryMethod = this.InterpolantFactoryMethodSmooth;
        break;
    }
    if (factoryMethod === void 0) {
      const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
      if (this.createInterpolant === void 0) {
        if (interpolation !== this.DefaultInterpolation) {
          this.setInterpolation(this.DefaultInterpolation);
        } else {
          throw new Error(message);
        }
      }
      console.warn("THREE.KeyframeTrack:", message);
      return this;
    }
    this.createInterpolant = factoryMethod;
    return this;
  }
  getInterpolation() {
    switch (this.createInterpolant) {
      case this.InterpolantFactoryMethodDiscrete:
        return InterpolateDiscrete;
      case this.InterpolantFactoryMethodLinear:
        return InterpolateLinear;
      case this.InterpolantFactoryMethodSmooth:
        return InterpolateSmooth;
    }
  }
  getValueSize() {
    return this.values.length / this.times.length;
  }
  // move all keyframes either forwards or backwards in time
  shift(timeOffset) {
    if (timeOffset !== 0) {
      const times = this.times;
      for (let i2 = 0, n2 = times.length; i2 !== n2; ++i2) {
        times[i2] += timeOffset;
      }
    }
    return this;
  }
  // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  scale(timeScale) {
    if (timeScale !== 1) {
      const times = this.times;
      for (let i2 = 0, n2 = times.length; i2 !== n2; ++i2) {
        times[i2] *= timeScale;
      }
    }
    return this;
  }
  // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  trim(startTime, endTime) {
    const times = this.times, nKeys = times.length;
    let from = 0, to = nKeys - 1;
    while (from !== nKeys && times[from] < startTime) {
      ++from;
    }
    while (to !== -1 && times[to] > endTime) {
      --to;
    }
    ++to;
    if (from !== 0 || to !== nKeys) {
      if (from >= to) {
        to = Math.max(to, 1);
        from = to - 1;
      }
      const stride = this.getValueSize();
      this.times = times.slice(from, to);
      this.values = this.values.slice(from * stride, to * stride);
    }
    return this;
  }
  // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  validate() {
    let valid = true;
    const valueSize = this.getValueSize();
    if (valueSize - Math.floor(valueSize) !== 0) {
      console.error("THREE.KeyframeTrack: Invalid value size in track.", this);
      valid = false;
    }
    const times = this.times, values = this.values, nKeys = times.length;
    if (nKeys === 0) {
      console.error("THREE.KeyframeTrack: Track is empty.", this);
      valid = false;
    }
    let prevTime = null;
    for (let i2 = 0; i2 !== nKeys; i2++) {
      const currTime = times[i2];
      if (typeof currTime === "number" && isNaN(currTime)) {
        console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i2, currTime);
        valid = false;
        break;
      }
      if (prevTime !== null && prevTime > currTime) {
        console.error("THREE.KeyframeTrack: Out of order keys.", this, i2, currTime, prevTime);
        valid = false;
        break;
      }
      prevTime = currTime;
    }
    if (values !== void 0) {
      if (isTypedArray(values)) {
        for (let i2 = 0, n2 = values.length; i2 !== n2; ++i2) {
          const value = values[i2];
          if (isNaN(value)) {
            console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i2, value);
            valid = false;
            break;
          }
        }
      }
    }
    return valid;
  }
  // removes equivalent sequential keys as common in morph target sequences
  // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  optimize() {
    const times = this.times.slice(), values = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1;
    let writeIndex = 1;
    for (let i2 = 1; i2 < lastIndex; ++i2) {
      let keep = false;
      const time = times[i2];
      const timeNext = times[i2 + 1];
      if (time !== timeNext && (i2 !== 1 || time !== times[0])) {
        if (!smoothInterpolation) {
          const offset = i2 * stride, offsetP = offset - stride, offsetN = offset + stride;
          for (let j2 = 0; j2 !== stride; ++j2) {
            const value = values[offset + j2];
            if (value !== values[offsetP + j2] || value !== values[offsetN + j2]) {
              keep = true;
              break;
            }
          }
        } else {
          keep = true;
        }
      }
      if (keep) {
        if (i2 !== writeIndex) {
          times[writeIndex] = times[i2];
          const readOffset = i2 * stride, writeOffset = writeIndex * stride;
          for (let j2 = 0; j2 !== stride; ++j2) {
            values[writeOffset + j2] = values[readOffset + j2];
          }
        }
        ++writeIndex;
      }
    }
    if (lastIndex > 0) {
      times[writeIndex] = times[lastIndex];
      for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j2 = 0; j2 !== stride; ++j2) {
        values[writeOffset + j2] = values[readOffset + j2];
      }
      ++writeIndex;
    }
    if (writeIndex !== times.length) {
      this.times = times.slice(0, writeIndex);
      this.values = values.slice(0, writeIndex * stride);
    } else {
      this.times = times;
      this.values = values;
    }
    return this;
  }
  clone() {
    const times = this.times.slice();
    const values = this.values.slice();
    const TypedKeyframeTrack = this.constructor;
    const track = new TypedKeyframeTrack(this.name, times, values);
    track.createInterpolant = this.createInterpolant;
    return track;
  }
}
KeyframeTrack.prototype.TimeBufferType = Float32Array;
KeyframeTrack.prototype.ValueBufferType = Float32Array;
KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
class BooleanKeyframeTrack extends KeyframeTrack {
  // No interpolation parameter because only InterpolateDiscrete is valid.
  constructor(name, times, values) {
    super(name, times, values);
  }
}
BooleanKeyframeTrack.prototype.ValueTypeName = "bool";
BooleanKeyframeTrack.prototype.ValueBufferType = Array;
BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0;
BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0;
class ColorKeyframeTrack extends KeyframeTrack {
}
ColorKeyframeTrack.prototype.ValueTypeName = "color";
class NumberKeyframeTrack extends KeyframeTrack {
}
NumberKeyframeTrack.prototype.ValueTypeName = "number";
class QuaternionLinearInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1, t0, t2, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t2 - t0) / (t1 - t0);
    let offset = i1 * stride;
    for (let end = offset + stride; offset !== end; offset += 4) {
      Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
    }
    return result;
  }
}
class QuaternionKeyframeTrack extends KeyframeTrack {
  InterpolantFactoryMethodLinear(result) {
    return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  }
}
QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion";
QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0;
class StringKeyframeTrack extends KeyframeTrack {
  // No interpolation parameter because only InterpolateDiscrete is valid.
  constructor(name, times, values) {
    super(name, times, values);
  }
}
StringKeyframeTrack.prototype.ValueTypeName = "string";
StringKeyframeTrack.prototype.ValueBufferType = Array;
StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0;
StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0;
class VectorKeyframeTrack extends KeyframeTrack {
}
VectorKeyframeTrack.prototype.ValueTypeName = "vector";
class AnimationClip {
  constructor(name = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode) {
    this.name = name;
    this.tracks = tracks;
    this.duration = duration;
    this.blendMode = blendMode;
    this.uuid = generateUUID();
    if (this.duration < 0) {
      this.resetDuration();
    }
  }
  static parse(json3) {
    const tracks = [], jsonTracks = json3.tracks, frameTime = 1 / (json3.fps || 1);
    for (let i2 = 0, n2 = jsonTracks.length; i2 !== n2; ++i2) {
      tracks.push(parseKeyframeTrack(jsonTracks[i2]).scale(frameTime));
    }
    const clip = new this(json3.name, json3.duration, tracks, json3.blendMode);
    clip.uuid = json3.uuid;
    return clip;
  }
  static toJSON(clip) {
    const tracks = [], clipTracks = clip.tracks;
    const json3 = {
      "name": clip.name,
      "duration": clip.duration,
      "tracks": tracks,
      "uuid": clip.uuid,
      "blendMode": clip.blendMode
    };
    for (let i2 = 0, n2 = clipTracks.length; i2 !== n2; ++i2) {
      tracks.push(KeyframeTrack.toJSON(clipTracks[i2]));
    }
    return json3;
  }
  static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
    const numMorphTargets = morphTargetSequence.length;
    const tracks = [];
    for (let i2 = 0; i2 < numMorphTargets; i2++) {
      let times = [];
      let values = [];
      times.push(
        (i2 + numMorphTargets - 1) % numMorphTargets,
        i2,
        (i2 + 1) % numMorphTargets
      );
      values.push(0, 1, 0);
      const order = getKeyframeOrder(times);
      times = sortedArray(times, 1, order);
      values = sortedArray(values, 1, order);
      if (!noLoop && times[0] === 0) {
        times.push(numMorphTargets);
        values.push(values[0]);
      }
      tracks.push(
        new NumberKeyframeTrack(
          ".morphTargetInfluences[" + morphTargetSequence[i2].name + "]",
          times,
          values
        ).scale(1 / fps)
      );
    }
    return new this(name, -1, tracks);
  }
  static findByName(objectOrClipArray, name) {
    let clipArray = objectOrClipArray;
    if (!Array.isArray(objectOrClipArray)) {
      const o4 = objectOrClipArray;
      clipArray = o4.geometry && o4.geometry.animations || o4.animations;
    }
    for (let i2 = 0; i2 < clipArray.length; i2++) {
      if (clipArray[i2].name === name) {
        return clipArray[i2];
      }
    }
    return null;
  }
  static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
    const animationToMorphTargets = {};
    const pattern2 = /^([\w-]*?)([\d]+)$/;
    for (let i2 = 0, il = morphTargets.length; i2 < il; i2++) {
      const morphTarget = morphTargets[i2];
      const parts = morphTarget.name.match(pattern2);
      if (parts && parts.length > 1) {
        const name = parts[1];
        let animationMorphTargets = animationToMorphTargets[name];
        if (!animationMorphTargets) {
          animationToMorphTargets[name] = animationMorphTargets = [];
        }
        animationMorphTargets.push(morphTarget);
      }
    }
    const clips = [];
    for (const name in animationToMorphTargets) {
      clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
    }
    return clips;
  }
  // parse the animation.hierarchy format
  static parseAnimation(animation, bones) {
    if (!animation) {
      console.error("THREE.AnimationClip: No animation in JSONLoader data.");
      return null;
    }
    const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) {
      if (animationKeys.length !== 0) {
        const times = [];
        const values = [];
        flattenJSON(animationKeys, times, values, propertyName);
        if (times.length !== 0) {
          destTracks.push(new trackType(trackName, times, values));
        }
      }
    };
    const tracks = [];
    const clipName = animation.name || "default";
    const fps = animation.fps || 30;
    const blendMode = animation.blendMode;
    let duration = animation.length || -1;
    const hierarchyTracks = animation.hierarchy || [];
    for (let h2 = 0; h2 < hierarchyTracks.length; h2++) {
      const animationKeys = hierarchyTracks[h2].keys;
      if (!animationKeys || animationKeys.length === 0) continue;
      if (animationKeys[0].morphTargets) {
        const morphTargetNames = {};
        let k2;
        for (k2 = 0; k2 < animationKeys.length; k2++) {
          if (animationKeys[k2].morphTargets) {
            for (let m2 = 0; m2 < animationKeys[k2].morphTargets.length; m2++) {
              morphTargetNames[animationKeys[k2].morphTargets[m2]] = -1;
            }
          }
        }
        for (const morphTargetName in morphTargetNames) {
          const times = [];
          const values = [];
          for (let m2 = 0; m2 !== animationKeys[k2].morphTargets.length; ++m2) {
            const animationKey = animationKeys[k2];
            times.push(animationKey.time);
            values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
          }
          tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values));
        }
        duration = morphTargetNames.length * fps;
      } else {
        const boneName = ".bones[" + bones[h2].name + "]";
        addNonemptyTrack(
          VectorKeyframeTrack,
          boneName + ".position",
          animationKeys,
          "pos",
          tracks
        );
        addNonemptyTrack(
          QuaternionKeyframeTrack,
          boneName + ".quaternion",
          animationKeys,
          "rot",
          tracks
        );
        addNonemptyTrack(
          VectorKeyframeTrack,
          boneName + ".scale",
          animationKeys,
          "scl",
          tracks
        );
      }
    }
    if (tracks.length === 0) {
      return null;
    }
    const clip = new this(clipName, duration, tracks, blendMode);
    return clip;
  }
  resetDuration() {
    const tracks = this.tracks;
    let duration = 0;
    for (let i2 = 0, n2 = tracks.length; i2 !== n2; ++i2) {
      const track = this.tracks[i2];
      duration = Math.max(duration, track.times[track.times.length - 1]);
    }
    this.duration = duration;
    return this;
  }
  trim() {
    for (let i2 = 0; i2 < this.tracks.length; i2++) {
      this.tracks[i2].trim(0, this.duration);
    }
    return this;
  }
  validate() {
    let valid = true;
    for (let i2 = 0; i2 < this.tracks.length; i2++) {
      valid = valid && this.tracks[i2].validate();
    }
    return valid;
  }
  optimize() {
    for (let i2 = 0; i2 < this.tracks.length; i2++) {
      this.tracks[i2].optimize();
    }
    return this;
  }
  clone() {
    const tracks = [];
    for (let i2 = 0; i2 < this.tracks.length; i2++) {
      tracks.push(this.tracks[i2].clone());
    }
    return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  }
  toJSON() {
    return this.constructor.toJSON(this);
  }
}
function getTrackTypeForValueTypeName(typeName) {
  switch (typeName.toLowerCase()) {
    case "scalar":
    case "double":
    case "float":
    case "number":
    case "integer":
      return NumberKeyframeTrack;
    case "vector":
    case "vector2":
    case "vector3":
    case "vector4":
      return VectorKeyframeTrack;
    case "color":
      return ColorKeyframeTrack;
    case "quaternion":
      return QuaternionKeyframeTrack;
    case "bool":
    case "boolean":
      return BooleanKeyframeTrack;
    case "string":
      return StringKeyframeTrack;
  }
  throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName);
}
function parseKeyframeTrack(json3) {
  if (json3.type === void 0) {
    throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");
  }
  const trackType = getTrackTypeForValueTypeName(json3.type);
  if (json3.times === void 0) {
    const times = [], values = [];
    flattenJSON(json3.keys, times, values, "value");
    json3.times = times;
    json3.values = values;
  }
  if (trackType.parse !== void 0) {
    return trackType.parse(json3);
  } else {
    return new trackType(json3.name, json3.times, json3.values, json3.interpolation);
  }
}
const Cache = {
  enabled: false,
  files: {},
  add: function(key, file) {
    if (this.enabled === false) return;
    this.files[key] = file;
  },
  get: function(key) {
    if (this.enabled === false) return;
    return this.files[key];
  },
  remove: function(key) {
    delete this.files[key];
  },
  clear: function() {
    this.files = {};
  }
};
class LoadingManager {
  constructor(onLoad, onProgress, onError) {
    const scope = this;
    let isLoading = false;
    let itemsLoaded = 0;
    let itemsTotal = 0;
    let urlModifier = void 0;
    const handlers = [];
    this.onStart = void 0;
    this.onLoad = onLoad;
    this.onProgress = onProgress;
    this.onError = onError;
    this.itemStart = function(url) {
      itemsTotal++;
      if (isLoading === false) {
        if (scope.onStart !== void 0) {
          scope.onStart(url, itemsLoaded, itemsTotal);
        }
      }
      isLoading = true;
    };
    this.itemEnd = function(url) {
      itemsLoaded++;
      if (scope.onProgress !== void 0) {
        scope.onProgress(url, itemsLoaded, itemsTotal);
      }
      if (itemsLoaded === itemsTotal) {
        isLoading = false;
        if (scope.onLoad !== void 0) {
          scope.onLoad();
        }
      }
    };
    this.itemError = function(url) {
      if (scope.onError !== void 0) {
        scope.onError(url);
      }
    };
    this.resolveURL = function(url) {
      if (urlModifier) {
        return urlModifier(url);
      }
      return url;
    };
    this.setURLModifier = function(transform) {
      urlModifier = transform;
      return this;
    };
    this.addHandler = function(regex, loader2) {
      handlers.push(regex, loader2);
      return this;
    };
    this.removeHandler = function(regex) {
      const index = handlers.indexOf(regex);
      if (index !== -1) {
        handlers.splice(index, 2);
      }
      return this;
    };
    this.getHandler = function(file) {
      for (let i2 = 0, l2 = handlers.length; i2 < l2; i2 += 2) {
        const regex = handlers[i2];
        const loader2 = handlers[i2 + 1];
        if (regex.global) regex.lastIndex = 0;
        if (regex.test(file)) {
          return loader2;
        }
      }
      return null;
    };
  }
}
const DefaultLoadingManager = /* @__PURE__ */ new LoadingManager();
class Loader {
  constructor(manager) {
    this.manager = manager !== void 0 ? manager : DefaultLoadingManager;
    this.crossOrigin = "anonymous";
    this.withCredentials = false;
    this.path = "";
    this.resourcePath = "";
    this.requestHeader = {};
  }
  load() {
  }
  loadAsync(url, onProgress) {
    const scope = this;
    return new Promise(function(resolve2, reject) {
      scope.load(url, resolve2, onProgress, reject);
    });
  }
  parse() {
  }
  setCrossOrigin(crossOrigin) {
    this.crossOrigin = crossOrigin;
    return this;
  }
  setWithCredentials(value) {
    this.withCredentials = value;
    return this;
  }
  setPath(path) {
    this.path = path;
    return this;
  }
  setResourcePath(resourcePath) {
    this.resourcePath = resourcePath;
    return this;
  }
  setRequestHeader(requestHeader) {
    this.requestHeader = requestHeader;
    return this;
  }
}
Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT";
const loading = {};
class HttpError extends Error {
  constructor(message, response) {
    super(message);
    this.response = response;
  }
}
class FileLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    if (url === void 0) url = "";
    if (this.path !== void 0) url = this.path + url;
    url = this.manager.resolveURL(url);
    const cached = Cache.get(url);
    if (cached !== void 0) {
      this.manager.itemStart(url);
      setTimeout(() => {
        if (onLoad) onLoad(cached);
        this.manager.itemEnd(url);
      }, 0);
      return cached;
    }
    if (loading[url] !== void 0) {
      loading[url].push({
        onLoad,
        onProgress,
        onError
      });
      return;
    }
    loading[url] = [];
    loading[url].push({
      onLoad,
      onProgress,
      onError
    });
    const req = new Request(url, {
      headers: new Headers(this.requestHeader),
      credentials: this.withCredentials ? "include" : "same-origin"
      // An abort controller could be added within a future PR
    });
    const mimeType = this.mimeType;
    const responseType = this.responseType;
    fetch(req).then((response) => {
      if (response.status === 200 || response.status === 0) {
        if (response.status === 0) {
          console.warn("THREE.FileLoader: HTTP Status 0 received.");
        }
        if (typeof ReadableStream === "undefined" || response.body === void 0 || response.body.getReader === void 0) {
          return response;
        }
        const callbacks = loading[url];
        const reader = response.body.getReader();
        const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length");
        const total = contentLength ? parseInt(contentLength) : 0;
        const lengthComputable = total !== 0;
        let loaded = 0;
        const stream = new ReadableStream({
          start(controller) {
            readData();
            function readData() {
              reader.read().then(({ done, value }) => {
                if (done) {
                  controller.close();
                } else {
                  loaded += value.byteLength;
                  const event = new ProgressEvent("progress", { lengthComputable, loaded, total });
                  for (let i2 = 0, il = callbacks.length; i2 < il; i2++) {
                    const callback = callbacks[i2];
                    if (callback.onProgress) callback.onProgress(event);
                  }
                  controller.enqueue(value);
                  readData();
                }
              }, (e2) => {
                controller.error(e2);
              });
            }
          }
        });
        return new Response(stream);
      } else {
        throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
      }
    }).then((response) => {
      switch (responseType) {
        case "arraybuffer":
          return response.arrayBuffer();
        case "blob":
          return response.blob();
        case "document":
          return response.text().then((text) => {
            const parser = new DOMParser();
            return parser.parseFromString(text, mimeType);
          });
        case "json":
          return response.json();
        default:
          if (mimeType === void 0) {
            return response.text();
          } else {
            const re2 = /charset="?([^;"\s]*)"?/i;
            const exec = re2.exec(mimeType);
            const label = exec && exec[1] ? exec[1].toLowerCase() : void 0;
            const decoder = new TextDecoder(label);
            return response.arrayBuffer().then((ab) => decoder.decode(ab));
          }
      }
    }).then((data) => {
      Cache.add(url, data);
      const callbacks = loading[url];
      delete loading[url];
      for (let i2 = 0, il = callbacks.length; i2 < il; i2++) {
        const callback = callbacks[i2];
        if (callback.onLoad) callback.onLoad(data);
      }
    }).catch((err) => {
      const callbacks = loading[url];
      if (callbacks === void 0) {
        this.manager.itemError(url);
        throw err;
      }
      delete loading[url];
      for (let i2 = 0, il = callbacks.length; i2 < il; i2++) {
        const callback = callbacks[i2];
        if (callback.onError) callback.onError(err);
      }
      this.manager.itemError(url);
    }).finally(() => {
      this.manager.itemEnd(url);
    });
    this.manager.itemStart(url);
  }
  setResponseType(value) {
    this.responseType = value;
    return this;
  }
  setMimeType(value) {
    this.mimeType = value;
    return this;
  }
}
class AnimationLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader2 = new FileLoader(this.manager);
    loader2.setPath(this.path);
    loader2.setRequestHeader(this.requestHeader);
    loader2.setWithCredentials(this.withCredentials);
    loader2.load(url, function(text) {
      try {
        onLoad(scope.parse(JSON.parse(text)));
      } catch (e2) {
        if (onError) {
          onError(e2);
        } else {
          console.error(e2);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  parse(json3) {
    const animations = [];
    for (let i2 = 0; i2 < json3.length; i2++) {
      const clip = AnimationClip.parse(json3[i2]);
      animations.push(clip);
    }
    return animations;
  }
}
class CompressedTextureLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const images = [];
    const texture = new CompressedTexture();
    const loader2 = new FileLoader(this.manager);
    loader2.setPath(this.path);
    loader2.setResponseType("arraybuffer");
    loader2.setRequestHeader(this.requestHeader);
    loader2.setWithCredentials(scope.withCredentials);
    let loaded = 0;
    function loadTexture(i2) {
      loader2.load(url[i2], function(buffer) {
        const texDatas = scope.parse(buffer, true);
        images[i2] = {
          width: texDatas.width,
          height: texDatas.height,
          format: texDatas.format,
          mipmaps: texDatas.mipmaps
        };
        loaded += 1;
        if (loaded === 6) {
          if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
          texture.image = images;
          texture.format = texDatas.format;
          texture.needsUpdate = true;
          if (onLoad) onLoad(texture);
        }
      }, onProgress, onError);
    }
    if (Array.isArray(url)) {
      for (let i2 = 0, il = url.length; i2 < il; ++i2) {
        loadTexture(i2);
      }
    } else {
      loader2.load(url, function(buffer) {
        const texDatas = scope.parse(buffer, true);
        if (texDatas.isCubemap) {
          const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
          for (let f2 = 0; f2 < faces; f2++) {
            images[f2] = { mipmaps: [] };
            for (let i2 = 0; i2 < texDatas.mipmapCount; i2++) {
              images[f2].mipmaps.push(texDatas.mipmaps[f2 * texDatas.mipmapCount + i2]);
              images[f2].format = texDatas.format;
              images[f2].width = texDatas.width;
              images[f2].height = texDatas.height;
            }
          }
          texture.image = images;
        } else {
          texture.image.width = texDatas.width;
          texture.image.height = texDatas.height;
          texture.mipmaps = texDatas.mipmaps;
        }
        if (texDatas.mipmapCount === 1) {
          texture.minFilter = LinearFilter;
        }
        texture.format = texDatas.format;
        texture.needsUpdate = true;
        if (onLoad) onLoad(texture);
      }, onProgress, onError);
    }
    return texture;
  }
}
class ImageLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    if (this.path !== void 0) url = this.path + url;
    url = this.manager.resolveURL(url);
    const scope = this;
    const cached = Cache.get(url);
    if (cached !== void 0) {
      scope.manager.itemStart(url);
      setTimeout(function() {
        if (onLoad) onLoad(cached);
        scope.manager.itemEnd(url);
      }, 0);
      return cached;
    }
    const image = createElementNS("img");
    function onImageLoad() {
      removeEventListeners();
      Cache.add(url, this);
      if (onLoad) onLoad(this);
      scope.manager.itemEnd(url);
    }
    function onImageError(event) {
      removeEventListeners();
      if (onError) onError(event);
      scope.manager.itemError(url);
      scope.manager.itemEnd(url);
    }
    function removeEventListeners() {
      image.removeEventListener("load", onImageLoad, false);
      image.removeEventListener("error", onImageError, false);
    }
    image.addEventListener("load", onImageLoad, false);
    image.addEventListener("error", onImageError, false);
    if (url.slice(0, 5) !== "data:") {
      if (this.crossOrigin !== void 0) image.crossOrigin = this.crossOrigin;
    }
    scope.manager.itemStart(url);
    image.src = url;
    return image;
  }
}
class CubeTextureLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(urls, onLoad, onProgress, onError) {
    const texture = new CubeTexture();
    texture.colorSpace = SRGBColorSpace;
    const loader2 = new ImageLoader(this.manager);
    loader2.setCrossOrigin(this.crossOrigin);
    loader2.setPath(this.path);
    let loaded = 0;
    function loadTexture(i2) {
      loader2.load(urls[i2], function(image) {
        texture.images[i2] = image;
        loaded++;
        if (loaded === 6) {
          texture.needsUpdate = true;
          if (onLoad) onLoad(texture);
        }
      }, void 0, onError);
    }
    for (let i2 = 0; i2 < urls.length; ++i2) {
      loadTexture(i2);
    }
    return texture;
  }
}
class DataTextureLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const texture = new DataTexture();
    const loader2 = new FileLoader(this.manager);
    loader2.setResponseType("arraybuffer");
    loader2.setRequestHeader(this.requestHeader);
    loader2.setPath(this.path);
    loader2.setWithCredentials(scope.withCredentials);
    loader2.load(url, function(buffer) {
      let texData;
      try {
        texData = scope.parse(buffer);
      } catch (error2) {
        if (onError !== void 0) {
          onError(error2);
        } else {
          console.error(error2);
          return;
        }
      }
      if (texData.image !== void 0) {
        texture.image = texData.image;
      } else if (texData.data !== void 0) {
        texture.image.width = texData.width;
        texture.image.height = texData.height;
        texture.image.data = texData.data;
      }
      texture.wrapS = texData.wrapS !== void 0 ? texData.wrapS : ClampToEdgeWrapping;
      texture.wrapT = texData.wrapT !== void 0 ? texData.wrapT : ClampToEdgeWrapping;
      texture.magFilter = texData.magFilter !== void 0 ? texData.magFilter : LinearFilter;
      texture.minFilter = texData.minFilter !== void 0 ? texData.minFilter : LinearFilter;
      texture.anisotropy = texData.anisotropy !== void 0 ? texData.anisotropy : 1;
      if (texData.colorSpace !== void 0) {
        texture.colorSpace = texData.colorSpace;
      }
      if (texData.flipY !== void 0) {
        texture.flipY = texData.flipY;
      }
      if (texData.format !== void 0) {
        texture.format = texData.format;
      }
      if (texData.type !== void 0) {
        texture.type = texData.type;
      }
      if (texData.mipmaps !== void 0) {
        texture.mipmaps = texData.mipmaps;
        texture.minFilter = LinearMipmapLinearFilter;
      }
      if (texData.mipmapCount === 1) {
        texture.minFilter = LinearFilter;
      }
      if (texData.generateMipmaps !== void 0) {
        texture.generateMipmaps = texData.generateMipmaps;
      }
      texture.needsUpdate = true;
      if (onLoad) onLoad(texture, texData);
    }, onProgress, onError);
    return texture;
  }
}
class TextureLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const texture = new Texture();
    const loader2 = new ImageLoader(this.manager);
    loader2.setCrossOrigin(this.crossOrigin);
    loader2.setPath(this.path);
    loader2.load(url, function(image) {
      texture.image = image;
      texture.needsUpdate = true;
      if (onLoad !== void 0) {
        onLoad(texture);
      }
    }, onProgress, onError);
    return texture;
  }
}
class Light extends Object3D {
  constructor(color, intensity = 1) {
    super();
    this.isLight = true;
    this.type = "Light";
    this.color = new Color(color);
    this.intensity = intensity;
  }
  dispose() {
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.color.copy(source.color);
    this.intensity = source.intensity;
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.object.color = this.color.getHex();
    data.object.intensity = this.intensity;
    if (this.groundColor !== void 0) data.object.groundColor = this.groundColor.getHex();
    if (this.distance !== void 0) data.object.distance = this.distance;
    if (this.angle !== void 0) data.object.angle = this.angle;
    if (this.decay !== void 0) data.object.decay = this.decay;
    if (this.penumbra !== void 0) data.object.penumbra = this.penumbra;
    if (this.shadow !== void 0) data.object.shadow = this.shadow.toJSON();
    if (this.target !== void 0) data.object.target = this.target.uuid;
    return data;
  }
}
class HemisphereLight extends Light {
  constructor(skyColor, groundColor, intensity) {
    super(skyColor, intensity);
    this.isHemisphereLight = true;
    this.type = "HemisphereLight";
    this.position.copy(Object3D.DEFAULT_UP);
    this.updateMatrix();
    this.groundColor = new Color(groundColor);
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.groundColor.copy(source.groundColor);
    return this;
  }
}
const _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4();
const _lightPositionWorld$1 = /* @__PURE__ */ new Vector3();
const _lookTarget$1 = /* @__PURE__ */ new Vector3();
class LightShadow {
  constructor(camera) {
    this.camera = camera;
    this.intensity = 1;
    this.bias = 0;
    this.normalBias = 0;
    this.radius = 1;
    this.blurSamples = 8;
    this.mapSize = new Vector2(512, 512);
    this.map = null;
    this.mapPass = null;
    this.matrix = new Matrix4();
    this.autoUpdate = true;
    this.needsUpdate = false;
    this._frustum = new Frustum();
    this._frameExtents = new Vector2(1, 1);
    this._viewportCount = 1;
    this._viewports = [
      new Vector4(0, 0, 1, 1)
    ];
  }
  getViewportCount() {
    return this._viewportCount;
  }
  getFrustum() {
    return this._frustum;
  }
  updateMatrices(light) {
    const shadowCamera = this.camera;
    const shadowMatrix = this.matrix;
    _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
    shadowCamera.position.copy(_lightPositionWorld$1);
    _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
    shadowCamera.lookAt(_lookTarget$1);
    shadowCamera.updateMatrixWorld();
    _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
    this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
    shadowMatrix.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      0.5,
      0.5,
      0,
      0,
      0,
      1
    );
    shadowMatrix.multiply(_projScreenMatrix$1);
  }
  getViewport(viewportIndex) {
    return this._viewports[viewportIndex];
  }
  getFrameExtents() {
    return this._frameExtents;
  }
  dispose() {
    if (this.map) {
      this.map.dispose();
    }
    if (this.mapPass) {
      this.mapPass.dispose();
    }
  }
  copy(source) {
    this.camera = source.camera.clone();
    this.intensity = source.intensity;
    this.bias = source.bias;
    this.radius = source.radius;
    this.mapSize.copy(source.mapSize);
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  toJSON() {
    const object = {};
    if (this.intensity !== 1) object.intensity = this.intensity;
    if (this.bias !== 0) object.bias = this.bias;
    if (this.normalBias !== 0) object.normalBias = this.normalBias;
    if (this.radius !== 1) object.radius = this.radius;
    if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
    object.camera = this.camera.toJSON(false).object;
    delete object.camera.matrix;
    return object;
  }
}
class SpotLightShadow extends LightShadow {
  constructor() {
    super(new PerspectiveCamera(50, 1, 0.5, 500));
    this.isSpotLightShadow = true;
    this.focus = 1;
  }
  updateMatrices(light) {
    const camera = this.camera;
    const fov2 = RAD2DEG * 2 * light.angle * this.focus;
    const aspect2 = this.mapSize.width / this.mapSize.height;
    const far = light.distance || camera.far;
    if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) {
      camera.fov = fov2;
      camera.aspect = aspect2;
      camera.far = far;
      camera.updateProjectionMatrix();
    }
    super.updateMatrices(light);
  }
  copy(source) {
    super.copy(source);
    this.focus = source.focus;
    return this;
  }
}
class SpotLight extends Light {
  constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) {
    super(color, intensity);
    this.isSpotLight = true;
    this.type = "SpotLight";
    this.position.copy(Object3D.DEFAULT_UP);
    this.updateMatrix();
    this.target = new Object3D();
    this.distance = distance;
    this.angle = angle;
    this.penumbra = penumbra;
    this.decay = decay;
    this.map = null;
    this.shadow = new SpotLightShadow();
  }
  get power() {
    return this.intensity * Math.PI;
  }
  set power(power) {
    this.intensity = power / Math.PI;
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.distance = source.distance;
    this.angle = source.angle;
    this.penumbra = source.penumbra;
    this.decay = source.decay;
    this.target = source.target.clone();
    this.shadow = source.shadow.clone();
    return this;
  }
}
const _projScreenMatrix = /* @__PURE__ */ new Matrix4();
const _lightPositionWorld = /* @__PURE__ */ new Vector3();
const _lookTarget = /* @__PURE__ */ new Vector3();
class PointLightShadow extends LightShadow {
  constructor() {
    super(new PerspectiveCamera(90, 1, 0.5, 500));
    this.isPointLightShadow = true;
    this._frameExtents = new Vector2(4, 2);
    this._viewportCount = 6;
    this._viewports = [
      // These viewports map a cube-map onto a 2D texture with the
      // following orientation:
      //
      //  xzXZ
      //   y Y
      //
      // X - Positive x direction
      // x - Negative x direction
      // Y - Positive y direction
      // y - Negative y direction
      // Z - Positive z direction
      // z - Negative z direction
      // positive X
      new Vector4(2, 1, 1, 1),
      // negative X
      new Vector4(0, 1, 1, 1),
      // positive Z
      new Vector4(3, 1, 1, 1),
      // negative Z
      new Vector4(1, 1, 1, 1),
      // positive Y
      new Vector4(3, 0, 1, 1),
      // negative Y
      new Vector4(1, 0, 1, 1)
    ];
    this._cubeDirections = [
      new Vector3(1, 0, 0),
      new Vector3(-1, 0, 0),
      new Vector3(0, 0, 1),
      new Vector3(0, 0, -1),
      new Vector3(0, 1, 0),
      new Vector3(0, -1, 0)
    ];
    this._cubeUps = [
      new Vector3(0, 1, 0),
      new Vector3(0, 1, 0),
      new Vector3(0, 1, 0),
      new Vector3(0, 1, 0),
      new Vector3(0, 0, 1),
      new Vector3(0, 0, -1)
    ];
  }
  updateMatrices(light, viewportIndex = 0) {
    const camera = this.camera;
    const shadowMatrix = this.matrix;
    const far = light.distance || camera.far;
    if (far !== camera.far) {
      camera.far = far;
      camera.updateProjectionMatrix();
    }
    _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
    camera.position.copy(_lightPositionWorld);
    _lookTarget.copy(camera.position);
    _lookTarget.add(this._cubeDirections[viewportIndex]);
    camera.up.copy(this._cubeUps[viewportIndex]);
    camera.lookAt(_lookTarget);
    camera.updateMatrixWorld();
    shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
    _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
    this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  }
}
class PointLight extends Light {
  constructor(color, intensity, distance = 0, decay = 2) {
    super(color, intensity);
    this.isPointLight = true;
    this.type = "PointLight";
    this.distance = distance;
    this.decay = decay;
    this.shadow = new PointLightShadow();
  }
  get power() {
    return this.intensity * 4 * Math.PI;
  }
  set power(power) {
    this.intensity = power / (4 * Math.PI);
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.distance = source.distance;
    this.decay = source.decay;
    this.shadow = source.shadow.clone();
    return this;
  }
}
class OrthographicCamera extends Camera {
  constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2e3) {
    super();
    this.isOrthographicCamera = true;
    this.type = "OrthographicCamera";
    this.zoom = 1;
    this.view = null;
    this.left = left;
    this.right = right;
    this.top = top;
    this.bottom = bottom;
    this.near = near;
    this.far = far;
    this.updateProjectionMatrix();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.left = source.left;
    this.right = source.right;
    this.top = source.top;
    this.bottom = source.bottom;
    this.near = source.near;
    this.far = source.far;
    this.zoom = source.zoom;
    this.view = source.view === null ? null : Object.assign({}, source.view);
    return this;
  }
  setViewOffset(fullWidth, fullHeight, x, y2, width, height) {
    if (this.view === null) {
      this.view = {
        enabled: true,
        fullWidth: 1,
        fullHeight: 1,
        offsetX: 0,
        offsetY: 0,
        width: 1,
        height: 1
      };
    }
    this.view.enabled = true;
    this.view.fullWidth = fullWidth;
    this.view.fullHeight = fullHeight;
    this.view.offsetX = x;
    this.view.offsetY = y2;
    this.view.width = width;
    this.view.height = height;
    this.updateProjectionMatrix();
  }
  clearViewOffset() {
    if (this.view !== null) {
      this.view.enabled = false;
    }
    this.updateProjectionMatrix();
  }
  updateProjectionMatrix() {
    const dx = (this.right - this.left) / (2 * this.zoom);
    const dy = (this.top - this.bottom) / (2 * this.zoom);
    const cx = (this.right + this.left) / 2;
    const cy = (this.top + this.bottom) / 2;
    let left = cx - dx;
    let right = cx + dx;
    let top = cy + dy;
    let bottom = cy - dy;
    if (this.view !== null && this.view.enabled) {
      const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
      const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
      left += scaleW * this.view.offsetX;
      right = left + scaleW * this.view.width;
      top -= scaleH * this.view.offsetY;
      bottom = top - scaleH * this.view.height;
    }
    this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem);
    this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.object.zoom = this.zoom;
    data.object.left = this.left;
    data.object.right = this.right;
    data.object.top = this.top;
    data.object.bottom = this.bottom;
    data.object.near = this.near;
    data.object.far = this.far;
    if (this.view !== null) data.object.view = Object.assign({}, this.view);
    return data;
  }
}
class DirectionalLightShadow extends LightShadow {
  constructor() {
    super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
    this.isDirectionalLightShadow = true;
  }
}
class DirectionalLight extends Light {
  constructor(color, intensity) {
    super(color, intensity);
    this.isDirectionalLight = true;
    this.type = "DirectionalLight";
    this.position.copy(Object3D.DEFAULT_UP);
    this.updateMatrix();
    this.target = new Object3D();
    this.shadow = new DirectionalLightShadow();
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(source) {
    super.copy(source);
    this.target = source.target.clone();
    this.shadow = source.shadow.clone();
    return this;
  }
}
class AmbientLight extends Light {
  constructor(color, intensity) {
    super(color, intensity);
    this.isAmbientLight = true;
    this.type = "AmbientLight";
  }
}
class RectAreaLight extends Light {
  constructor(color, intensity, width = 10, height = 10) {
    super(color, intensity);
    this.isRectAreaLight = true;
    this.type = "RectAreaLight";
    this.width = width;
    this.height = height;
  }
  get power() {
    return this.intensity * this.width * this.height * Math.PI;
  }
  set power(power) {
    this.intensity = power / (this.width * this.height * Math.PI);
  }
  copy(source) {
    super.copy(source);
    this.width = source.width;
    this.height = source.height;
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.object.width = this.width;
    data.object.height = this.height;
    return data;
  }
}
class SphericalHarmonics3 {
  constructor() {
    this.isSphericalHarmonics3 = true;
    this.coefficients = [];
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients.push(new Vector3());
    }
  }
  set(coefficients) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].copy(coefficients[i2]);
    }
    return this;
  }
  zero() {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].set(0, 0, 0);
    }
    return this;
  }
  // get the radiance in the direction of the normal
  // target is a Vector3
  getAt(normal, target) {
    const x = normal.x, y2 = normal.y, z2 = normal.z;
    const coeff = this.coefficients;
    target.copy(coeff[0]).multiplyScalar(0.282095);
    target.addScaledVector(coeff[1], 0.488603 * y2);
    target.addScaledVector(coeff[2], 0.488603 * z2);
    target.addScaledVector(coeff[3], 0.488603 * x);
    target.addScaledVector(coeff[4], 1.092548 * (x * y2));
    target.addScaledVector(coeff[5], 1.092548 * (y2 * z2));
    target.addScaledVector(coeff[6], 0.315392 * (3 * z2 * z2 - 1));
    target.addScaledVector(coeff[7], 1.092548 * (x * z2));
    target.addScaledVector(coeff[8], 0.546274 * (x * x - y2 * y2));
    return target;
  }
  // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  // target is a Vector3
  // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  getIrradianceAt(normal, target) {
    const x = normal.x, y2 = normal.y, z2 = normal.z;
    const coeff = this.coefficients;
    target.copy(coeff[0]).multiplyScalar(0.886227);
    target.addScaledVector(coeff[1], 2 * 0.511664 * y2);
    target.addScaledVector(coeff[2], 2 * 0.511664 * z2);
    target.addScaledVector(coeff[3], 2 * 0.511664 * x);
    target.addScaledVector(coeff[4], 2 * 0.429043 * x * y2);
    target.addScaledVector(coeff[5], 2 * 0.429043 * y2 * z2);
    target.addScaledVector(coeff[6], 0.743125 * z2 * z2 - 0.247708);
    target.addScaledVector(coeff[7], 2 * 0.429043 * x * z2);
    target.addScaledVector(coeff[8], 0.429043 * (x * x - y2 * y2));
    return target;
  }
  add(sh) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].add(sh.coefficients[i2]);
    }
    return this;
  }
  addScaledSH(sh, s2) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].addScaledVector(sh.coefficients[i2], s2);
    }
    return this;
  }
  scale(s2) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].multiplyScalar(s2);
    }
    return this;
  }
  lerp(sh, alpha) {
    for (let i2 = 0; i2 < 9; i2++) {
      this.coefficients[i2].lerp(sh.coefficients[i2], alpha);
    }
    return this;
  }
  equals(sh) {
    for (let i2 = 0; i2 < 9; i2++) {
      if (!this.coefficients[i2].equals(sh.coefficients[i2])) {
        return false;
      }
    }
    return true;
  }
  copy(sh) {
    return this.set(sh.coefficients);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  fromArray(array, offset = 0) {
    const coefficients = this.coefficients;
    for (let i2 = 0; i2 < 9; i2++) {
      coefficients[i2].fromArray(array, offset + i2 * 3);
    }
    return this;
  }
  toArray(array = [], offset = 0) {
    const coefficients = this.coefficients;
    for (let i2 = 0; i2 < 9; i2++) {
      coefficients[i2].toArray(array, offset + i2 * 3);
    }
    return array;
  }
  // evaluate the basis functions
  // shBasis is an Array[ 9 ]
  static getBasisAt(normal, shBasis) {
    const x = normal.x, y2 = normal.y, z2 = normal.z;
    shBasis[0] = 0.282095;
    shBasis[1] = 0.488603 * y2;
    shBasis[2] = 0.488603 * z2;
    shBasis[3] = 0.488603 * x;
    shBasis[4] = 1.092548 * x * y2;
    shBasis[5] = 1.092548 * y2 * z2;
    shBasis[6] = 0.315392 * (3 * z2 * z2 - 1);
    shBasis[7] = 1.092548 * x * z2;
    shBasis[8] = 0.546274 * (x * x - y2 * y2);
  }
}
class LightProbe extends Light {
  constructor(sh = new SphericalHarmonics3(), intensity = 1) {
    super(void 0, intensity);
    this.isLightProbe = true;
    this.sh = sh;
  }
  copy(source) {
    super.copy(source);
    this.sh.copy(source.sh);
    return this;
  }
  fromJSON(json3) {
    this.intensity = json3.intensity;
    this.sh.fromArray(json3.sh);
    return this;
  }
  toJSON(meta2) {
    const data = super.toJSON(meta2);
    data.object.sh = this.sh.toArray();
    return data;
  }
}
class MaterialLoader extends Loader {
  constructor(manager) {
    super(manager);
    this.textures = {};
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader2 = new FileLoader(scope.manager);
    loader2.setPath(scope.path);
    loader2.setRequestHeader(scope.requestHeader);
    loader2.setWithCredentials(scope.withCredentials);
    loader2.load(url, function(text) {
      try {
        onLoad(scope.parse(JSON.parse(text)));
      } catch (e2) {
        if (onError) {
          onError(e2);
        } else {
          console.error(e2);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  parse(json3) {
    const textures = this.textures;
    function getTexture(name) {
      if (textures[name] === void 0) {
        console.warn("THREE.MaterialLoader: Undefined texture", name);
      }
      return textures[name];
    }
    const material = this.createMaterialFromType(json3.type);
    if (json3.uuid !== void 0) material.uuid = json3.uuid;
    if (json3.name !== void 0) material.name = json3.name;
    if (json3.color !== void 0 && material.color !== void 0) material.color.setHex(json3.color);
    if (json3.roughness !== void 0) material.roughness = json3.roughness;
    if (json3.metalness !== void 0) material.metalness = json3.metalness;
    if (json3.sheen !== void 0) material.sheen = json3.sheen;
    if (json3.sheenColor !== void 0) material.sheenColor = new Color().setHex(json3.sheenColor);
    if (json3.sheenRoughness !== void 0) material.sheenRoughness = json3.sheenRoughness;
    if (json3.emissive !== void 0 && material.emissive !== void 0) material.emissive.setHex(json3.emissive);
    if (json3.specular !== void 0 && material.specular !== void 0) material.specular.setHex(json3.specular);
    if (json3.specularIntensity !== void 0) material.specularIntensity = json3.specularIntensity;
    if (json3.specularColor !== void 0 && material.specularColor !== void 0) material.specularColor.setHex(json3.specularColor);
    if (json3.shininess !== void 0) material.shininess = json3.shininess;
    if (json3.clearcoat !== void 0) material.clearcoat = json3.clearcoat;
    if (json3.clearcoatRoughness !== void 0) material.clearcoatRoughness = json3.clearcoatRoughness;
    if (json3.dispersion !== void 0) material.dispersion = json3.dispersion;
    if (json3.iridescence !== void 0) material.iridescence = json3.iridescence;
    if (json3.iridescenceIOR !== void 0) material.iridescenceIOR = json3.iridescenceIOR;
    if (json3.iridescenceThicknessRange !== void 0) material.iridescenceThicknessRange = json3.iridescenceThicknessRange;
    if (json3.transmission !== void 0) material.transmission = json3.transmission;
    if (json3.thickness !== void 0) material.thickness = json3.thickness;
    if (json3.attenuationDistance !== void 0) material.attenuationDistance = json3.attenuationDistance;
    if (json3.attenuationColor !== void 0 && material.attenuationColor !== void 0) material.attenuationColor.setHex(json3.attenuationColor);
    if (json3.anisotropy !== void 0) material.anisotropy = json3.anisotropy;
    if (json3.anisotropyRotation !== void 0) material.anisotropyRotation = json3.anisotropyRotation;
    if (json3.fog !== void 0) material.fog = json3.fog;
    if (json3.flatShading !== void 0) material.flatShading = json3.flatShading;
    if (json3.blending !== void 0) material.blending = json3.blending;
    if (json3.combine !== void 0) material.combine = json3.combine;
    if (json3.side !== void 0) material.side = json3.side;
    if (json3.shadowSide !== void 0) material.shadowSide = json3.shadowSide;
    if (json3.opacity !== void 0) material.opacity = json3.opacity;
    if (json3.transparent !== void 0) material.transparent = json3.transparent;
    if (json3.alphaTest !== void 0) material.alphaTest = json3.alphaTest;
    if (json3.alphaHash !== void 0) material.alphaHash = json3.alphaHash;
    if (json3.depthFunc !== void 0) material.depthFunc = json3.depthFunc;
    if (json3.depthTest !== void 0) material.depthTest = json3.depthTest;
    if (json3.depthWrite !== void 0) material.depthWrite = json3.depthWrite;
    if (json3.colorWrite !== void 0) material.colorWrite = json3.colorWrite;
    if (json3.blendSrc !== void 0) material.blendSrc = json3.blendSrc;
    if (json3.blendDst !== void 0) material.blendDst = json3.blendDst;
    if (json3.blendEquation !== void 0) material.blendEquation = json3.blendEquation;
    if (json3.blendSrcAlpha !== void 0) material.blendSrcAlpha = json3.blendSrcAlpha;
    if (json3.blendDstAlpha !== void 0) material.blendDstAlpha = json3.blendDstAlpha;
    if (json3.blendEquationAlpha !== void 0) material.blendEquationAlpha = json3.blendEquationAlpha;
    if (json3.blendColor !== void 0 && material.blendColor !== void 0) material.blendColor.setHex(json3.blendColor);
    if (json3.blendAlpha !== void 0) material.blendAlpha = json3.blendAlpha;
    if (json3.stencilWriteMask !== void 0) material.stencilWriteMask = json3.stencilWriteMask;
    if (json3.stencilFunc !== void 0) material.stencilFunc = json3.stencilFunc;
    if (json3.stencilRef !== void 0) material.stencilRef = json3.stencilRef;
    if (json3.stencilFuncMask !== void 0) material.stencilFuncMask = json3.stencilFuncMask;
    if (json3.stencilFail !== void 0) material.stencilFail = json3.stencilFail;
    if (json3.stencilZFail !== void 0) material.stencilZFail = json3.stencilZFail;
    if (json3.stencilZPass !== void 0) material.stencilZPass = json3.stencilZPass;
    if (json3.stencilWrite !== void 0) material.stencilWrite = json3.stencilWrite;
    if (json3.wireframe !== void 0) material.wireframe = json3.wireframe;
    if (json3.wireframeLinewidth !== void 0) material.wireframeLinewidth = json3.wireframeLinewidth;
    if (json3.wireframeLinecap !== void 0) material.wireframeLinecap = json3.wireframeLinecap;
    if (json3.wireframeLinejoin !== void 0) material.wireframeLinejoin = json3.wireframeLinejoin;
    if (json3.rotation !== void 0) material.rotation = json3.rotation;
    if (json3.linewidth !== void 0) material.linewidth = json3.linewidth;
    if (json3.dashSize !== void 0) material.dashSize = json3.dashSize;
    if (json3.gapSize !== void 0) material.gapSize = json3.gapSize;
    if (json3.scale !== void 0) material.scale = json3.scale;
    if (json3.polygonOffset !== void 0) material.polygonOffset = json3.polygonOffset;
    if (json3.polygonOffsetFactor !== void 0) material.polygonOffsetFactor = json3.polygonOffsetFactor;
    if (json3.polygonOffsetUnits !== void 0) material.polygonOffsetUnits = json3.polygonOffsetUnits;
    if (json3.dithering !== void 0) material.dithering = json3.dithering;
    if (json3.alphaToCoverage !== void 0) material.alphaToCoverage = json3.alphaToCoverage;
    if (json3.premultipliedAlpha !== void 0) material.premultipliedAlpha = json3.premultipliedAlpha;
    if (json3.forceSinglePass !== void 0) material.forceSinglePass = json3.forceSinglePass;
    if (json3.visible !== void 0) material.visible = json3.visible;
    if (json3.toneMapped !== void 0) material.toneMapped = json3.toneMapped;
    if (json3.userData !== void 0) material.userData = json3.userData;
    if (json3.vertexColors !== void 0) {
      if (typeof json3.vertexColors === "number") {
        material.vertexColors = json3.vertexColors > 0 ? true : false;
      } else {
        material.vertexColors = json3.vertexColors;
      }
    }
    if (json3.uniforms !== void 0) {
      for (const name in json3.uniforms) {
        const uniform = json3.uniforms[name];
        material.uniforms[name] = {};
        switch (uniform.type) {
          case "t":
            material.uniforms[name].value = getTexture(uniform.value);
            break;
          case "c":
            material.uniforms[name].value = new Color().setHex(uniform.value);
            break;
          case "v2":
            material.uniforms[name].value = new Vector2().fromArray(uniform.value);
            break;
          case "v3":
            material.uniforms[name].value = new Vector3().fromArray(uniform.value);
            break;
          case "v4":
            material.uniforms[name].value = new Vector4().fromArray(uniform.value);
            break;
          case "m3":
            material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
            break;
          case "m4":
            material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
            break;
          default:
            material.uniforms[name].value = uniform.value;
        }
      }
    }
    if (json3.defines !== void 0) material.defines = json3.defines;
    if (json3.vertexShader !== void 0) material.vertexShader = json3.vertexShader;
    if (json3.fragmentShader !== void 0) material.fragmentShader = json3.fragmentShader;
    if (json3.glslVersion !== void 0) material.glslVersion = json3.glslVersion;
    if (json3.extensions !== void 0) {
      for (const key in json3.extensions) {
        material.extensions[key] = json3.extensions[key];
      }
    }
    if (json3.lights !== void 0) material.lights = json3.lights;
    if (json3.clipping !== void 0) material.clipping = json3.clipping;
    if (json3.size !== void 0) material.size = json3.size;
    if (json3.sizeAttenuation !== void 0) material.sizeAttenuation = json3.sizeAttenuation;
    if (json3.map !== void 0) material.map = getTexture(json3.map);
    if (json3.matcap !== void 0) material.matcap = getTexture(json3.matcap);
    if (json3.alphaMap !== void 0) material.alphaMap = getTexture(json3.alphaMap);
    if (json3.bumpMap !== void 0) material.bumpMap = getTexture(json3.bumpMap);
    if (json3.bumpScale !== void 0) material.bumpScale = json3.bumpScale;
    if (json3.normalMap !== void 0) material.normalMap = getTexture(json3.normalMap);
    if (json3.normalMapType !== void 0) material.normalMapType = json3.normalMapType;
    if (json3.normalScale !== void 0) {
      let normalScale = json3.normalScale;
      if (Array.isArray(normalScale) === false) {
        normalScale = [normalScale, normalScale];
      }
      material.normalScale = new Vector2().fromArray(normalScale);
    }
    if (json3.displacementMap !== void 0) material.displacementMap = getTexture(json3.displacementMap);
    if (json3.displacementScale !== void 0) material.displacementScale = json3.displacementScale;
    if (json3.displacementBias !== void 0) material.displacementBias = json3.displacementBias;
    if (json3.roughnessMap !== void 0) material.roughnessMap = getTexture(json3.roughnessMap);
    if (json3.metalnessMap !== void 0) material.metalnessMap = getTexture(json3.metalnessMap);
    if (json3.emissiveMap !== void 0) material.emissiveMap = getTexture(json3.emissiveMap);
    if (json3.emissiveIntensity !== void 0) material.emissiveIntensity = json3.emissiveIntensity;
    if (json3.specularMap !== void 0) material.specularMap = getTexture(json3.specularMap);
    if (json3.specularIntensityMap !== void 0) material.specularIntensityMap = getTexture(json3.specularIntensityMap);
    if (json3.specularColorMap !== void 0) material.specularColorMap = getTexture(json3.specularColorMap);
    if (json3.envMap !== void 0) material.envMap = getTexture(json3.envMap);
    if (json3.envMapRotation !== void 0) material.envMapRotation.fromArray(json3.envMapRotation);
    if (json3.envMapIntensity !== void 0) material.envMapIntensity = json3.envMapIntensity;
    if (json3.reflectivity !== void 0) material.reflectivity = json3.reflectivity;
    if (json3.refractionRatio !== void 0) material.refractionRatio = json3.refractionRatio;
    if (json3.lightMap !== void 0) material.lightMap = getTexture(json3.lightMap);
    if (json3.lightMapIntensity !== void 0) material.lightMapIntensity = json3.lightMapIntensity;
    if (json3.aoMap !== void 0) material.aoMap = getTexture(json3.aoMap);
    if (json3.aoMapIntensity !== void 0) material.aoMapIntensity = json3.aoMapIntensity;
    if (json3.gradientMap !== void 0) material.gradientMap = getTexture(json3.gradientMap);
    if (json3.clearcoatMap !== void 0) material.clearcoatMap = getTexture(json3.clearcoatMap);
    if (json3.clearcoatRoughnessMap !== void 0) material.clearcoatRoughnessMap = getTexture(json3.clearcoatRoughnessMap);
    if (json3.clearcoatNormalMap !== void 0) material.clearcoatNormalMap = getTexture(json3.clearcoatNormalMap);
    if (json3.clearcoatNormalScale !== void 0) material.clearcoatNormalScale = new Vector2().fromArray(json3.clearcoatNormalScale);
    if (json3.iridescenceMap !== void 0) material.iridescenceMap = getTexture(json3.iridescenceMap);
    if (json3.iridescenceThicknessMap !== void 0) material.iridescenceThicknessMap = getTexture(json3.iridescenceThicknessMap);
    if (json3.transmissionMap !== void 0) material.transmissionMap = getTexture(json3.transmissionMap);
    if (json3.thicknessMap !== void 0) material.thicknessMap = getTexture(json3.thicknessMap);
    if (json3.anisotropyMap !== void 0) material.anisotropyMap = getTexture(json3.anisotropyMap);
    if (json3.sheenColorMap !== void 0) material.sheenColorMap = getTexture(json3.sheenColorMap);
    if (json3.sheenRoughnessMap !== void 0) material.sheenRoughnessMap = getTexture(json3.sheenRoughnessMap);
    return material;
  }
  setTextures(value) {
    this.textures = value;
    return this;
  }
  createMaterialFromType(type) {
    return MaterialLoader.createMaterialFromType(type);
  }
  static createMaterialFromType(type) {
    const materialLib = {
      ShadowMaterial,
      SpriteMaterial,
      RawShaderMaterial,
      ShaderMaterial,
      PointsMaterial,
      MeshPhysicalMaterial,
      MeshStandardMaterial,
      MeshPhongMaterial,
      MeshToonMaterial,
      MeshNormalMaterial,
      MeshLambertMaterial,
      MeshDepthMaterial,
      MeshDistanceMaterial,
      MeshBasicMaterial,
      MeshMatcapMaterial,
      LineDashedMaterial,
      LineBasicMaterial,
      Material
    };
    return new materialLib[type]();
  }
}
class LoaderUtils {
  static decodeText(array) {
    console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.");
    if (typeof TextDecoder !== "undefined") {
      return new TextDecoder().decode(array);
    }
    let s2 = "";
    for (let i2 = 0, il = array.length; i2 < il; i2++) {
      s2 += String.fromCharCode(array[i2]);
    }
    try {
      return decodeURIComponent(escape(s2));
    } catch (e2) {
      return s2;
    }
  }
  static extractUrlBase(url) {
    const index = url.lastIndexOf("/");
    if (index === -1) return "./";
    return url.slice(0, index + 1);
  }
  static resolveURL(url, path) {
    if (typeof url !== "string" || url === "") return "";
    if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
      path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1");
    }
    if (/^(https?:)?\/\//i.test(url)) return url;
    if (/^data:.*,.*$/i.test(url)) return url;
    if (/^blob:.*$/i.test(url)) return url;
    return path + url;
  }
}
class InstancedBufferGeometry extends BufferGeometry {
  constructor() {
    super();
    this.isInstancedBufferGeometry = true;
    this.type = "InstancedBufferGeometry";
    this.instanceCount = Infinity;
  }
  copy(source) {
    super.copy(source);
    this.instanceCount = source.instanceCount;
    return this;
  }
  toJSON() {
    const data = super.toJSON();
    data.instanceCount = this.instanceCount;
    data.isInstancedBufferGeometry = true;
    return data;
  }
}
class BufferGeometryLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader2 = new FileLoader(scope.manager);
    loader2.setPath(scope.path);
    loader2.setRequestHeader(scope.requestHeader);
    loader2.setWithCredentials(scope.withCredentials);
    loader2.load(url, function(text) {
      try {
        onLoad(scope.parse(JSON.parse(text)));
      } catch (e2) {
        if (onError) {
          onError(e2);
        } else {
          console.error(e2);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  parse(json3) {
    const interleavedBufferMap = {};
    const arrayBufferMap = {};
    function getInterleavedBuffer(json4, uuid) {
      if (interleavedBufferMap[uuid] !== void 0) return interleavedBufferMap[uuid];
      const interleavedBuffers = json4.interleavedBuffers;
      const interleavedBuffer = interleavedBuffers[uuid];
      const buffer = getArrayBuffer(json4, interleavedBuffer.buffer);
      const array = getTypedArray(interleavedBuffer.type, buffer);
      const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
      ib.uuid = interleavedBuffer.uuid;
      interleavedBufferMap[uuid] = ib;
      return ib;
    }
    function getArrayBuffer(json4, uuid) {
      if (arrayBufferMap[uuid] !== void 0) return arrayBufferMap[uuid];
      const arrayBuffers = json4.arrayBuffers;
      const arrayBuffer = arrayBuffers[uuid];
      const ab = new Uint32Array(arrayBuffer).buffer;
      arrayBufferMap[uuid] = ab;
      return ab;
    }
    const geometry = json3.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
    const index = json3.data.index;
    if (index !== void 0) {
      const typedArray = getTypedArray(index.type, index.array);
      geometry.setIndex(new BufferAttribute(typedArray, 1));
    }
    const attributes = json3.data.attributes;
    for (const key in attributes) {
      const attribute = attributes[key];
      let bufferAttribute;
      if (attribute.isInterleavedBufferAttribute) {
        const interleavedBuffer = getInterleavedBuffer(json3.data, attribute.data);
        bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
      } else {
        const typedArray = getTypedArray(attribute.type, attribute.array);
        const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
        bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
      }
      if (attribute.name !== void 0) bufferAttribute.name = attribute.name;
      if (attribute.usage !== void 0) bufferAttribute.setUsage(attribute.usage);
      geometry.setAttribute(key, bufferAttribute);
    }
    const morphAttributes = json3.data.morphAttributes;
    if (morphAttributes) {
      for (const key in morphAttributes) {
        const attributeArray = morphAttributes[key];
        const array = [];
        for (let i2 = 0, il = attributeArray.length; i2 < il; i2++) {
          const attribute = attributeArray[i2];
          let bufferAttribute;
          if (attribute.isInterleavedBufferAttribute) {
            const interleavedBuffer = getInterleavedBuffer(json3.data, attribute.data);
            bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
          } else {
            const typedArray = getTypedArray(attribute.type, attribute.array);
            bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
          }
          if (attribute.name !== void 0) bufferAttribute.name = attribute.name;
          array.push(bufferAttribute);
        }
        geometry.morphAttributes[key] = array;
      }
    }
    const morphTargetsRelative = json3.data.morphTargetsRelative;
    if (morphTargetsRelative) {
      geometry.morphTargetsRelative = true;
    }
    const groups = json3.data.groups || json3.data.drawcalls || json3.data.offsets;
    if (groups !== void 0) {
      for (let i2 = 0, n2 = groups.length; i2 !== n2; ++i2) {
        const group = groups[i2];
        geometry.addGroup(group.start, group.count, group.materialIndex);
      }
    }
    const boundingSphere = json3.data.boundingSphere;
    if (boundingSphere !== void 0) {
      const center = new Vector3();
      if (boundingSphere.center !== void 0) {
        center.fromArray(boundingSphere.center);
      }
      geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
    }
    if (json3.name) geometry.name = json3.name;
    if (json3.userData) geometry.userData = json3.userData;
    return geometry;
  }
}
class ObjectLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path;
    this.resourcePath = this.resourcePath || path;
    const loader2 = new FileLoader(this.manager);
    loader2.setPath(this.path);
    loader2.setRequestHeader(this.requestHeader);
    loader2.setWithCredentials(this.withCredentials);
    loader2.load(url, function(text) {
      let json3 = null;
      try {
        json3 = JSON.parse(text);
      } catch (error2) {
        if (onError !== void 0) onError(error2);
        console.error("THREE:ObjectLoader: Can't parse " + url + ".", error2.message);
        return;
      }
      const metadata = json3.metadata;
      if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") {
        if (onError !== void 0) onError(new Error("THREE.ObjectLoader: Can't load " + url));
        console.error("THREE.ObjectLoader: Can't load " + url);
        return;
      }
      scope.parse(json3, onLoad);
    }, onProgress, onError);
  }
  async loadAsync(url, onProgress) {
    const scope = this;
    const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path;
    this.resourcePath = this.resourcePath || path;
    const loader2 = new FileLoader(this.manager);
    loader2.setPath(this.path);
    loader2.setRequestHeader(this.requestHeader);
    loader2.setWithCredentials(this.withCredentials);
    const text = await loader2.loadAsync(url, onProgress);
    const json3 = JSON.parse(text);
    const metadata = json3.metadata;
    if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") {
      throw new Error("THREE.ObjectLoader: Can't load " + url);
    }
    return await scope.parseAsync(json3);
  }
  parse(json3, onLoad) {
    const animations = this.parseAnimations(json3.animations);
    const shapes = this.parseShapes(json3.shapes);
    const geometries = this.parseGeometries(json3.geometries, shapes);
    const images = this.parseImages(json3.images, function() {
      if (onLoad !== void 0) onLoad(object);
    });
    const textures = this.parseTextures(json3.textures, images);
    const materials = this.parseMaterials(json3.materials, textures);
    const object = this.parseObject(json3.object, geometries, materials, textures, animations);
    const skeletons = this.parseSkeletons(json3.skeletons, object);
    this.bindSkeletons(object, skeletons);
    this.bindLightTargets(object);
    if (onLoad !== void 0) {
      let hasImages = false;
      for (const uuid in images) {
        if (images[uuid].data instanceof HTMLImageElement) {
          hasImages = true;
          break;
        }
      }
      if (hasImages === false) onLoad(object);
    }
    return object;
  }
  async parseAsync(json3) {
    const animations = this.parseAnimations(json3.animations);
    const shapes = this.parseShapes(json3.shapes);
    const geometries = this.parseGeometries(json3.geometries, shapes);
    const images = await this.parseImagesAsync(json3.images);
    const textures = this.parseTextures(json3.textures, images);
    const materials = this.parseMaterials(json3.materials, textures);
    const object = this.parseObject(json3.object, geometries, materials, textures, animations);
    const skeletons = this.parseSkeletons(json3.skeletons, object);
    this.bindSkeletons(object, skeletons);
    this.bindLightTargets(object);
    return object;
  }
  parseShapes(json3) {
    const shapes = {};
    if (json3 !== void 0) {
      for (let i2 = 0, l2 = json3.length; i2 < l2; i2++) {
        const shape = new Shape().fromJSON(json3[i2]);
        shapes[shape.uuid] = shape;
      }
    }
    return shapes;
  }
  parseSkeletons(json3, object) {
    const skeletons = {};
    const bones = {};
    object.traverse(function(child) {
      if (child.isBone) bones[child.uuid] = child;
    });
    if (json3 !== void 0) {
      for (let i2 = 0, l2 = json3.length; i2 < l2; i2++) {
        const skeleton = new Skeleton().fromJSON(json3[i2], bones);
        skeletons[skeleton.uuid] = skeleton;
      }
    }
    return skeletons;
  }
  parseGeometries(json3, shapes) {
    const geometries = {};
    if (json3 !== void 0) {
      const bufferGeometryLoader = new BufferGeometryLoader();
      for (let i2 = 0, l2 = json3.length; i2 < l2; i2++) {
        let geometry;
        const data = json3[i2];
        switch (data.type) {
          case "BufferGeometry":
          case "InstancedBufferGeometry":
            geometry = bufferGeometryLoader.parse(data);
            break;
          default:
            if (data.type in Geometries) {
              geometry = Geometries[data.type].fromJSON(data, shapes);
            } else {
              console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
            }
        }
        geometry.uuid = data.uuid;
        if (data.name !== void 0) geometry.name = data.name;
        if (data.userData !== void 0) geometry.userData = data.userData;
        geometries[data.uuid] = geometry;
      }
    }
    return geometries;
  }
  parseMaterials(json3, textures) {
    const cache = {};
    const materials = {};
    if (json3 !== void 0) {
      const loader2 = new MaterialLoader();
      loader2.setTextures(textures);
      for (let i2 = 0, l2 = json3.length; i2 < l2; i2++) {
        const data = json3[i2];
        if (cache[data.uuid] === void 0) {
          cache[data.uuid] = loader2.parse(data);
        }
        materials[data.uuid] = cache[data.uuid];
      }
    }
    return materials;
  }
  parseAnimations(json3) {
    const animations = {};
    if (json3 !== void 0) {
      for (let i2 = 0; i2 < json3.length; i2++) {
        const data = json3[i2];
        const clip = AnimationClip.parse(data);
        animations[clip.uuid] = clip;
      }
    }
    return animations;
  }
  parseImages(json3, onLoad) {
    const scope = this;
    const images = {};
    let loader2;
    function loadImage(url) {
      scope.manager.itemStart(url);
      return loader2.load(url, function() {
        scope.manager.itemEnd(url);
      }, void 0, function() {
        scope.manager.itemError(url);
        scope.manager.itemEnd(url);
      });
    }
    function deserializeImage(image) {
      if (typeof image === "string") {
        const url = image;
        const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
        return loadImage(path);
      } else {
        if (image.data) {
          return {
            data: getTypedArray(image.type, image.data),
            width: image.width,
            height: image.height
          };
        } else {
          return null;
        }
      }
    }
    if (json3 !== void 0 && json3.length > 0) {
      const manager = new LoadingManager(onLoad);
      loader2 = new ImageLoader(manager);
      loader2.setCrossOrigin(this.crossOrigin);
      for (let i2 = 0, il = json3.length; i2 < il; i2++) {
        const image = json3[i2];
        const url = image.url;
        if (Array.isArray(url)) {
          const imageArray = [];
          for (let j2 = 0, jl = url.length; j2 < jl; j2++) {
            const currentUrl = url[j2];
            const deserializedImage = deserializeImage(currentUrl);
            if (deserializedImage !== null) {
              if (deserializedImage instanceof HTMLImageElement) {
                imageArray.push(deserializedImage);
              } else {
                imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
              }
            }
          }
          images[image.uuid] = new Source(imageArray);
        } else {
          const deserializedImage = deserializeImage(image.url);
          images[image.uuid] = new Source(deserializedImage);
        }
      }
    }
    return images;
  }
  async parseImagesAsync(json3) {
    const scope = this;
    const images = {};
    let loader2;
    async function deserializeImage(image) {
      if (typeof image === "string") {
        const url = image;
        const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
        return await loader2.loadAsync(path);
      } else {
        if (image.data) {
          return {
            data: getTypedArray(image.type, image.data),
            width: image.width,
            height: image.height
          };
        } else {
          return null;
        }
      }
    }
    if (json3 !== void 0 && json3.length > 0) {
      loader2 = new ImageLoader(this.manager);
      loader2.setCrossOrigin(this.crossOrigin);
      for (let i2 = 0, il = json3.length; i2 < il; i2++) {
        const image = json3[i2];
        const url = image.url;
        if (Array.isArray(url)) {
          const imageArray = [];
          for (let j2 = 0, jl = url.length; j2 < jl; j2++) {
            const currentUrl = url[j2];
            const deserializedImage = await deserializeImage(currentUrl);
            if (deserializedImage !== null) {
              if (deserializedImage instanceof HTMLImageElement) {
                imageArray.push(deserializedImage);
              } else {
                imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
              }
            }
          }
          images[image.uuid] = new Source(imageArray);
        } else {
          const deserializedImage = await deserializeImage(image.url);
          images[image.uuid] = new Source(deserializedImage);
        }
      }
    }
    return images;
  }
  parseTextures(json3, images) {
    function parseConstant(value, type) {
      if (typeof value === "number") return value;
      console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value);
      return type[value];
    }
    const textures = {};
    if (json3 !== void 0) {
      for (let i2 = 0, l2 = json3.length; i2 < l2; i2++) {
        const data = json3[i2];
        if (data.image === void 0) {
          console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
        }
        if (images[data.image] === void 0) {
          console.warn("THREE.ObjectLoader: Undefined image", data.image);
        }
        const source = images[data.image];
        const image = source.data;
        let texture;
        if (Array.isArray(image)) {
          texture = new CubeTexture();
          if (image.length === 6) texture.needsUpdate = true;
        } else {
          if (image && image.data) {
            texture = new DataTexture();
          } else {
            texture = new Texture();
          }
          if (image) texture.needsUpdate = true;
        }
        texture.source = source;
        texture.uuid = data.uuid;
        if (data.name !== void 0) texture.name = data.name;
        if (data.mapping !== void 0) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
        if (data.channel !== void 0) texture.channel = data.channel;
        if (data.offset !== void 0) texture.offset.fromArray(data.offset);
        if (data.repeat !== void 0) texture.repeat.fromArray(data.repeat);
        if (data.center !== void 0) texture.center.fromArray(data.center);
        if (data.rotation !== void 0) texture.rotation = data.rotation;
        if (data.wrap !== void 0) {
          texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
          texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
        }
        if (data.format !== void 0) texture.format = data.format;
        if (data.internalFormat !== void 0) texture.internalFormat = data.internalFormat;
        if (data.type !== void 0) texture.type = data.type;
        if (data.colorSpace !== void 0) texture.colorSpace = data.colorSpace;
        if (data.minFilter !== void 0) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
        if (data.magFilter !== void 0) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
        if (data.anisotropy !== void 0) texture.anisotropy = data.anisotropy;
        if (data.flipY !== void 0) texture.flipY = data.flipY;
        if (data.generateMipmaps !== void 0) texture.generateMipmaps = data.generateMipmaps;
        if (data.premultiplyAlpha !== void 0) texture.premultiplyAlpha = data.premultiplyAlpha;
        if (data.unpackAlignment !== void 0) texture.unpackAlignment = data.unpackAlignment;
        if (data.compareFunction !== void 0) texture.compareFunction = data.compareFunction;
        if (data.userData !== void 0) texture.userData = data.userData;
        textures[data.uuid] = texture;
      }
    }
    return textures;
  }
  parseObject(data, geometries, materials, textures, animations) {
    let object;
    function getGeometry(name) {
      if (geometries[name] === void 0) {
        console.warn("THREE.ObjectLoader: Undefined geometry", name);
      }
      return geometries[name];
    }
    function getMaterial(name) {
      if (name === void 0) return void 0;
      if (Array.isArray(name)) {
        const array = [];
        for (let i2 = 0, l2 = name.length; i2 < l2; i2++) {
          const uuid = name[i2];
          if (materials[uuid] === void 0) {
            console.warn("THREE.ObjectLoader: Undefined material", uuid);
          }
          array.push(materials[uuid]);
        }
        return array;
      }
      if (materials[name] === void 0) {
        console.warn("THREE.ObjectLoader: Undefined material", name);
      }
      return materials[name];
    }
    function getTexture(uuid) {
      if (textures[uuid] === void 0) {
        console.warn("THREE.ObjectLoader: Undefined texture", uuid);
      }
      return textures[uuid];
    }
    let geometry, material;
    switch (data.type) {
      case "Scene":
        object = new Scene();
        if (data.background !== void 0) {
          if (Number.isInteger(data.background)) {
            object.background = new Color(data.background);
          } else {
            object.background = getTexture(data.background);
          }
        }
        if (data.environment !== void 0) {
          object.environment = getTexture(data.environment);
        }
        if (data.fog !== void 0) {
          if (data.fog.type === "Fog") {
            object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
          } else if (data.fog.type === "FogExp2") {
            object.fog = new FogExp2(data.fog.color, data.fog.density);
          }
          if (data.fog.name !== "") {
            object.fog.name = data.fog.name;
          }
        }
        if (data.backgroundBlurriness !== void 0) object.backgroundBlurriness = data.backgroundBlurriness;
        if (data.backgroundIntensity !== void 0) object.backgroundIntensity = data.backgroundIntensity;
        if (data.backgroundRotation !== void 0) object.backgroundRotation.fromArray(data.backgroundRotation);
        if (data.environmentIntensity !== void 0) object.environmentIntensity = data.environmentIntensity;
        if (data.environmentRotation !== void 0) object.environmentRotation.fromArray(data.environmentRotation);
        break;
      case "PerspectiveCamera":
        object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
        if (data.focus !== void 0) object.focus = data.focus;
        if (data.zoom !== void 0) object.zoom = data.zoom;
        if (data.filmGauge !== void 0) object.filmGauge = data.filmGauge;
        if (data.filmOffset !== void 0) object.filmOffset = data.filmOffset;
        if (data.view !== void 0) object.view = Object.assign({}, data.view);
        break;
      case "OrthographicCamera":
        object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
        if (data.zoom !== void 0) object.zoom = data.zoom;
        if (data.view !== void 0) object.view = Object.assign({}, data.view);
        break;
      case "AmbientLight":
        object = new AmbientLight(data.color, data.intensity);
        break;
      case "DirectionalLight":
        object = new DirectionalLight(data.color, data.intensity);
        object.target = data.target || "";
        break;
      case "PointLight":
        object = new PointLight(data.color, data.intensity, data.distance, data.decay);
        break;
      case "RectAreaLight":
        object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
        break;
      case "SpotLight":
        object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
        object.target = data.target || "";
        break;
      case "HemisphereLight":
        object = new HemisphereLight(data.color, data.groundColor, data.intensity);
        break;
      case "LightProbe":
        object = new LightProbe().fromJSON(data);
        break;
      case "SkinnedMesh":
        geometry = getGeometry(data.geometry);
        material = getMaterial(data.material);
        object = new SkinnedMesh(geometry, material);
        if (data.bindMode !== void 0) object.bindMode = data.bindMode;
        if (data.bindMatrix !== void 0) object.bindMatrix.fromArray(data.bindMatrix);
        if (data.skeleton !== void 0) object.skeleton = data.skeleton;
        break;
      case "Mesh":
        geometry = getGeometry(data.geometry);
        material = getMaterial(data.material);
        object = new Mesh(geometry, material);
        break;
      case "InstancedMesh":
        geometry = getGeometry(data.geometry);
        material = getMaterial(data.material);
        const count = data.count;
        const instanceMatrix = data.instanceMatrix;
        const instanceColor = data.instanceColor;
        object = new InstancedMesh(geometry, material, count);
        object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
        if (instanceColor !== void 0) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
        break;
      case "BatchedMesh":
        geometry = getGeometry(data.geometry);
        material = getMaterial(data.material);
        object = new BatchedMesh(data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material);
        object.geometry = geometry;
        object.perObjectFrustumCulled = data.perObjectFrustumCulled;
        object.sortObjects = data.sortObjects;
        object._drawRanges = data.drawRanges;
        object._reservedRanges = data.reservedRanges;
        object._visibility = data.visibility;
        object._active = data.active;
        object._bounds = data.bounds.map((bound) => {
          const box = new Box3();
          box.min.fromArray(bound.boxMin);
          box.max.fromArray(bound.boxMax);
          const sphere = new Sphere();
          sphere.radius = bound.sphereRadius;
          sphere.center.fromArray(bound.sphereCenter);
          return {
            boxInitialized: bound.boxInitialized,
            box,
            sphereInitialized: bound.sphereInitialized,
            sphere
          };
        });
        object._maxInstanceCount = data.maxInstanceCount;
        object._maxVertexCount = data.maxVertexCount;
        object._maxIndexCount = data.maxIndexCount;
        object._geometryInitialized = data.geometryInitialized;
        object._geometryCount = data.geometryCount;
        object._matricesTexture = getTexture(data.matricesTexture.uuid);
        if (data.colorsTexture !== void 0) object._colorsTexture = getTexture(data.colorsTexture.uuid);
        break;
      case "LOD":
        object = new LOD();
        break;
      case "Line":
        object = new Line$1(getGeometry(data.geometry), getMaterial(data.material));
        break;
      case "LineLoop":
        object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
        break;
      case "LineSegments":
        object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
        break;
      case "PointCloud":
      case "Points":
        object = new Points(getGeometry(data.geometry), getMaterial(data.material));
        break;
      case "Sprite":
        object = new Sprite(getMaterial(data.material));
        break;
      case "Group":
        object = new Group();
        break;
      case "Bone":
        object = new Bone();
        break;
      default:
        object = new Object3D();
    }
    object.uuid = data.uuid;
    if (data.name !== void 0) object.name = data.name;
    if (data.matrix !== void 0) {
      object.matrix.fromArray(data.matrix);
      if (data.matrixAutoUpdate !== void 0) object.matrixAutoUpdate = data.matrixAutoUpdate;
      if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
    } else {
      if (data.position !== void 0) object.position.fromArray(data.position);
      if (data.rotation !== void 0) object.rotation.fromArray(data.rotation);
      if (data.quaternion !== void 0) object.quaternion.fromArray(data.quaternion);
      if (data.scale !== void 0) object.scale.fromArray(data.scale);
    }
    if (data.up !== void 0) object.up.fromArray(data.up);
    if (data.castShadow !== void 0) object.castShadow = data.castShadow;
    if (data.receiveShadow !== void 0) object.receiveShadow = data.receiveShadow;
    if (data.shadow) {
      if (data.shadow.intensity !== void 0) object.shadow.intensity = data.shadow.intensity;
      if (data.shadow.bias !== void 0) object.shadow.bias = data.shadow.bias;
      if (data.shadow.normalBias !== void 0) object.shadow.normalBias = data.shadow.normalBias;
      if (data.shadow.radius !== void 0) object.shadow.radius = data.shadow.radius;
      if (data.shadow.mapSize !== void 0) object.shadow.mapSize.fromArray(data.shadow.mapSize);
      if (data.shadow.camera !== void 0) object.shadow.camera = this.parseObject(data.shadow.camera);
    }
    if (data.visible !== void 0) object.visible = data.visible;
    if (data.frustumCulled !== void 0) object.frustumCulled = data.frustumCulled;
    if (data.renderOrder !== void 0) object.renderOrder = data.renderOrder;
    if (data.userData !== void 0) object.userData = data.userData;
    if (data.layers !== void 0) object.layers.mask = data.layers;
    if (data.children !== void 0) {
      const children = data.children;
      for (let i2 = 0; i2 < children.length; i2++) {
        object.add(this.parseObject(children[i2], geometries, materials, textures, animations));
      }
    }
    if (data.animations !== void 0) {
      const objectAnimations = data.animations;
      for (let i2 = 0; i2 < objectAnimations.length; i2++) {
        const uuid = objectAnimations[i2];
        object.animations.push(animations[uuid]);
      }
    }
    if (data.type === "LOD") {
      if (data.autoUpdate !== void 0) object.autoUpdate = data.autoUpdate;
      const levels = data.levels;
      for (let l2 = 0; l2 < levels.length; l2++) {
        const level = levels[l2];
        const child = object.getObjectByProperty("uuid", level.object);
        if (child !== void 0) {
          object.addLevel(child, level.distance, level.hysteresis);
        }
      }
    }
    return object;
  }
  bindSkeletons(object, skeletons) {
    if (Object.keys(skeletons).length === 0) return;
    object.traverse(function(child) {
      if (child.isSkinnedMesh === true && child.skeleton !== void 0) {
        const skeleton = skeletons[child.skeleton];
        if (skeleton === void 0) {
          console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton);
        } else {
          child.bind(skeleton, child.bindMatrix);
        }
      }
    });
  }
  bindLightTargets(object) {
    object.traverse(function(child) {
      if (child.isDirectionalLight || child.isSpotLight) {
        const uuid = child.target;
        const target = object.getObjectByProperty("uuid", uuid);
        if (target !== void 0) {
          child.target = target;
        } else {
          child.target = new Object3D();
        }
      }
    });
  }
}
const TEXTURE_MAPPING = {
  UVMapping,
  CubeReflectionMapping,
  CubeRefractionMapping,
  EquirectangularReflectionMapping,
  EquirectangularRefractionMapping,
  CubeUVReflectionMapping
};
const TEXTURE_WRAPPING = {
  RepeatWrapping,
  ClampToEdgeWrapping,
  MirroredRepeatWrapping
};
const TEXTURE_FILTER = {
  NearestFilter,
  NearestMipmapNearestFilter,
  NearestMipmapLinearFilter,
  LinearFilter,
  LinearMipmapNearestFilter,
  LinearMipmapLinearFilter
};
class ImageBitmapLoader extends Loader {
  constructor(manager) {
    super(manager);
    this.isImageBitmapLoader = true;
    if (typeof createImageBitmap === "undefined") {
      console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported.");
    }
    if (typeof fetch === "undefined") {
      console.warn("THREE.ImageBitmapLoader: fetch() not supported.");
    }
    this.options = { premultiplyAlpha: "none" };
  }
  setOptions(options) {
    this.options = options;
    return this;
  }
  load(url, onLoad, onProgress, onError) {
    if (url === void 0) url = "";
    if (this.path !== void 0) url = this.path + url;
    url = this.manager.resolveURL(url);
    const scope = this;
    const cached = Cache.get(url);
    if (cached !== void 0) {
      scope.manager.itemStart(url);
      if (cached.then) {
        cached.then((imageBitmap) => {
          if (onLoad) onLoad(imageBitmap);
          scope.manager.itemEnd(url);
        }).catch((e2) => {
          if (onError) onError(e2);
        });
        return;
      }
      setTimeout(function() {
        if (onLoad) onLoad(cached);
        scope.manager.itemEnd(url);
      }, 0);
      return cached;
    }
    const fetchOptions = {};
    fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include";
    fetchOptions.headers = this.requestHeader;
    const promise = fetch(url, fetchOptions).then(function(res) {
      return res.blob();
    }).then(function(blob) {
      return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" }));
    }).then(function(imageBitmap) {
      Cache.add(url, imageBitmap);
      if (onLoad) onLoad(imageBitmap);
      scope.manager.itemEnd(url);
      return imageBitmap;
    }).catch(function(e2) {
      if (onError) onError(e2);
      Cache.remove(url);
      scope.manager.itemError(url);
      scope.manager.itemEnd(url);
    });
    Cache.add(url, promise);
    scope.manager.itemStart(url);
  }
}
let _context;
class AudioContext {
  static getContext() {
    if (_context === void 0) {
      _context = new (window.AudioContext || window.webkitAudioContext)();
    }
    return _context;
  }
  static setContext(value) {
    _context = value;
  }
}
class AudioLoader extends Loader {
  constructor(manager) {
    super(manager);
  }
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader2 = new FileLoader(this.manager);
    loader2.setResponseType("arraybuffer");
    loader2.setPath(this.path);
    loader2.setRequestHeader(this.requestHeader);
    loader2.setWithCredentials(this.withCredentials);
    loader2.load(url, function(buffer) {
      try {
        const bufferCopy = buffer.slice(0);
        const context2 = AudioContext.getContext();
        context2.decodeAudioData(bufferCopy, function(audioBuffer) {
          onLoad(audioBuffer);
        }).catch(handleError);
      } catch (e2) {
        handleError(e2);
      }
    }, onProgress, onError);
    function handleError(e2) {
      if (onError) {
        onError(e2);
      } else {
        console.error(e2);
      }
      scope.manager.itemError(url);
    }
  }
}
const _eyeRight = /* @__PURE__ */ new Matrix4();
const _eyeLeft = /* @__PURE__ */ new Matrix4();
const _projectionMatrix = /* @__PURE__ */ new Matrix4();
class StereoCamera {
  constructor() {
    this.type = "StereoCamera";
    this.aspect = 1;
    this.eyeSep = 0.064;
    this.cameraL = new PerspectiveCamera();
    this.cameraL.layers.enable(1);
    this.cameraL.matrixAutoUpdate = false;
    this.cameraR = new PerspectiveCamera();
    this.cameraR.layers.enable(2);
    this.cameraR.matrixAutoUpdate = false;
    this._cache = {
      focus: null,
      fov: null,
      aspect: null,
      near: null,
      far: null,
      zoom: null,
      eyeSep: null
    };
  }
  update(camera) {
    const cache = this._cache;
    const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
    if (needsUpdate) {
      cache.focus = camera.focus;
      cache.fov = camera.fov;
      cache.aspect = camera.aspect * this.aspect;
      cache.near = camera.near;
      cache.far = camera.far;
      cache.zoom = camera.zoom;
      cache.eyeSep = this.eyeSep;
      _projectionMatrix.copy(camera.projectionMatrix);
      const eyeSepHalf = cache.eyeSep / 2;
      const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
      const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
      let xmin, xmax;
      _eyeLeft.elements[12] = -eyeSepHalf;
      _eyeRight.elements[12] = eyeSepHalf;
      xmin = -ymax * cache.aspect + eyeSepOnProjection;
      xmax = ymax * cache.aspect + eyeSepOnProjection;
      _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
      _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
      this.cameraL.projectionMatrix.copy(_projectionMatrix);
      xmin = -ymax * cache.aspect - eyeSepOnProjection;
      xmax = ymax * cache.aspect - eyeSepOnProjection;
      _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
      _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
      this.cameraR.projectionMatrix.copy(_projectionMatrix);
    }
    this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
    this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  }
}
class ArrayCamera extends PerspectiveCamera {
  constructor(array = []) {
    super();
    this.isArrayCamera = true;
    this.cameras = array;
  }
}
class Clock {
  constructor(autoStart = true) {
    this.autoStart = autoStart;
    this.startTime = 0;
    this.oldTime = 0;
    this.elapsedTime = 0;
    this.running = false;
  }
  start() {
    this.startTime = now();
    this.oldTime = this.startTime;
    this.elapsedTime = 0;
    this.running = true;
  }
  stop() {
    this.getElapsedTime();
    this.running = false;
    this.autoStart = false;
  }
  getElapsedTime() {
    this.getDelta();
    return this.elapsedTime;
  }
  getDelta() {
    let diff = 0;
    if (this.autoStart && !this.running) {
      this.start();
      return 0;
    }
    if (this.running) {
      const newTime = now();
      diff = (newTime - this.oldTime) / 1e3;
      this.oldTime = newTime;
      this.elapsedTime += diff;
    }
    return diff;
  }
}
function now() {
  return performance.now();
}
const _position$1 = /* @__PURE__ */ new Vector3();
const _quaternion$1 = /* @__PURE__ */ new Quaternion();
const _scale$1 = /* @__PURE__ */ new Vector3();
const _orientation$1 = /* @__PURE__ */ new Vector3();
class AudioListener extends Object3D {
  constructor() {
    super();
    this.type = "AudioListener";
    this.context = AudioContext.getContext();
    this.gain = this.context.createGain();
    this.gain.connect(this.context.destination);
    this.filter = null;
    this.timeDelta = 0;
    this._clock = new Clock();
  }
  getInput() {
    return this.gain;
  }
  removeFilter() {
    if (this.filter !== null) {
      this.gain.disconnect(this.filter);
      this.filter.disconnect(this.context.destination);
      this.gain.connect(this.context.destination);
      this.filter = null;
    }
    return this;
  }
  getFilter() {
    return this.filter;
  }
  setFilter(value) {
    if (this.filter !== null) {
      this.gain.disconnect(this.filter);
      this.filter.disconnect(this.context.destination);
    } else {
      this.gain.disconnect(this.context.destination);
    }
    this.filter = value;
    this.gain.connect(this.filter);
    this.filter.connect(this.context.destination);
    return this;
  }
  getMasterVolume() {
    return this.gain.gain.value;
  }
  setMasterVolume(value) {
    this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
    return this;
  }
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    const listener = this.context.listener;
    const up = this.up;
    this.timeDelta = this._clock.getDelta();
    this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
    _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
    if (listener.positionX) {
      const endTime = this.context.currentTime + this.timeDelta;
      listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
      listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
      listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
      listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
      listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
      listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
      listener.upX.linearRampToValueAtTime(up.x, endTime);
      listener.upY.linearRampToValueAtTime(up.y, endTime);
      listener.upZ.linearRampToValueAtTime(up.z, endTime);
    } else {
      listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
      listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
    }
  }
}
class Audio extends Object3D {
  constructor(listener) {
    super();
    this.type = "Audio";
    this.listener = listener;
    this.context = listener.context;
    this.gain = this.context.createGain();
    this.gain.connect(listener.getInput());
    this.autoplay = false;
    this.buffer = null;
    this.detune = 0;
    this.loop = false;
    this.loopStart = 0;
    this.loopEnd = 0;
    this.offset = 0;
    this.duration = void 0;
    this.playbackRate = 1;
    this.isPlaying = false;
    this.hasPlaybackControl = true;
    this.source = null;
    this.sourceType = "empty";
    this._startedAt = 0;
    this._progress = 0;
    this._connected = false;
    this.filters = [];
  }
  getOutput() {
    return this.gain;
  }
  setNodeSource(audioNode) {
    this.hasPlaybackControl = false;
    this.sourceType = "audioNode";
    this.source = audioNode;
    this.connect();
    return this;
  }
  setMediaElementSource(mediaElement) {
    this.hasPlaybackControl = false;
    this.sourceType = "mediaNode";
    this.source = this.context.createMediaElementSource(mediaElement);
    this.connect();
    return this;
  }
  setMediaStreamSource(mediaStream) {
    this.hasPlaybackControl = false;
    this.sourceType = "mediaStreamNode";
    this.source = this.context.createMediaStreamSource(mediaStream);
    this.connect();
    return this;
  }
  setBuffer(audioBuffer) {
    this.buffer = audioBuffer;
    this.sourceType = "buffer";
    if (this.autoplay) this.play();
    return this;
  }
  play(delay = 0) {
    if (this.isPlaying === true) {
      console.warn("THREE.Audio: Audio is already playing.");
      return;
    }
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this._startedAt = this.context.currentTime + delay;
    const source = this.context.createBufferSource();
    source.buffer = this.buffer;
    source.loop = this.loop;
    source.loopStart = this.loopStart;
    source.loopEnd = this.loopEnd;
    source.onended = this.onEnded.bind(this);
    source.start(this._startedAt, this._progress + this.offset, this.duration);
    this.isPlaying = true;
    this.source = source;
    this.setDetune(this.detune);
    this.setPlaybackRate(this.playbackRate);
    return this.connect();
  }
  pause() {
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    if (this.isPlaying === true) {
      this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
      if (this.loop === true) {
        this._progress = this._progress % (this.duration || this.buffer.duration);
      }
      this.source.stop();
      this.source.onended = null;
      this.isPlaying = false;
    }
    return this;
  }
  stop(delay = 0) {
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this._progress = 0;
    if (this.source !== null) {
      this.source.stop(this.context.currentTime + delay);
      this.source.onended = null;
    }
    this.isPlaying = false;
    return this;
  }
  connect() {
    if (this.filters.length > 0) {
      this.source.connect(this.filters[0]);
      for (let i2 = 1, l2 = this.filters.length; i2 < l2; i2++) {
        this.filters[i2 - 1].connect(this.filters[i2]);
      }
      this.filters[this.filters.length - 1].connect(this.getOutput());
    } else {
      this.source.connect(this.getOutput());
    }
    this._connected = true;
    return this;
  }
  disconnect() {
    if (this._connected === false) {
      return;
    }
    if (this.filters.length > 0) {
      this.source.disconnect(this.filters[0]);
      for (let i2 = 1, l2 = this.filters.length; i2 < l2; i2++) {
        this.filters[i2 - 1].disconnect(this.filters[i2]);
      }
      this.filters[this.filters.length - 1].disconnect(this.getOutput());
    } else {
      this.source.disconnect(this.getOutput());
    }
    this._connected = false;
    return this;
  }
  getFilters() {
    return this.filters;
  }
  setFilters(value) {
    if (!value) value = [];
    if (this._connected === true) {
      this.disconnect();
      this.filters = value.slice();
      this.connect();
    } else {
      this.filters = value.slice();
    }
    return this;
  }
  setDetune(value) {
    this.detune = value;
    if (this.isPlaying === true && this.source.detune !== void 0) {
      this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
    }
    return this;
  }
  getDetune() {
    return this.detune;
  }
  getFilter() {
    return this.getFilters()[0];
  }
  setFilter(filter) {
    return this.setFilters(filter ? [filter] : []);
  }
  setPlaybackRate(value) {
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this.playbackRate = value;
    if (this.isPlaying === true) {
      this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
    }
    return this;
  }
  getPlaybackRate() {
    return this.playbackRate;
  }
  onEnded() {
    this.isPlaying = false;
    this._progress = 0;
  }
  getLoop() {
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return false;
    }
    return this.loop;
  }
  setLoop(value) {
    if (this.hasPlaybackControl === false) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this.loop = value;
    if (this.isPlaying === true) {
      this.source.loop = this.loop;
    }
    return this;
  }
  setLoopStart(value) {
    this.loopStart = value;
    return this;
  }
  setLoopEnd(value) {
    this.loopEnd = value;
    return this;
  }
  getVolume() {
    return this.gain.gain.value;
  }
  setVolume(value) {
    this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
    return this;
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.sourceType !== "buffer") {
      console.warn("THREE.Audio: Audio source type cannot be copied.");
      return this;
    }
    this.autoplay = source.autoplay;
    this.buffer = source.buffer;
    this.detune = source.detune;
    this.loop = source.loop;
    this.loopStart = source.loopStart;
    this.loopEnd = source.loopEnd;
    this.offset = source.offset;
    this.duration = source.duration;
    this.playbackRate = source.playbackRate;
    this.hasPlaybackControl = source.hasPlaybackControl;
    this.sourceType = source.sourceType;
    this.filters = source.filters.slice();
    return this;
  }
  clone(recursive) {
    return new this.constructor(this.listener).copy(this, recursive);
  }
}
const _position = /* @__PURE__ */ new Vector3();
const _quaternion = /* @__PURE__ */ new Quaternion();
const _scale = /* @__PURE__ */ new Vector3();
const _orientation = /* @__PURE__ */ new Vector3();
class PositionalAudio extends Audio {
  constructor(listener) {
    super(listener);
    this.panner = this.context.createPanner();
    this.panner.panningModel = "HRTF";
    this.panner.connect(this.gain);
  }
  connect() {
    super.connect();
    this.panner.connect(this.gain);
  }
  disconnect() {
    super.disconnect();
    this.panner.disconnect(this.gain);
  }
  getOutput() {
    return this.panner;
  }
  getRefDistance() {
    return this.panner.refDistance;
  }
  setRefDistance(value) {
    this.panner.refDistance = value;
    return this;
  }
  getRolloffFactor() {
    return this.panner.rolloffFactor;
  }
  setRolloffFactor(value) {
    this.panner.rolloffFactor = value;
    return this;
  }
  getDistanceModel() {
    return this.panner.distanceModel;
  }
  setDistanceModel(value) {
    this.panner.distanceModel = value;
    return this;
  }
  getMaxDistance() {
    return this.panner.maxDistance;
  }
  setMaxDistance(value) {
    this.panner.maxDistance = value;
    return this;
  }
  setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
    this.panner.coneInnerAngle = coneInnerAngle;
    this.panner.coneOuterAngle = coneOuterAngle;
    this.panner.coneOuterGain = coneOuterGain;
    return this;
  }
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (this.hasPlaybackControl === true && this.isPlaying === false) return;
    this.matrixWorld.decompose(_position, _quaternion, _scale);
    _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
    const panner = this.panner;
    if (panner.positionX) {
      const endTime = this.context.currentTime + this.listener.timeDelta;
      panner.positionX.linearRampToValueAtTime(_position.x, endTime);
      panner.positionY.linearRampToValueAtTime(_position.y, endTime);
      panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
      panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
      panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
      panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
    } else {
      panner.setPosition(_position.x, _position.y, _position.z);
      panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
    }
  }
}
class AudioAnalyser {
  constructor(audio, fftSize = 2048) {
    this.analyser = audio.context.createAnalyser();
    this.analyser.fftSize = fftSize;
    this.data = new Uint8Array(this.analyser.frequencyBinCount);
    audio.getOutput().connect(this.analyser);
  }
  getFrequencyData() {
    this.analyser.getByteFrequencyData(this.data);
    return this.data;
  }
  getAverageFrequency() {
    let value = 0;
    const data = this.getFrequencyData();
    for (let i2 = 0; i2 < data.length; i2++) {
      value += data[i2];
    }
    return value / data.length;
  }
}
class PropertyMixer {
  constructor(binding, typeName, valueSize) {
    this.binding = binding;
    this.valueSize = valueSize;
    let mixFunction, mixFunctionAdditive, setIdentity;
    switch (typeName) {
      case "quaternion":
        mixFunction = this._slerp;
        mixFunctionAdditive = this._slerpAdditive;
        setIdentity = this._setAdditiveIdentityQuaternion;
        this.buffer = new Float64Array(valueSize * 6);
        this._workIndex = 5;
        break;
      case "string":
      case "bool":
        mixFunction = this._select;
        mixFunctionAdditive = this._select;
        setIdentity = this._setAdditiveIdentityOther;
        this.buffer = new Array(valueSize * 5);
        break;
      default:
        mixFunction = this._lerp;
        mixFunctionAdditive = this._lerpAdditive;
        setIdentity = this._setAdditiveIdentityNumeric;
        this.buffer = new Float64Array(valueSize * 5);
    }
    this._mixBufferRegion = mixFunction;
    this._mixBufferRegionAdditive = mixFunctionAdditive;
    this._setIdentity = setIdentity;
    this._origIndex = 3;
    this._addIndex = 4;
    this.cumulativeWeight = 0;
    this.cumulativeWeightAdditive = 0;
    this.useCount = 0;
    this.referenceCount = 0;
  }
  // accumulate data in the 'incoming' region into 'accu<i>'
  accumulate(accuIndex, weight) {
    const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride;
    let currentWeight = this.cumulativeWeight;
    if (currentWeight === 0) {
      for (let i2 = 0; i2 !== stride; ++i2) {
        buffer[offset + i2] = buffer[i2];
      }
      currentWeight = weight;
    } else {
      currentWeight += weight;
      const mix = weight / currentWeight;
      this._mixBufferRegion(buffer, offset, 0, mix, stride);
    }
    this.cumulativeWeight = currentWeight;
  }
  // accumulate data in the 'incoming' region into 'add'
  accumulateAdditive(weight) {
    const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex;
    if (this.cumulativeWeightAdditive === 0) {
      this._setIdentity();
    }
    this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
    this.cumulativeWeightAdditive += weight;
  }
  // apply the state of 'accu<i>' to the binding when accus differ
  apply(accuIndex) {
    const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding;
    this.cumulativeWeight = 0;
    this.cumulativeWeightAdditive = 0;
    if (weight < 1) {
      const originalValueOffset = stride * this._origIndex;
      this._mixBufferRegion(
        buffer,
        offset,
        originalValueOffset,
        1 - weight,
        stride
      );
    }
    if (weightAdditive > 0) {
      this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
    }
    for (let i2 = stride, e2 = stride + stride; i2 !== e2; ++i2) {
      if (buffer[i2] !== buffer[i2 + stride]) {
        binding.setValue(buffer, offset);
        break;
      }
    }
  }
  // remember the state of the bound property and copy it to both accus
  saveOriginalState() {
    const binding = this.binding;
    const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex;
    binding.getValue(buffer, originalValueOffset);
    for (let i2 = stride, e2 = originalValueOffset; i2 !== e2; ++i2) {
      buffer[i2] = buffer[originalValueOffset + i2 % stride];
    }
    this._setIdentity();
    this.cumulativeWeight = 0;
    this.cumulativeWeightAdditive = 0;
  }
  // apply the state previously taken via 'saveOriginalState' to the binding
  restoreOriginalState() {
    const originalValueOffset = this.valueSize * 3;
    this.binding.setValue(this.buffer, originalValueOffset);
  }
  _setAdditiveIdentityNumeric() {
    const startIndex = this._addIndex * this.valueSize;
    const endIndex = startIndex + this.valueSize;
    for (let i2 = startIndex; i2 < endIndex; i2++) {
      this.buffer[i2] = 0;
    }
  }
  _setAdditiveIdentityQuaternion() {
    this._setAdditiveIdentityNumeric();
    this.buffer[this._addIndex * this.valueSize + 3] = 1;
  }
  _setAdditiveIdentityOther() {
    const startIndex = this._origIndex * this.valueSize;
    const targetIndex = this._addIndex * this.valueSize;
    for (let i2 = 0; i2 < this.valueSize; i2++) {
      this.buffer[targetIndex + i2] = this.buffer[startIndex + i2];
    }
  }
  // mix functions
  _select(buffer, dstOffset, srcOffset, t2, stride) {
    if (t2 >= 0.5) {
      for (let i2 = 0; i2 !== stride; ++i2) {
        buffer[dstOffset + i2] = buffer[srcOffset + i2];
      }
    }
  }
  _slerp(buffer, dstOffset, srcOffset, t2) {
    Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t2);
  }
  _slerpAdditive(buffer, dstOffset, srcOffset, t2, stride) {
    const workOffset = this._workIndex * stride;
    Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset);
    Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t2);
  }
  _lerp(buffer, dstOffset, srcOffset, t2, stride) {
    const s2 = 1 - t2;
    for (let i2 = 0; i2 !== stride; ++i2) {
      const j2 = dstOffset + i2;
      buffer[j2] = buffer[j2] * s2 + buffer[srcOffset + i2] * t2;
    }
  }
  _lerpAdditive(buffer, dstOffset, srcOffset, t2, stride) {
    for (let i2 = 0; i2 !== stride; ++i2) {
      const j2 = dstOffset + i2;
      buffer[j2] = buffer[j2] + buffer[srcOffset + i2] * t2;
    }
  }
}
const _RESERVED_CHARS_RE = "\\[\\]\\.:\\/";
const _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g");
const _wordChar = "[^" + _RESERVED_CHARS_RE + "]";
const _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]";
const _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar);
const _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot);
const _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar);
const _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar);
const _trackRe = new RegExp(
  "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$"
);
const _supportedObjectNames = ["material", "materials", "bones", "map"];
class Composite {
  constructor(targetGroup, path, optionalParsedPath) {
    const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
    this._targetGroup = targetGroup;
    this._bindings = targetGroup.subscribe_(path, parsedPath);
  }
  getValue(array, offset) {
    this.bind();
    const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex];
    if (binding !== void 0) binding.getValue(array, offset);
  }
  setValue(array, offset) {
    const bindings = this._bindings;
    for (let i2 = this._targetGroup.nCachedObjects_, n2 = bindings.length; i2 !== n2; ++i2) {
      bindings[i2].setValue(array, offset);
    }
  }
  bind() {
    const bindings = this._bindings;
    for (let i2 = this._targetGroup.nCachedObjects_, n2 = bindings.length; i2 !== n2; ++i2) {
      bindings[i2].bind();
    }
  }
  unbind() {
    const bindings = this._bindings;
    for (let i2 = this._targetGroup.nCachedObjects_, n2 = bindings.length; i2 !== n2; ++i2) {
      bindings[i2].unbind();
    }
  }
}
class PropertyBinding {
  constructor(rootNode, path, parsedPath) {
    this.path = path;
    this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
    this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName);
    this.rootNode = rootNode;
    this.getValue = this._getValue_unbound;
    this.setValue = this._setValue_unbound;
  }
  static create(root, path, parsedPath) {
    if (!(root && root.isAnimationObjectGroup)) {
      return new PropertyBinding(root, path, parsedPath);
    } else {
      return new PropertyBinding.Composite(root, path, parsedPath);
    }
  }
  /**
   * Replaces spaces with underscores and removes unsupported characters from
   * node names, to ensure compatibility with parseTrackName().
   *
   * @param {string} name Node name to be sanitized.
   * @return {string}
   */
  static sanitizeNodeName(name) {
    return name.replace(/\s/g, "_").replace(_reservedRe, "");
  }
  static parseTrackName(trackName) {
    const matches = _trackRe.exec(trackName);
    if (matches === null) {
      throw new Error("PropertyBinding: Cannot parse trackName: " + trackName);
    }
    const results = {
      // directoryName: matches[ 1 ], // (tschw) currently unused
      nodeName: matches[2],
      objectName: matches[3],
      objectIndex: matches[4],
      propertyName: matches[5],
      // required
      propertyIndex: matches[6]
    };
    const lastDot = results.nodeName && results.nodeName.lastIndexOf(".");
    if (lastDot !== void 0 && lastDot !== -1) {
      const objectName = results.nodeName.substring(lastDot + 1);
      if (_supportedObjectNames.indexOf(objectName) !== -1) {
        results.nodeName = results.nodeName.substring(0, lastDot);
        results.objectName = objectName;
      }
    }
    if (results.propertyName === null || results.propertyName.length === 0) {
      throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName);
    }
    return results;
  }
  static findNode(root, nodeName) {
    if (nodeName === void 0 || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
      return root;
    }
    if (root.skeleton) {
      const bone = root.skeleton.getBoneByName(nodeName);
      if (bone !== void 0) {
        return bone;
      }
    }
    if (root.children) {
      const searchNodeSubtree = function(children) {
        for (let i2 = 0; i2 < children.length; i2++) {
          const childNode = children[i2];
          if (childNode.name === nodeName || childNode.uuid === nodeName) {
            return childNode;
          }
          const result = searchNodeSubtree(childNode.children);
          if (result) return result;
        }
        return null;
      };
      const subTreeNode = searchNodeSubtree(root.children);
      if (subTreeNode) {
        return subTreeNode;
      }
    }
    return null;
  }
  // these are used to "bind" a nonexistent property
  _getValue_unavailable() {
  }
  _setValue_unavailable() {
  }
  // Getters
  _getValue_direct(buffer, offset) {
    buffer[offset] = this.targetObject[this.propertyName];
  }
  _getValue_array(buffer, offset) {
    const source = this.resolvedProperty;
    for (let i2 = 0, n2 = source.length; i2 !== n2; ++i2) {
      buffer[offset++] = source[i2];
    }
  }
  _getValue_arrayElement(buffer, offset) {
    buffer[offset] = this.resolvedProperty[this.propertyIndex];
  }
  _getValue_toArray(buffer, offset) {
    this.resolvedProperty.toArray(buffer, offset);
  }
  // Direct
  _setValue_direct(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
  }
  _setValue_direct_setNeedsUpdate(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
    this.targetObject.needsUpdate = true;
  }
  _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  // EntireArray
  _setValue_array(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i2 = 0, n2 = dest.length; i2 !== n2; ++i2) {
      dest[i2] = buffer[offset++];
    }
  }
  _setValue_array_setNeedsUpdate(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i2 = 0, n2 = dest.length; i2 !== n2; ++i2) {
      dest[i2] = buffer[offset++];
    }
    this.targetObject.needsUpdate = true;
  }
  _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i2 = 0, n2 = dest.length; i2 !== n2; ++i2) {
      dest[i2] = buffer[offset++];
    }
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  // ArrayElement
  _setValue_arrayElement(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
  }
  _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
    this.targetObject.needsUpdate = true;
  }
  _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  // HasToFromArray
  _setValue_fromArray(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
  }
  _setValue_fromArray_setNeedsUpdate(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
    this.targetObject.needsUpdate = true;
  }
  _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  _getValue_unbound(targetArray, offset) {
    this.bind();
    this.getValue(targetArray, offset);
  }
  _setValue_unbound(sourceArray, offset) {
    this.bind();
    this.setValue(sourceArray, offset);
  }
  // create getter / setter pair for a property in the scene graph
  bind() {
    let targetObject = this.node;
    const parsedPath = this.parsedPath;
    const objectName = parsedPath.objectName;
    const propertyName = parsedPath.propertyName;
    let propertyIndex = parsedPath.propertyIndex;
    if (!targetObject) {
      targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName);
      this.node = targetObject;
    }
    this.getValue = this._getValue_unavailable;
    this.setValue = this._setValue_unavailable;
    if (!targetObject) {
      console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + ".");
      return;
    }
    if (objectName) {
      let objectIndex = parsedPath.objectIndex;
      switch (objectName) {
        case "materials":
          if (!targetObject.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!targetObject.material.materials) {
            console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this);
            return;
          }
          targetObject = targetObject.material.materials;
          break;
        case "bones":
          if (!targetObject.skeleton) {
            console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this);
            return;
          }
          targetObject = targetObject.skeleton.bones;
          for (let i2 = 0; i2 < targetObject.length; i2++) {
            if (targetObject[i2].name === objectIndex) {
              objectIndex = i2;
              break;
            }
          }
          break;
        case "map":
          if ("map" in targetObject) {
            targetObject = targetObject.map;
            break;
          }
          if (!targetObject.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!targetObject.material.map) {
            console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this);
            return;
          }
          targetObject = targetObject.material.map;
          break;
        default:
          if (targetObject[objectName] === void 0) {
            console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this);
            return;
          }
          targetObject = targetObject[objectName];
      }
      if (objectIndex !== void 0) {
        if (targetObject[objectIndex] === void 0) {
          console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject);
          return;
        }
        targetObject = targetObject[objectIndex];
      }
    }
    const nodeProperty = targetObject[propertyName];
    if (nodeProperty === void 0) {
      const nodeName = parsedPath.nodeName;
      console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject);
      return;
    }
    let versioning = this.Versioning.None;
    this.targetObject = targetObject;
    if (targetObject.needsUpdate !== void 0) {
      versioning = this.Versioning.NeedsUpdate;
    } else if (targetObject.matrixWorldNeedsUpdate !== void 0) {
      versioning = this.Versioning.MatrixWorldNeedsUpdate;
    }
    let bindingType = this.BindingType.Direct;
    if (propertyIndex !== void 0) {
      if (propertyName === "morphTargetInfluences") {
        if (!targetObject.geometry) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this);
          return;
        }
        if (!targetObject.geometry.morphAttributes) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this);
          return;
        }
        if (targetObject.morphTargetDictionary[propertyIndex] !== void 0) {
          propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
        }
      }
      bindingType = this.BindingType.ArrayElement;
      this.resolvedProperty = nodeProperty;
      this.propertyIndex = propertyIndex;
    } else if (nodeProperty.fromArray !== void 0 && nodeProperty.toArray !== void 0) {
      bindingType = this.BindingType.HasFromToArray;
      this.resolvedProperty = nodeProperty;
    } else if (Array.isArray(nodeProperty)) {
      bindingType = this.BindingType.EntireArray;
      this.resolvedProperty = nodeProperty;
    } else {
      this.propertyName = propertyName;
    }
    this.getValue = this.GetterByBindingType[bindingType];
    this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  }
  unbind() {
    this.node = null;
    this.getValue = this._getValue_unbound;
    this.setValue = this._setValue_unbound;
  }
}
PropertyBinding.Composite = Composite;
PropertyBinding.prototype.BindingType = {
  Direct: 0,
  EntireArray: 1,
  ArrayElement: 2,
  HasFromToArray: 3
};
PropertyBinding.prototype.Versioning = {
  None: 0,
  NeedsUpdate: 1,
  MatrixWorldNeedsUpdate: 2
};
PropertyBinding.prototype.GetterByBindingType = [
  PropertyBinding.prototype._getValue_direct,
  PropertyBinding.prototype._getValue_array,
  PropertyBinding.prototype._getValue_arrayElement,
  PropertyBinding.prototype._getValue_toArray
];
PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  [
    // Direct
    PropertyBinding.prototype._setValue_direct,
    PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
    PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate
  ],
  [
    // EntireArray
    PropertyBinding.prototype._setValue_array,
    PropertyBinding.prototype._setValue_array_setNeedsUpdate,
    PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate
  ],
  [
    // ArrayElement
    PropertyBinding.prototype._setValue_arrayElement,
    PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
    PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate
  ],
  [
    // HasToFromArray
    PropertyBinding.prototype._setValue_fromArray,
    PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
    PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
  ]
];
class AnimationObjectGroup {
  constructor() {
    this.isAnimationObjectGroup = true;
    this.uuid = generateUUID();
    this._objects = Array.prototype.slice.call(arguments);
    this.nCachedObjects_ = 0;
    const indices = {};
    this._indicesByUUID = indices;
    for (let i2 = 0, n2 = arguments.length; i2 !== n2; ++i2) {
      indices[arguments[i2].uuid] = i2;
    }
    this._paths = [];
    this._parsedPaths = [];
    this._bindings = [];
    this._bindingsIndicesByPath = {};
    const scope = this;
    this.stats = {
      objects: {
        get total() {
          return scope._objects.length;
        },
        get inUse() {
          return this.total - scope.nCachedObjects_;
        }
      },
      get bindingsPerObject() {
        return scope._bindings.length;
      }
    };
  }
  add() {
    const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length;
    let knownObject = void 0, nObjects = objects.length, nCachedObjects = this.nCachedObjects_;
    for (let i2 = 0, n2 = arguments.length; i2 !== n2; ++i2) {
      const object = arguments[i2], uuid = object.uuid;
      let index = indicesByUUID[uuid];
      if (index === void 0) {
        index = nObjects++;
        indicesByUUID[uuid] = index;
        objects.push(object);
        for (let j2 = 0, m2 = nBindings; j2 !== m2; ++j2) {
          bindings[j2].push(new PropertyBinding(object, paths[j2], parsedPaths[j2]));
        }
      } else if (index < nCachedObjects) {
        knownObject = objects[index];
        const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex];
        indicesByUUID[lastCachedObject.uuid] = index;
        objects[index] = lastCachedObject;
        indicesByUUID[uuid] = firstActiveIndex;
        objects[firstActiveIndex] = object;
        for (let j2 = 0, m2 = nBindings; j2 !== m2; ++j2) {
          const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex];
          let binding = bindingsForPath[index];
          bindingsForPath[index] = lastCached;
          if (binding === void 0) {
            binding = new PropertyBinding(object, paths[j2], parsedPaths[j2]);
          }
          bindingsForPath[firstActiveIndex] = binding;
        }
      } else if (objects[index] !== knownObject) {
        console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.");
      }
    }
    this.nCachedObjects_ = nCachedObjects;
  }
  remove() {
    const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length;
    let nCachedObjects = this.nCachedObjects_;
    for (let i2 = 0, n2 = arguments.length; i2 !== n2; ++i2) {
      const object = arguments[i2], uuid = object.uuid, index = indicesByUUID[uuid];
      if (index !== void 0 && index >= nCachedObjects) {
        const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex];
        indicesByUUID[firstActiveObject.uuid] = index;
        objects[index] = firstActiveObject;
        indicesByUUID[uuid] = lastCachedIndex;
        objects[lastCachedIndex] = object;
        for (let j2 = 0, m2 = nBindings; j2 !== m2; ++j2) {
          const bindingsForPath = bindings[j2], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index];
          bindingsForPath[index] = firstActive;
          bindingsForPath[lastCachedIndex] = binding;
        }
      }
    }
    this.nCachedObjects_ = nCachedObjects;
  }
  // remove & forget
  uncache() {
    const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length;
    let nCachedObjects = this.nCachedObjects_, nObjects = objects.length;
    for (let i2 = 0, n2 = arguments.length; i2 !== n2; ++i2) {
      const object = arguments[i2], uuid = object.uuid, index = indicesByUUID[uuid];
      if (index !== void 0) {
        delete indicesByUUID[uuid];
        if (index < nCachedObjects) {
          const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex];
          indicesByUUID[lastCachedObject.uuid] = index;
          objects[index] = lastCachedObject;
          indicesByUUID[lastObject.uuid] = firstActiveIndex;
          objects[firstActiveIndex] = lastObject;
          objects.pop();
          for (let j2 = 0, m2 = nBindings; j2 !== m2; ++j2) {
            const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex], last = bindingsForPath[lastIndex];
            bindingsForPath[index] = lastCached;
            bindingsForPath[firstActiveIndex] = last;
            bindingsForPath.pop();
          }
        } else {
          const lastIndex = --nObjects, lastObject = objects[lastIndex];
          if (lastIndex > 0) {
            indicesByUUID[lastObject.uuid] = index;
          }
          objects[index] = lastObject;
          objects.pop();
          for (let j2 = 0, m2 = nBindings; j2 !== m2; ++j2) {
            const bindingsForPath = bindings[j2];
            bindingsForPath[index] = bindingsForPath[lastIndex];
            bindingsForPath.pop();
          }
        }
      }
    }
    this.nCachedObjects_ = nCachedObjects;
  }
  // Internal interface used by befriended PropertyBinding.Composite:
  subscribe_(path, parsedPath) {
    const indicesByPath = this._bindingsIndicesByPath;
    let index = indicesByPath[path];
    const bindings = this._bindings;
    if (index !== void 0) return bindings[index];
    const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects);
    index = bindings.length;
    indicesByPath[path] = index;
    paths.push(path);
    parsedPaths.push(parsedPath);
    bindings.push(bindingsForPath);
    for (let i2 = nCachedObjects, n2 = objects.length; i2 !== n2; ++i2) {
      const object = objects[i2];
      bindingsForPath[i2] = new PropertyBinding(object, path, parsedPath);
    }
    return bindingsForPath;
  }
  unsubscribe_(path) {
    const indicesByPath = this._bindingsIndicesByPath, index = indicesByPath[path];
    if (index !== void 0) {
      const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex];
      indicesByPath[lastBindingsPath] = index;
      bindings[index] = lastBindings;
      bindings.pop();
      parsedPaths[index] = parsedPaths[lastBindingsIndex];
      parsedPaths.pop();
      paths[index] = paths[lastBindingsIndex];
      paths.pop();
    }
  }
}
class AnimationAction {
  constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
    this._mixer = mixer;
    this._clip = clip;
    this._localRoot = localRoot;
    this.blendMode = blendMode;
    const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks);
    const interpolantSettings = {
      endingStart: ZeroCurvatureEnding,
      endingEnd: ZeroCurvatureEnding
    };
    for (let i2 = 0; i2 !== nTracks; ++i2) {
      const interpolant = tracks[i2].createInterpolant(null);
      interpolants[i2] = interpolant;
      interpolant.settings = interpolantSettings;
    }
    this._interpolantSettings = interpolantSettings;
    this._interpolants = interpolants;
    this._propertyBindings = new Array(nTracks);
    this._cacheIndex = null;
    this._byClipCacheIndex = null;
    this._timeScaleInterpolant = null;
    this._weightInterpolant = null;
    this.loop = LoopRepeat;
    this._loopCount = -1;
    this._startTime = null;
    this.time = 0;
    this.timeScale = 1;
    this._effectiveTimeScale = 1;
    this.weight = 1;
    this._effectiveWeight = 1;
    this.repetitions = Infinity;
    this.paused = false;
    this.enabled = true;
    this.clampWhenFinished = false;
    this.zeroSlopeAtStart = true;
    this.zeroSlopeAtEnd = true;
  }
  // State & Scheduling
  play() {
    this._mixer._activateAction(this);
    return this;
  }
  stop() {
    this._mixer._deactivateAction(this);
    return this.reset();
  }
  reset() {
    this.paused = false;
    this.enabled = true;
    this.time = 0;
    this._loopCount = -1;
    this._startTime = null;
    return this.stopFading().stopWarping();
  }
  isRunning() {
    return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  }
  // return true when play has been called
  isScheduled() {
    return this._mixer._isActiveAction(this);
  }
  startAt(time) {
    this._startTime = time;
    return this;
  }
  setLoop(mode2, repetitions) {
    this.loop = mode2;
    this.repetitions = repetitions;
    return this;
  }
  // Weight
  // set the weight stopping any scheduled fading
  // although .enabled = false yields an effective weight of zero, this
  // method does *not* change .enabled, because it would be confusing
  setEffectiveWeight(weight) {
    this.weight = weight;
    this._effectiveWeight = this.enabled ? weight : 0;
    return this.stopFading();
  }
  // return the weight considering fading and .enabled
  getEffectiveWeight() {
    return this._effectiveWeight;
  }
  fadeIn(duration) {
    return this._scheduleFading(duration, 0, 1);
  }
  fadeOut(duration) {
    return this._scheduleFading(duration, 1, 0);
  }
  crossFadeFrom(fadeOutAction, duration, warp) {
    fadeOutAction.fadeOut(duration);
    this.fadeIn(duration);
    if (warp) {
      const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration;
      fadeOutAction.warp(1, startEndRatio, duration);
      this.warp(endStartRatio, 1, duration);
    }
    return this;
  }
  crossFadeTo(fadeInAction, duration, warp) {
    return fadeInAction.crossFadeFrom(this, duration, warp);
  }
  stopFading() {
    const weightInterpolant = this._weightInterpolant;
    if (weightInterpolant !== null) {
      this._weightInterpolant = null;
      this._mixer._takeBackControlInterpolant(weightInterpolant);
    }
    return this;
  }
  // Time Scale Control
  // set the time scale stopping any scheduled warping
  // although .paused = true yields an effective time scale of zero, this
  // method does *not* change .paused, because it would be confusing
  setEffectiveTimeScale(timeScale) {
    this.timeScale = timeScale;
    this._effectiveTimeScale = this.paused ? 0 : timeScale;
    return this.stopWarping();
  }
  // return the time scale considering warping and .paused
  getEffectiveTimeScale() {
    return this._effectiveTimeScale;
  }
  setDuration(duration) {
    this.timeScale = this._clip.duration / duration;
    return this.stopWarping();
  }
  syncWith(action2) {
    this.time = action2.time;
    this.timeScale = action2.timeScale;
    return this.stopWarping();
  }
  halt(duration) {
    return this.warp(this._effectiveTimeScale, 0, duration);
  }
  warp(startTimeScale, endTimeScale, duration) {
    const mixer = this._mixer, now2 = mixer.time, timeScale = this.timeScale;
    let interpolant = this._timeScaleInterpolant;
    if (interpolant === null) {
      interpolant = mixer._lendControlInterpolant();
      this._timeScaleInterpolant = interpolant;
    }
    const times = interpolant.parameterPositions, values = interpolant.sampleValues;
    times[0] = now2;
    times[1] = now2 + duration;
    values[0] = startTimeScale / timeScale;
    values[1] = endTimeScale / timeScale;
    return this;
  }
  stopWarping() {
    const timeScaleInterpolant = this._timeScaleInterpolant;
    if (timeScaleInterpolant !== null) {
      this._timeScaleInterpolant = null;
      this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
    }
    return this;
  }
  // Object Accessors
  getMixer() {
    return this._mixer;
  }
  getClip() {
    return this._clip;
  }
  getRoot() {
    return this._localRoot || this._mixer._root;
  }
  // Interna
  _update(time, deltaTime, timeDirection, accuIndex) {
    if (!this.enabled) {
      this._updateWeight(time);
      return;
    }
    const startTime = this._startTime;
    if (startTime !== null) {
      const timeRunning = (time - startTime) * timeDirection;
      if (timeRunning < 0 || timeDirection === 0) {
        deltaTime = 0;
      } else {
        this._startTime = null;
        deltaTime = timeDirection * timeRunning;
      }
    }
    deltaTime *= this._updateTimeScale(time);
    const clipTime = this._updateTime(deltaTime);
    const weight = this._updateWeight(time);
    if (weight > 0) {
      const interpolants = this._interpolants;
      const propertyMixers = this._propertyBindings;
      switch (this.blendMode) {
        case AdditiveAnimationBlendMode:
          for (let j2 = 0, m2 = interpolants.length; j2 !== m2; ++j2) {
            interpolants[j2].evaluate(clipTime);
            propertyMixers[j2].accumulateAdditive(weight);
          }
          break;
        case NormalAnimationBlendMode:
        default:
          for (let j2 = 0, m2 = interpolants.length; j2 !== m2; ++j2) {
            interpolants[j2].evaluate(clipTime);
            propertyMixers[j2].accumulate(accuIndex, weight);
          }
      }
    }
  }
  _updateWeight(time) {
    let weight = 0;
    if (this.enabled) {
      weight = this.weight;
      const interpolant = this._weightInterpolant;
      if (interpolant !== null) {
        const interpolantValue = interpolant.evaluate(time)[0];
        weight *= interpolantValue;
        if (time > interpolant.parameterPositions[1]) {
          this.stopFading();
          if (interpolantValue === 0) {
            this.enabled = false;
          }
        }
      }
    }
    this._effectiveWeight = weight;
    return weight;
  }
  _updateTimeScale(time) {
    let timeScale = 0;
    if (!this.paused) {
      timeScale = this.timeScale;
      const interpolant = this._timeScaleInterpolant;
      if (interpolant !== null) {
        const interpolantValue = interpolant.evaluate(time)[0];
        timeScale *= interpolantValue;
        if (time > interpolant.parameterPositions[1]) {
          this.stopWarping();
          if (timeScale === 0) {
            this.paused = true;
          } else {
            this.timeScale = timeScale;
          }
        }
      }
    }
    this._effectiveTimeScale = timeScale;
    return timeScale;
  }
  _updateTime(deltaTime) {
    const duration = this._clip.duration;
    const loop = this.loop;
    let time = this.time + deltaTime;
    let loopCount = this._loopCount;
    const pingPong = loop === LoopPingPong;
    if (deltaTime === 0) {
      if (loopCount === -1) return time;
      return pingPong && (loopCount & 1) === 1 ? duration - time : time;
    }
    if (loop === LoopOnce) {
      if (loopCount === -1) {
        this._loopCount = 0;
        this._setEndings(true, true, false);
      }
      handle_stop: {
        if (time >= duration) {
          time = duration;
        } else if (time < 0) {
          time = 0;
        } else {
          this.time = time;
          break handle_stop;
        }
        if (this.clampWhenFinished) this.paused = true;
        else this.enabled = false;
        this.time = time;
        this._mixer.dispatchEvent({
          type: "finished",
          action: this,
          direction: deltaTime < 0 ? -1 : 1
        });
      }
    } else {
      if (loopCount === -1) {
        if (deltaTime >= 0) {
          loopCount = 0;
          this._setEndings(true, this.repetitions === 0, pingPong);
        } else {
          this._setEndings(this.repetitions === 0, true, pingPong);
        }
      }
      if (time >= duration || time < 0) {
        const loopDelta = Math.floor(time / duration);
        time -= duration * loopDelta;
        loopCount += Math.abs(loopDelta);
        const pending = this.repetitions - loopCount;
        if (pending <= 0) {
          if (this.clampWhenFinished) this.paused = true;
          else this.enabled = false;
          time = deltaTime > 0 ? duration : 0;
          this.time = time;
          this._mixer.dispatchEvent({
            type: "finished",
            action: this,
            direction: deltaTime > 0 ? 1 : -1
          });
        } else {
          if (pending === 1) {
            const atStart = deltaTime < 0;
            this._setEndings(atStart, !atStart, pingPong);
          } else {
            this._setEndings(false, false, pingPong);
          }
          this._loopCount = loopCount;
          this.time = time;
          this._mixer.dispatchEvent({
            type: "loop",
            action: this,
            loopDelta
          });
        }
      } else {
        this.time = time;
      }
      if (pingPong && (loopCount & 1) === 1) {
        return duration - time;
      }
    }
    return time;
  }
  _setEndings(atStart, atEnd, pingPong) {
    const settings = this._interpolantSettings;
    if (pingPong) {
      settings.endingStart = ZeroSlopeEnding;
      settings.endingEnd = ZeroSlopeEnding;
    } else {
      if (atStart) {
        settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
      } else {
        settings.endingStart = WrapAroundEnding;
      }
      if (atEnd) {
        settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
      } else {
        settings.endingEnd = WrapAroundEnding;
      }
    }
  }
  _scheduleFading(duration, weightNow, weightThen) {
    const mixer = this._mixer, now2 = mixer.time;
    let interpolant = this._weightInterpolant;
    if (interpolant === null) {
      interpolant = mixer._lendControlInterpolant();
      this._weightInterpolant = interpolant;
    }
    const times = interpolant.parameterPositions, values = interpolant.sampleValues;
    times[0] = now2;
    values[0] = weightNow;
    times[1] = now2 + duration;
    values[1] = weightThen;
    return this;
  }
}
const _controlInterpolantsResultBuffer = new Float32Array(1);
class AnimationMixer extends EventDispatcher$1 {
  constructor(root) {
    super();
    this._root = root;
    this._initMemoryManager();
    this._accuIndex = 0;
    this.time = 0;
    this.timeScale = 1;
  }
  _bindAction(action2, prototypeAction) {
    const root = action2._localRoot || this._root, tracks = action2._clip.tracks, nTracks = tracks.length, bindings = action2._propertyBindings, interpolants = action2._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName;
    let bindingsByName = bindingsByRoot[rootUuid];
    if (bindingsByName === void 0) {
      bindingsByName = {};
      bindingsByRoot[rootUuid] = bindingsByName;
    }
    for (let i2 = 0; i2 !== nTracks; ++i2) {
      const track = tracks[i2], trackName = track.name;
      let binding = bindingsByName[trackName];
      if (binding !== void 0) {
        ++binding.referenceCount;
        bindings[i2] = binding;
      } else {
        binding = bindings[i2];
        if (binding !== void 0) {
          if (binding._cacheIndex === null) {
            ++binding.referenceCount;
            this._addInactiveBinding(binding, rootUuid, trackName);
          }
          continue;
        }
        const path = prototypeAction && prototypeAction._propertyBindings[i2].binding.parsedPath;
        binding = new PropertyMixer(
          PropertyBinding.create(root, trackName, path),
          track.ValueTypeName,
          track.getValueSize()
        );
        ++binding.referenceCount;
        this._addInactiveBinding(binding, rootUuid, trackName);
        bindings[i2] = binding;
      }
      interpolants[i2].resultBuffer = binding.buffer;
    }
  }
  _activateAction(action2) {
    if (!this._isActiveAction(action2)) {
      if (action2._cacheIndex === null) {
        const rootUuid = (action2._localRoot || this._root).uuid, clipUuid = action2._clip.uuid, actionsForClip = this._actionsByClip[clipUuid];
        this._bindAction(
          action2,
          actionsForClip && actionsForClip.knownActions[0]
        );
        this._addInactiveAction(action2, clipUuid, rootUuid);
      }
      const bindings = action2._propertyBindings;
      for (let i2 = 0, n2 = bindings.length; i2 !== n2; ++i2) {
        const binding = bindings[i2];
        if (binding.useCount++ === 0) {
          this._lendBinding(binding);
          binding.saveOriginalState();
        }
      }
      this._lendAction(action2);
    }
  }
  _deactivateAction(action2) {
    if (this._isActiveAction(action2)) {
      const bindings = action2._propertyBindings;
      for (let i2 = 0, n2 = bindings.length; i2 !== n2; ++i2) {
        const binding = bindings[i2];
        if (--binding.useCount === 0) {
          binding.restoreOriginalState();
          this._takeBackBinding(binding);
        }
      }
      this._takeBackAction(action2);
    }
  }
  // Memory manager
  _initMemoryManager() {
    this._actions = [];
    this._nActiveActions = 0;
    this._actionsByClip = {};
    this._bindings = [];
    this._nActiveBindings = 0;
    this._bindingsByRootAndName = {};
    this._controlInterpolants = [];
    this._nActiveControlInterpolants = 0;
    const scope = this;
    this.stats = {
      actions: {
        get total() {
          return scope._actions.length;
        },
        get inUse() {
          return scope._nActiveActions;
        }
      },
      bindings: {
        get total() {
          return scope._bindings.length;
        },
        get inUse() {
          return scope._nActiveBindings;
        }
      },
      controlInterpolants: {
        get total() {
          return scope._controlInterpolants.length;
        },
        get inUse() {
          return scope._nActiveControlInterpolants;
        }
      }
    };
  }
  // Memory management for AnimationAction objects
  _isActiveAction(action2) {
    const index = action2._cacheIndex;
    return index !== null && index < this._nActiveActions;
  }
  _addInactiveAction(action2, clipUuid, rootUuid) {
    const actions = this._actions, actionsByClip = this._actionsByClip;
    let actionsForClip = actionsByClip[clipUuid];
    if (actionsForClip === void 0) {
      actionsForClip = {
        knownActions: [action2],
        actionByRoot: {}
      };
      action2._byClipCacheIndex = 0;
      actionsByClip[clipUuid] = actionsForClip;
    } else {
      const knownActions = actionsForClip.knownActions;
      action2._byClipCacheIndex = knownActions.length;
      knownActions.push(action2);
    }
    action2._cacheIndex = actions.length;
    actions.push(action2);
    actionsForClip.actionByRoot[rootUuid] = action2;
  }
  _removeInactiveAction(action2) {
    const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action2._cacheIndex;
    lastInactiveAction._cacheIndex = cacheIndex;
    actions[cacheIndex] = lastInactiveAction;
    actions.pop();
    action2._cacheIndex = null;
    const clipUuid = action2._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action2._byClipCacheIndex;
    lastKnownAction._byClipCacheIndex = byClipCacheIndex;
    knownActionsForClip[byClipCacheIndex] = lastKnownAction;
    knownActionsForClip.pop();
    action2._byClipCacheIndex = null;
    const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action2._localRoot || this._root).uuid;
    delete actionByRoot[rootUuid];
    if (knownActionsForClip.length === 0) {
      delete actionsByClip[clipUuid];
    }
    this._removeInactiveBindingsForAction(action2);
  }
  _removeInactiveBindingsForAction(action2) {
    const bindings = action2._propertyBindings;
    for (let i2 = 0, n2 = bindings.length; i2 !== n2; ++i2) {
      const binding = bindings[i2];
      if (--binding.referenceCount === 0) {
        this._removeInactiveBinding(binding);
      }
    }
  }
  _lendAction(action2) {
    const actions = this._actions, prevIndex = action2._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex];
    action2._cacheIndex = lastActiveIndex;
    actions[lastActiveIndex] = action2;
    firstInactiveAction._cacheIndex = prevIndex;
    actions[prevIndex] = firstInactiveAction;
  }
  _takeBackAction(action2) {
    const actions = this._actions, prevIndex = action2._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex];
    action2._cacheIndex = firstInactiveIndex;
    actions[firstInactiveIndex] = action2;
    lastActiveAction._cacheIndex = prevIndex;
    actions[prevIndex] = lastActiveAction;
  }
  // Memory management for PropertyMixer objects
  _addInactiveBinding(binding, rootUuid, trackName) {
    const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings;
    let bindingByName = bindingsByRoot[rootUuid];
    if (bindingByName === void 0) {
      bindingByName = {};
      bindingsByRoot[rootUuid] = bindingByName;
    }
    bindingByName[trackName] = binding;
    binding._cacheIndex = bindings.length;
    bindings.push(binding);
  }
  _removeInactiveBinding(binding) {
    const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex;
    lastInactiveBinding._cacheIndex = cacheIndex;
    bindings[cacheIndex] = lastInactiveBinding;
    bindings.pop();
    delete bindingByName[trackName];
    if (Object.keys(bindingByName).length === 0) {
      delete bindingsByRoot[rootUuid];
    }
  }
  _lendBinding(binding) {
    const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex];
    binding._cacheIndex = lastActiveIndex;
    bindings[lastActiveIndex] = binding;
    firstInactiveBinding._cacheIndex = prevIndex;
    bindings[prevIndex] = firstInactiveBinding;
  }
  _takeBackBinding(binding) {
    const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex];
    binding._cacheIndex = firstInactiveIndex;
    bindings[firstInactiveIndex] = binding;
    lastActiveBinding._cacheIndex = prevIndex;
    bindings[prevIndex] = lastActiveBinding;
  }
  // Memory management of Interpolants for weight and time scale
  _lendControlInterpolant() {
    const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++;
    let interpolant = interpolants[lastActiveIndex];
    if (interpolant === void 0) {
      interpolant = new LinearInterpolant(
        new Float32Array(2),
        new Float32Array(2),
        1,
        _controlInterpolantsResultBuffer
      );
      interpolant.__cacheIndex = lastActiveIndex;
      interpolants[lastActiveIndex] = interpolant;
    }
    return interpolant;
  }
  _takeBackControlInterpolant(interpolant) {
    const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex];
    interpolant.__cacheIndex = firstInactiveIndex;
    interpolants[firstInactiveIndex] = interpolant;
    lastActiveInterpolant.__cacheIndex = prevIndex;
    interpolants[prevIndex] = lastActiveInterpolant;
  }
  // return an action for a clip optionally using a custom root target
  // object (this method allocates a lot of dynamic memory in case a
  // previously unknown clip/root combination is specified)
  clipAction(clip, optionalRoot, blendMode) {
    const root = optionalRoot || this._root, rootUuid = root.uuid;
    let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip;
    const clipUuid = clipObject !== null ? clipObject.uuid : clip;
    const actionsForClip = this._actionsByClip[clipUuid];
    let prototypeAction = null;
    if (blendMode === void 0) {
      if (clipObject !== null) {
        blendMode = clipObject.blendMode;
      } else {
        blendMode = NormalAnimationBlendMode;
      }
    }
    if (actionsForClip !== void 0) {
      const existingAction = actionsForClip.actionByRoot[rootUuid];
      if (existingAction !== void 0 && existingAction.blendMode === blendMode) {
        return existingAction;
      }
      prototypeAction = actionsForClip.knownActions[0];
      if (clipObject === null)
        clipObject = prototypeAction._clip;
    }
    if (clipObject === null) return null;
    const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
    this._bindAction(newAction, prototypeAction);
    this._addInactiveAction(newAction, clipUuid, rootUuid);
    return newAction;
  }
  // get an existing action
  existingAction(clip, optionalRoot) {
    const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid];
    if (actionsForClip !== void 0) {
      return actionsForClip.actionByRoot[rootUuid] || null;
    }
    return null;
  }
  // deactivates all previously scheduled actions
  stopAllAction() {
    const actions = this._actions, nActions = this._nActiveActions;
    for (let i2 = nActions - 1; i2 >= 0; --i2) {
      actions[i2].stop();
    }
    return this;
  }
  // advance the time and update apply the animation
  update(deltaTime) {
    deltaTime *= this.timeScale;
    const actions = this._actions, nActions = this._nActiveActions, time = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1;
    for (let i2 = 0; i2 !== nActions; ++i2) {
      const action2 = actions[i2];
      action2._update(time, deltaTime, timeDirection, accuIndex);
    }
    const bindings = this._bindings, nBindings = this._nActiveBindings;
    for (let i2 = 0; i2 !== nBindings; ++i2) {
      bindings[i2].apply(accuIndex);
    }
    return this;
  }
  // Allows you to seek to a specific time in an animation.
  setTime(timeInSeconds) {
    this.time = 0;
    for (let i2 = 0; i2 < this._actions.length; i2++) {
      this._actions[i2].time = 0;
    }
    return this.update(timeInSeconds);
  }
  // return this mixer's root target object
  getRoot() {
    return this._root;
  }
  // free all resources specific to a particular clip
  uncacheClip(clip) {
    const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid];
    if (actionsForClip !== void 0) {
      const actionsToRemove = actionsForClip.knownActions;
      for (let i2 = 0, n2 = actionsToRemove.length; i2 !== n2; ++i2) {
        const action2 = actionsToRemove[i2];
        this._deactivateAction(action2);
        const cacheIndex = action2._cacheIndex, lastInactiveAction = actions[actions.length - 1];
        action2._cacheIndex = null;
        action2._byClipCacheIndex = null;
        lastInactiveAction._cacheIndex = cacheIndex;
        actions[cacheIndex] = lastInactiveAction;
        actions.pop();
        this._removeInactiveBindingsForAction(action2);
      }
      delete actionsByClip[clipUuid];
    }
  }
  // free all resources specific to a particular root target object
  uncacheRoot(root) {
    const rootUuid = root.uuid, actionsByClip = this._actionsByClip;
    for (const clipUuid in actionsByClip) {
      const actionByRoot = actionsByClip[clipUuid].actionByRoot, action2 = actionByRoot[rootUuid];
      if (action2 !== void 0) {
        this._deactivateAction(action2);
        this._removeInactiveAction(action2);
      }
    }
    const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid];
    if (bindingByName !== void 0) {
      for (const trackName in bindingByName) {
        const binding = bindingByName[trackName];
        binding.restoreOriginalState();
        this._removeInactiveBinding(binding);
      }
    }
  }
  // remove a targeted clip from the cache
  uncacheAction(clip, optionalRoot) {
    const action2 = this.existingAction(clip, optionalRoot);
    if (action2 !== null) {
      this._deactivateAction(action2);
      this._removeInactiveAction(action2);
    }
  }
}
class Uniform {
  constructor(value) {
    this.value = value;
  }
  clone() {
    return new Uniform(this.value.clone === void 0 ? this.value : this.value.clone());
  }
}
let _id$2 = 0;
class UniformsGroup extends EventDispatcher$1 {
  constructor() {
    super();
    this.isUniformsGroup = true;
    Object.defineProperty(this, "id", { value: _id$2++ });
    this.name = "";
    this.usage = StaticDrawUsage;
    this.uniforms = [];
  }
  add(uniform) {
    this.uniforms.push(uniform);
    return this;
  }
  remove(uniform) {
    const index = this.uniforms.indexOf(uniform);
    if (index !== -1) this.uniforms.splice(index, 1);
    return this;
  }
  setName(name) {
    this.name = name;
    return this;
  }
  setUsage(value) {
    this.usage = value;
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
    return this;
  }
  copy(source) {
    this.name = source.name;
    this.usage = source.usage;
    const uniformsSource = source.uniforms;
    this.uniforms.length = 0;
    for (let i2 = 0, l2 = uniformsSource.length; i2 < l2; i2++) {
      const uniforms = Array.isArray(uniformsSource[i2]) ? uniformsSource[i2] : [uniformsSource[i2]];
      for (let j2 = 0; j2 < uniforms.length; j2++) {
        this.uniforms.push(uniforms[j2].clone());
      }
    }
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
class InstancedInterleavedBuffer extends InterleavedBuffer {
  constructor(array, stride, meshPerAttribute = 1) {
    super(array, stride);
    this.isInstancedInterleavedBuffer = true;
    this.meshPerAttribute = meshPerAttribute;
  }
  copy(source) {
    super.copy(source);
    this.meshPerAttribute = source.meshPerAttribute;
    return this;
  }
  clone(data) {
    const ib = super.clone(data);
    ib.meshPerAttribute = this.meshPerAttribute;
    return ib;
  }
  toJSON(data) {
    const json3 = super.toJSON(data);
    json3.isInstancedInterleavedBuffer = true;
    json3.meshPerAttribute = this.meshPerAttribute;
    return json3;
  }
}
class GLBufferAttribute {
  constructor(buffer, type, itemSize, elementSize, count) {
    this.isGLBufferAttribute = true;
    this.name = "";
    this.buffer = buffer;
    this.type = type;
    this.itemSize = itemSize;
    this.elementSize = elementSize;
    this.count = count;
    this.version = 0;
  }
  set needsUpdate(value) {
    if (value === true) this.version++;
  }
  setBuffer(buffer) {
    this.buffer = buffer;
    return this;
  }
  setType(type, elementSize) {
    this.type = type;
    this.elementSize = elementSize;
    return this;
  }
  setItemSize(itemSize) {
    this.itemSize = itemSize;
    return this;
  }
  setCount(count) {
    this.count = count;
    return this;
  }
}
const _matrix = /* @__PURE__ */ new Matrix4();
class Raycaster {
  constructor(origin, direction, near = 0, far = Infinity) {
    this.ray = new Ray(origin, direction);
    this.near = near;
    this.far = far;
    this.camera = null;
    this.layers = new Layers();
    this.params = {
      Mesh: {},
      Line: { threshold: 1 },
      LOD: {},
      Points: { threshold: 1 },
      Sprite: {}
    };
  }
  set(origin, direction) {
    this.ray.set(origin, direction);
  }
  setFromCamera(coords, camera) {
    if (camera.isPerspectiveCamera) {
      this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
      this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
      this.camera = camera;
    } else if (camera.isOrthographicCamera) {
      this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera);
      this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
      this.camera = camera;
    } else {
      console.error("THREE.Raycaster: Unsupported camera type: " + camera.type);
    }
  }
  setFromXRController(controller) {
    _matrix.identity().extractRotation(controller.matrixWorld);
    this.ray.origin.setFromMatrixPosition(controller.matrixWorld);
    this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix);
    return this;
  }
  intersectObject(object, recursive = true, intersects2 = []) {
    intersect(object, this, intersects2, recursive);
    intersects2.sort(ascSort);
    return intersects2;
  }
  intersectObjects(objects, recursive = true, intersects2 = []) {
    for (let i2 = 0, l2 = objects.length; i2 < l2; i2++) {
      intersect(objects[i2], this, intersects2, recursive);
    }
    intersects2.sort(ascSort);
    return intersects2;
  }
}
function ascSort(a3, b2) {
  return a3.distance - b2.distance;
}
function intersect(object, raycaster, intersects2, recursive) {
  let propagate = true;
  if (object.layers.test(raycaster.layers)) {
    const result = object.raycast(raycaster, intersects2);
    if (result === false) propagate = false;
  }
  if (propagate === true && recursive === true) {
    const children = object.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      intersect(children[i2], raycaster, intersects2, true);
    }
  }
}
class Spherical {
  constructor(radius = 1, phi = 0, theta = 0) {
    this.radius = radius;
    this.phi = phi;
    this.theta = theta;
    return this;
  }
  set(radius, phi, theta) {
    this.radius = radius;
    this.phi = phi;
    this.theta = theta;
    return this;
  }
  copy(other) {
    this.radius = other.radius;
    this.phi = other.phi;
    this.theta = other.theta;
    return this;
  }
  // restrict phi to be between EPS and PI-EPS
  makeSafe() {
    const EPS = 1e-6;
    this.phi = clamp(this.phi, EPS, Math.PI - EPS);
    return this;
  }
  setFromVector3(v5) {
    return this.setFromCartesianCoords(v5.x, v5.y, v5.z);
  }
  setFromCartesianCoords(x, y2, z2) {
    this.radius = Math.sqrt(x * x + y2 * y2 + z2 * z2);
    if (this.radius === 0) {
      this.theta = 0;
      this.phi = 0;
    } else {
      this.theta = Math.atan2(x, z2);
      this.phi = Math.acos(clamp(y2 / this.radius, -1, 1));
    }
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
class Cylindrical {
  constructor(radius = 1, theta = 0, y2 = 0) {
    this.radius = radius;
    this.theta = theta;
    this.y = y2;
    return this;
  }
  set(radius, theta, y2) {
    this.radius = radius;
    this.theta = theta;
    this.y = y2;
    return this;
  }
  copy(other) {
    this.radius = other.radius;
    this.theta = other.theta;
    this.y = other.y;
    return this;
  }
  setFromVector3(v5) {
    return this.setFromCartesianCoords(v5.x, v5.y, v5.z);
  }
  setFromCartesianCoords(x, y2, z2) {
    this.radius = Math.sqrt(x * x + z2 * z2);
    this.theta = Math.atan2(x, z2);
    this.y = y2;
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
class Matrix2 {
  constructor(n11, n12, n21, n22) {
    Matrix2.prototype.isMatrix2 = true;
    this.elements = [
      1,
      0,
      0,
      1
    ];
    if (n11 !== void 0) {
      this.set(n11, n12, n21, n22);
    }
  }
  identity() {
    this.set(
      1,
      0,
      0,
      1
    );
    return this;
  }
  fromArray(array, offset = 0) {
    for (let i2 = 0; i2 < 4; i2++) {
      this.elements[i2] = array[i2 + offset];
    }
    return this;
  }
  set(n11, n12, n21, n22) {
    const te2 = this.elements;
    te2[0] = n11;
    te2[2] = n12;
    te2[1] = n21;
    te2[3] = n22;
    return this;
  }
}
const _vector$4 = /* @__PURE__ */ new Vector2();
class Box2 {
  constructor(min = new Vector2(Infinity, Infinity), max2 = new Vector2(-Infinity, -Infinity)) {
    this.isBox2 = true;
    this.min = min;
    this.max = max2;
  }
  set(min, max2) {
    this.min.copy(min);
    this.max.copy(max2);
    return this;
  }
  setFromPoints(points) {
    this.makeEmpty();
    for (let i2 = 0, il = points.length; i2 < il; i2++) {
      this.expandByPoint(points[i2]);
    }
    return this;
  }
  setFromCenterAndSize(center, size) {
    const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
    this.min.copy(center).sub(halfSize);
    this.max.copy(center).add(halfSize);
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(box) {
    this.min.copy(box.min);
    this.max.copy(box.max);
    return this;
  }
  makeEmpty() {
    this.min.x = this.min.y = Infinity;
    this.max.x = this.max.y = -Infinity;
    return this;
  }
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y;
  }
  getCenter(target) {
    return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  getSize(target) {
    return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  }
  expandByPoint(point) {
    this.min.min(point);
    this.max.max(point);
    return this;
  }
  expandByVector(vector) {
    this.min.sub(vector);
    this.max.add(vector);
    return this;
  }
  expandByScalar(scalar) {
    this.min.addScalar(-scalar);
    this.max.addScalar(scalar);
    return this;
  }
  containsPoint(point) {
    return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y;
  }
  containsBox(box) {
    return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  }
  getParameter(point, target) {
    return target.set(
      (point.x - this.min.x) / (this.max.x - this.min.x),
      (point.y - this.min.y) / (this.max.y - this.min.y)
    );
  }
  intersectsBox(box) {
    return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y;
  }
  clampPoint(point, target) {
    return target.copy(point).clamp(this.min, this.max);
  }
  distanceToPoint(point) {
    return this.clampPoint(point, _vector$4).distanceTo(point);
  }
  intersect(box) {
    this.min.max(box.min);
    this.max.min(box.max);
    if (this.isEmpty()) this.makeEmpty();
    return this;
  }
  union(box) {
    this.min.min(box.min);
    this.max.max(box.max);
    return this;
  }
  translate(offset) {
    this.min.add(offset);
    this.max.add(offset);
    return this;
  }
  equals(box) {
    return box.min.equals(this.min) && box.max.equals(this.max);
  }
}
const _startP = /* @__PURE__ */ new Vector3();
const _startEnd = /* @__PURE__ */ new Vector3();
class Line3 {
  constructor(start = new Vector3(), end = new Vector3()) {
    this.start = start;
    this.end = end;
  }
  set(start, end) {
    this.start.copy(start);
    this.end.copy(end);
    return this;
  }
  copy(line) {
    this.start.copy(line.start);
    this.end.copy(line.end);
    return this;
  }
  getCenter(target) {
    return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  }
  delta(target) {
    return target.subVectors(this.end, this.start);
  }
  distanceSq() {
    return this.start.distanceToSquared(this.end);
  }
  distance() {
    return this.start.distanceTo(this.end);
  }
  at(t2, target) {
    return this.delta(target).multiplyScalar(t2).add(this.start);
  }
  closestPointToPointParameter(point, clampToLine) {
    _startP.subVectors(point, this.start);
    _startEnd.subVectors(this.end, this.start);
    const startEnd2 = _startEnd.dot(_startEnd);
    const startEnd_startP = _startEnd.dot(_startP);
    let t2 = startEnd_startP / startEnd2;
    if (clampToLine) {
      t2 = clamp(t2, 0, 1);
    }
    return t2;
  }
  closestPointToPoint(point, clampToLine, target) {
    const t2 = this.closestPointToPointParameter(point, clampToLine);
    return this.delta(target).multiplyScalar(t2).add(this.start);
  }
  applyMatrix4(matrix) {
    this.start.applyMatrix4(matrix);
    this.end.applyMatrix4(matrix);
    return this;
  }
  equals(line) {
    return line.start.equals(this.start) && line.end.equals(this.end);
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const _vector$3 = /* @__PURE__ */ new Vector3();
class SpotLightHelper extends Object3D {
  constructor(light, color) {
    super();
    this.light = light;
    this.matrixAutoUpdate = false;
    this.color = color;
    this.type = "SpotLightHelper";
    const geometry = new BufferGeometry();
    const positions = [
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1,
      0,
      1,
      0,
      0,
      0,
      -1,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      0,
      0,
      0,
      -1,
      1
    ];
    for (let i2 = 0, j2 = 1, l2 = 32; i2 < l2; i2++, j2++) {
      const p1 = i2 / l2 * Math.PI * 2;
      const p2 = j2 / l2 * Math.PI * 2;
      positions.push(
        Math.cos(p1),
        Math.sin(p1),
        1,
        Math.cos(p2),
        Math.sin(p2),
        1
      );
    }
    geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
    const material = new LineBasicMaterial({ fog: false, toneMapped: false });
    this.cone = new LineSegments(geometry, material);
    this.add(this.cone);
    this.update();
  }
  dispose() {
    this.cone.geometry.dispose();
    this.cone.material.dispose();
  }
  update() {
    this.light.updateWorldMatrix(true, false);
    this.light.target.updateWorldMatrix(true, false);
    if (this.parent) {
      this.parent.updateWorldMatrix(true);
      this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld);
    } else {
      this.matrix.copy(this.light.matrixWorld);
    }
    this.matrixWorld.copy(this.light.matrixWorld);
    const coneLength = this.light.distance ? this.light.distance : 1e3;
    const coneWidth = coneLength * Math.tan(this.light.angle);
    this.cone.scale.set(coneWidth, coneWidth, coneLength);
    _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
    this.cone.lookAt(_vector$3);
    if (this.color !== void 0) {
      this.cone.material.color.set(this.color);
    } else {
      this.cone.material.color.copy(this.light.color);
    }
  }
}
const _vector$2 = /* @__PURE__ */ new Vector3();
const _boneMatrix = /* @__PURE__ */ new Matrix4();
const _matrixWorldInv = /* @__PURE__ */ new Matrix4();
class SkeletonHelper extends LineSegments {
  constructor(object) {
    const bones = getBoneList(object);
    const geometry = new BufferGeometry();
    const vertices = [];
    const colors = [];
    const color1 = new Color(0, 0, 1);
    const color2 = new Color(0, 1, 0);
    for (let i2 = 0; i2 < bones.length; i2++) {
      const bone = bones[i2];
      if (bone.parent && bone.parent.isBone) {
        vertices.push(0, 0, 0);
        vertices.push(0, 0, 0);
        colors.push(color1.r, color1.g, color1.b);
        colors.push(color2.r, color2.g, color2.b);
      }
    }
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true });
    super(geometry, material);
    this.isSkeletonHelper = true;
    this.type = "SkeletonHelper";
    this.root = object;
    this.bones = bones;
    this.matrix = object.matrixWorld;
    this.matrixAutoUpdate = false;
  }
  updateMatrixWorld(force) {
    const bones = this.bones;
    const geometry = this.geometry;
    const position = geometry.getAttribute("position");
    _matrixWorldInv.copy(this.root.matrixWorld).invert();
    for (let i2 = 0, j2 = 0; i2 < bones.length; i2++) {
      const bone = bones[i2];
      if (bone.parent && bone.parent.isBone) {
        _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
        _vector$2.setFromMatrixPosition(_boneMatrix);
        position.setXYZ(j2, _vector$2.x, _vector$2.y, _vector$2.z);
        _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
        _vector$2.setFromMatrixPosition(_boneMatrix);
        position.setXYZ(j2 + 1, _vector$2.x, _vector$2.y, _vector$2.z);
        j2 += 2;
      }
    }
    geometry.getAttribute("position").needsUpdate = true;
    super.updateMatrixWorld(force);
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
function getBoneList(object) {
  const boneList = [];
  if (object.isBone === true) {
    boneList.push(object);
  }
  for (let i2 = 0; i2 < object.children.length; i2++) {
    boneList.push.apply(boneList, getBoneList(object.children[i2]));
  }
  return boneList;
}
class PointLightHelper extends Mesh {
  constructor(light, sphereSize, color) {
    const geometry = new SphereGeometry(sphereSize, 4, 2);
    const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false });
    super(geometry, material);
    this.light = light;
    this.color = color;
    this.type = "PointLightHelper";
    this.matrix = this.light.matrixWorld;
    this.matrixAutoUpdate = false;
    this.update();
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
  update() {
    this.light.updateWorldMatrix(true, false);
    if (this.color !== void 0) {
      this.material.color.set(this.color);
    } else {
      this.material.color.copy(this.light.color);
    }
  }
}
const _vector$1 = /* @__PURE__ */ new Vector3();
const _color1 = /* @__PURE__ */ new Color();
const _color2 = /* @__PURE__ */ new Color();
class HemisphereLightHelper extends Object3D {
  constructor(light, size, color) {
    super();
    this.light = light;
    this.matrix = light.matrixWorld;
    this.matrixAutoUpdate = false;
    this.color = color;
    this.type = "HemisphereLightHelper";
    const geometry = new OctahedronGeometry(size);
    geometry.rotateY(Math.PI * 0.5);
    this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false });
    if (this.color === void 0) this.material.vertexColors = true;
    const position = geometry.getAttribute("position");
    const colors = new Float32Array(position.count * 3);
    geometry.setAttribute("color", new BufferAttribute(colors, 3));
    this.add(new Mesh(geometry, this.material));
    this.update();
  }
  dispose() {
    this.children[0].geometry.dispose();
    this.children[0].material.dispose();
  }
  update() {
    const mesh = this.children[0];
    if (this.color !== void 0) {
      this.material.color.set(this.color);
    } else {
      const colors = mesh.geometry.getAttribute("color");
      _color1.copy(this.light.color);
      _color2.copy(this.light.groundColor);
      for (let i2 = 0, l2 = colors.count; i2 < l2; i2++) {
        const color = i2 < l2 / 2 ? _color1 : _color2;
        colors.setXYZ(i2, color.r, color.g, color.b);
      }
      colors.needsUpdate = true;
    }
    this.light.updateWorldMatrix(true, false);
    mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  }
}
class GridHelper extends LineSegments {
  constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) {
    color1 = new Color(color1);
    color2 = new Color(color2);
    const center = divisions / 2;
    const step = size / divisions;
    const halfSize = size / 2;
    const vertices = [], colors = [];
    for (let i2 = 0, j2 = 0, k2 = -halfSize; i2 <= divisions; i2++, k2 += step) {
      vertices.push(-halfSize, 0, k2, halfSize, 0, k2);
      vertices.push(k2, 0, -halfSize, k2, 0, halfSize);
      const color = i2 === center ? color1 : color2;
      color.toArray(colors, j2);
      j2 += 3;
      color.toArray(colors, j2);
      j2 += 3;
      color.toArray(colors, j2);
      j2 += 3;
      color.toArray(colors, j2);
      j2 += 3;
    }
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false });
    super(geometry, material);
    this.type = "GridHelper";
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
class PolarGridHelper extends LineSegments {
  constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) {
    color1 = new Color(color1);
    color2 = new Color(color2);
    const vertices = [];
    const colors = [];
    if (sectors > 1) {
      for (let i2 = 0; i2 < sectors; i2++) {
        const v5 = i2 / sectors * (Math.PI * 2);
        const x = Math.sin(v5) * radius;
        const z2 = Math.cos(v5) * radius;
        vertices.push(0, 0, 0);
        vertices.push(x, 0, z2);
        const color = i2 & 1 ? color1 : color2;
        colors.push(color.r, color.g, color.b);
        colors.push(color.r, color.g, color.b);
      }
    }
    for (let i2 = 0; i2 < rings; i2++) {
      const color = i2 & 1 ? color1 : color2;
      const r2 = radius - radius / rings * i2;
      for (let j2 = 0; j2 < divisions; j2++) {
        let v5 = j2 / divisions * (Math.PI * 2);
        let x = Math.sin(v5) * r2;
        let z2 = Math.cos(v5) * r2;
        vertices.push(x, 0, z2);
        colors.push(color.r, color.g, color.b);
        v5 = (j2 + 1) / divisions * (Math.PI * 2);
        x = Math.sin(v5) * r2;
        z2 = Math.cos(v5) * r2;
        vertices.push(x, 0, z2);
        colors.push(color.r, color.g, color.b);
      }
    }
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false });
    super(geometry, material);
    this.type = "PolarGridHelper";
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
const _v1 = /* @__PURE__ */ new Vector3();
const _v2 = /* @__PURE__ */ new Vector3();
const _v3 = /* @__PURE__ */ new Vector3();
class DirectionalLightHelper extends Object3D {
  constructor(light, size, color) {
    super();
    this.light = light;
    this.matrix = light.matrixWorld;
    this.matrixAutoUpdate = false;
    this.color = color;
    this.type = "DirectionalLightHelper";
    if (size === void 0) size = 1;
    let geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute([
      -size,
      size,
      0,
      size,
      size,
      0,
      size,
      -size,
      0,
      -size,
      -size,
      0,
      -size,
      size,
      0
    ], 3));
    const material = new LineBasicMaterial({ fog: false, toneMapped: false });
    this.lightPlane = new Line$1(geometry, material);
    this.add(this.lightPlane);
    geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
    this.targetLine = new Line$1(geometry, material);
    this.add(this.targetLine);
    this.update();
  }
  dispose() {
    this.lightPlane.geometry.dispose();
    this.lightPlane.material.dispose();
    this.targetLine.geometry.dispose();
    this.targetLine.material.dispose();
  }
  update() {
    this.light.updateWorldMatrix(true, false);
    this.light.target.updateWorldMatrix(true, false);
    _v1.setFromMatrixPosition(this.light.matrixWorld);
    _v2.setFromMatrixPosition(this.light.target.matrixWorld);
    _v3.subVectors(_v2, _v1);
    this.lightPlane.lookAt(_v2);
    if (this.color !== void 0) {
      this.lightPlane.material.color.set(this.color);
      this.targetLine.material.color.set(this.color);
    } else {
      this.lightPlane.material.color.copy(this.light.color);
      this.targetLine.material.color.copy(this.light.color);
    }
    this.targetLine.lookAt(_v2);
    this.targetLine.scale.z = _v3.length();
  }
}
const _vector$d = /* @__PURE__ */ new Vector3();
const _camera = /* @__PURE__ */ new Camera();
class CameraHelper extends LineSegments {
  constructor(camera) {
    const geometry = new BufferGeometry();
    const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false });
    const vertices = [];
    const colors = [];
    const pointMap = {};
    addLine("n1", "n2");
    addLine("n2", "n4");
    addLine("n4", "n3");
    addLine("n3", "n1");
    addLine("f1", "f2");
    addLine("f2", "f4");
    addLine("f4", "f3");
    addLine("f3", "f1");
    addLine("n1", "f1");
    addLine("n2", "f2");
    addLine("n3", "f3");
    addLine("n4", "f4");
    addLine("p", "n1");
    addLine("p", "n2");
    addLine("p", "n3");
    addLine("p", "n4");
    addLine("u1", "u2");
    addLine("u2", "u3");
    addLine("u3", "u1");
    addLine("c", "t");
    addLine("p", "c");
    addLine("cn1", "cn2");
    addLine("cn3", "cn4");
    addLine("cf1", "cf2");
    addLine("cf3", "cf4");
    function addLine(a3, b2) {
      addPoint(a3);
      addPoint(b2);
    }
    function addPoint(id) {
      vertices.push(0, 0, 0);
      colors.push(0, 0, 0);
      if (pointMap[id] === void 0) {
        pointMap[id] = [];
      }
      pointMap[id].push(vertices.length / 3 - 1);
    }
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    super(geometry, material);
    this.type = "CameraHelper";
    this.camera = camera;
    if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
    this.matrix = camera.matrixWorld;
    this.matrixAutoUpdate = false;
    this.pointMap = pointMap;
    this.update();
    const colorFrustum = new Color(16755200);
    const colorCone = new Color(16711680);
    const colorUp = new Color(43775);
    const colorTarget = new Color(16777215);
    const colorCross = new Color(3355443);
    this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  }
  setColors(frustum, cone, up, target, cross) {
    const geometry = this.geometry;
    const colorAttribute = geometry.getAttribute("color");
    colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b);
    colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(25, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(27, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(29, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(31, cone.r, cone.g, cone.b);
    colorAttribute.setXYZ(32, up.r, up.g, up.b);
    colorAttribute.setXYZ(33, up.r, up.g, up.b);
    colorAttribute.setXYZ(34, up.r, up.g, up.b);
    colorAttribute.setXYZ(35, up.r, up.g, up.b);
    colorAttribute.setXYZ(36, up.r, up.g, up.b);
    colorAttribute.setXYZ(37, up.r, up.g, up.b);
    colorAttribute.setXYZ(38, target.r, target.g, target.b);
    colorAttribute.setXYZ(39, target.r, target.g, target.b);
    colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(41, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(43, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(45, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(47, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
    colorAttribute.setXYZ(49, cross.r, cross.g, cross.b);
    colorAttribute.needsUpdate = true;
  }
  update() {
    const geometry = this.geometry;
    const pointMap = this.pointMap;
    const w2 = 1, h2 = 1;
    _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse);
    setPoint("c", pointMap, geometry, _camera, 0, 0, -1);
    setPoint("t", pointMap, geometry, _camera, 0, 0, 1);
    setPoint("n1", pointMap, geometry, _camera, -w2, -h2, -1);
    setPoint("n2", pointMap, geometry, _camera, w2, -h2, -1);
    setPoint("n3", pointMap, geometry, _camera, -w2, h2, -1);
    setPoint("n4", pointMap, geometry, _camera, w2, h2, -1);
    setPoint("f1", pointMap, geometry, _camera, -w2, -h2, 1);
    setPoint("f2", pointMap, geometry, _camera, w2, -h2, 1);
    setPoint("f3", pointMap, geometry, _camera, -w2, h2, 1);
    setPoint("f4", pointMap, geometry, _camera, w2, h2, 1);
    setPoint("u1", pointMap, geometry, _camera, w2 * 0.7, h2 * 1.1, -1);
    setPoint("u2", pointMap, geometry, _camera, -w2 * 0.7, h2 * 1.1, -1);
    setPoint("u3", pointMap, geometry, _camera, 0, h2 * 2, -1);
    setPoint("cf1", pointMap, geometry, _camera, -w2, 0, 1);
    setPoint("cf2", pointMap, geometry, _camera, w2, 0, 1);
    setPoint("cf3", pointMap, geometry, _camera, 0, -h2, 1);
    setPoint("cf4", pointMap, geometry, _camera, 0, h2, 1);
    setPoint("cn1", pointMap, geometry, _camera, -w2, 0, -1);
    setPoint("cn2", pointMap, geometry, _camera, w2, 0, -1);
    setPoint("cn3", pointMap, geometry, _camera, 0, -h2, -1);
    setPoint("cn4", pointMap, geometry, _camera, 0, h2, -1);
    geometry.getAttribute("position").needsUpdate = true;
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
function setPoint(point, pointMap, geometry, camera, x, y2, z2) {
  _vector$d.set(x, y2, z2).unproject(camera);
  const points = pointMap[point];
  if (points !== void 0) {
    const position = geometry.getAttribute("position");
    for (let i2 = 0, l2 = points.length; i2 < l2; i2++) {
      position.setXYZ(points[i2], _vector$d.x, _vector$d.y, _vector$d.z);
    }
  }
}
const _box$5 = /* @__PURE__ */ new Box3();
class BoxHelper extends LineSegments {
  constructor(object, color = 16776960) {
    const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
    const positions = new Float32Array(8 * 3);
    const geometry = new BufferGeometry();
    geometry.setIndex(new BufferAttribute(indices, 1));
    geometry.setAttribute("position", new BufferAttribute(positions, 3));
    super(geometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.object = object;
    this.type = "BoxHelper";
    this.matrixAutoUpdate = false;
    this.update();
  }
  update(object) {
    if (object !== void 0) {
      console.warn("THREE.BoxHelper: .update() has no longer arguments.");
    }
    if (this.object !== void 0) {
      _box$5.setFromObject(this.object);
    }
    if (_box$5.isEmpty()) return;
    const min = _box$5.min;
    const max2 = _box$5.max;
    const position = this.geometry.attributes.position;
    const array = position.array;
    array[0] = max2.x;
    array[1] = max2.y;
    array[2] = max2.z;
    array[3] = min.x;
    array[4] = max2.y;
    array[5] = max2.z;
    array[6] = min.x;
    array[7] = min.y;
    array[8] = max2.z;
    array[9] = max2.x;
    array[10] = min.y;
    array[11] = max2.z;
    array[12] = max2.x;
    array[13] = max2.y;
    array[14] = min.z;
    array[15] = min.x;
    array[16] = max2.y;
    array[17] = min.z;
    array[18] = min.x;
    array[19] = min.y;
    array[20] = min.z;
    array[21] = max2.x;
    array[22] = min.y;
    array[23] = min.z;
    position.needsUpdate = true;
    this.geometry.computeBoundingSphere();
  }
  setFromObject(object) {
    this.object = object;
    this.update();
    return this;
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.object = source.object;
    return this;
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
class Box3Helper extends LineSegments {
  constructor(box, color = 16776960) {
    const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
    const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
    const geometry = new BufferGeometry();
    geometry.setIndex(new BufferAttribute(indices, 1));
    geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
    super(geometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.box = box;
    this.type = "Box3Helper";
    this.geometry.computeBoundingSphere();
  }
  updateMatrixWorld(force) {
    const box = this.box;
    if (box.isEmpty()) return;
    box.getCenter(this.position);
    box.getSize(this.scale);
    this.scale.multiplyScalar(0.5);
    super.updateMatrixWorld(force);
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
class PlaneHelper extends Line$1 {
  constructor(plane, size = 1, hex2 = 16776960) {
    const color = hex2;
    const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
    geometry.computeBoundingSphere();
    super(geometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.type = "PlaneHelper";
    this.plane = plane;
    this.size = size;
    const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
    const geometry2 = new BufferGeometry();
    geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3));
    geometry2.computeBoundingSphere();
    this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false })));
  }
  updateMatrixWorld(force) {
    this.position.set(0, 0, 0);
    this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
    this.lookAt(this.plane.normal);
    this.translateZ(-this.plane.constant);
    super.updateMatrixWorld(force);
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
    this.children[0].geometry.dispose();
    this.children[0].material.dispose();
  }
}
const _axis = /* @__PURE__ */ new Vector3();
let _lineGeometry, _coneGeometry;
class ArrowHelper extends Object3D {
  // dir is assumed to be normalized
  constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 16776960, headLength = length * 0.2, headWidth = headLength * 0.2) {
    super();
    this.type = "ArrowHelper";
    if (_lineGeometry === void 0) {
      _lineGeometry = new BufferGeometry();
      _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
      _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
      _coneGeometry.translate(0, -0.5, 0);
    }
    this.position.copy(origin);
    this.line = new Line$1(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.line.matrixAutoUpdate = false;
    this.add(this.line);
    this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false }));
    this.cone.matrixAutoUpdate = false;
    this.add(this.cone);
    this.setDirection(dir);
    this.setLength(length, headLength, headWidth);
  }
  setDirection(dir) {
    if (dir.y > 0.99999) {
      this.quaternion.set(0, 0, 0, 1);
    } else if (dir.y < -0.99999) {
      this.quaternion.set(1, 0, 0, 0);
    } else {
      _axis.set(dir.z, 0, -dir.x).normalize();
      const radians = Math.acos(dir.y);
      this.quaternion.setFromAxisAngle(_axis, radians);
    }
  }
  setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
    this.line.scale.set(1, Math.max(1e-4, length - headLength), 1);
    this.line.updateMatrix();
    this.cone.scale.set(headWidth, headLength, headWidth);
    this.cone.position.y = length;
    this.cone.updateMatrix();
  }
  setColor(color) {
    this.line.material.color.set(color);
    this.cone.material.color.set(color);
  }
  copy(source) {
    super.copy(source, false);
    this.line.copy(source.line);
    this.cone.copy(source.cone);
    return this;
  }
  dispose() {
    this.line.geometry.dispose();
    this.line.material.dispose();
    this.cone.geometry.dispose();
    this.cone.material.dispose();
  }
}
class AxesHelper extends LineSegments {
  constructor(size = 1) {
    const vertices = [
      0,
      0,
      0,
      size,
      0,
      0,
      0,
      0,
      0,
      0,
      size,
      0,
      0,
      0,
      0,
      0,
      0,
      size
    ];
    const colors = [
      1,
      0,
      0,
      1,
      0.6,
      0,
      0,
      1,
      0,
      0.6,
      1,
      0,
      0,
      0,
      1,
      0,
      0.6,
      1
    ];
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false });
    super(geometry, material);
    this.type = "AxesHelper";
  }
  setColors(xAxisColor, yAxisColor, zAxisColor) {
    const color = new Color();
    const array = this.geometry.attributes.color.array;
    color.set(xAxisColor);
    color.toArray(array, 0);
    color.toArray(array, 3);
    color.set(yAxisColor);
    color.toArray(array, 6);
    color.toArray(array, 9);
    color.set(zAxisColor);
    color.toArray(array, 12);
    color.toArray(array, 15);
    this.geometry.attributes.color.needsUpdate = true;
    return this;
  }
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
}
class ShapePath {
  constructor() {
    this.type = "ShapePath";
    this.color = new Color();
    this.subPaths = [];
    this.currentPath = null;
  }
  moveTo(x, y2) {
    this.currentPath = new Path();
    this.subPaths.push(this.currentPath);
    this.currentPath.moveTo(x, y2);
    return this;
  }
  lineTo(x, y2) {
    this.currentPath.lineTo(x, y2);
    return this;
  }
  quadraticCurveTo(aCPx, aCPy, aX, aY) {
    this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
    return this;
  }
  bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
    this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
    return this;
  }
  splineThru(pts) {
    this.currentPath.splineThru(pts);
    return this;
  }
  toShapes(isCCW) {
    function toShapesNoHoles(inSubpaths) {
      const shapes2 = [];
      for (let i2 = 0, l2 = inSubpaths.length; i2 < l2; i2++) {
        const tmpPath2 = inSubpaths[i2];
        const tmpShape2 = new Shape();
        tmpShape2.curves = tmpPath2.curves;
        shapes2.push(tmpShape2);
      }
      return shapes2;
    }
    function isPointInsidePolygon(inPt, inPolygon) {
      const polyLen = inPolygon.length;
      let inside = false;
      for (let p2 = polyLen - 1, q3 = 0; q3 < polyLen; p2 = q3++) {
        let edgeLowPt = inPolygon[p2];
        let edgeHighPt = inPolygon[q3];
        let edgeDx = edgeHighPt.x - edgeLowPt.x;
        let edgeDy = edgeHighPt.y - edgeLowPt.y;
        if (Math.abs(edgeDy) > Number.EPSILON) {
          if (edgeDy < 0) {
            edgeLowPt = inPolygon[q3];
            edgeDx = -edgeDx;
            edgeHighPt = inPolygon[p2];
            edgeDy = -edgeDy;
          }
          if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
          if (inPt.y === edgeLowPt.y) {
            if (inPt.x === edgeLowPt.x) return true;
          } else {
            const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
            if (perpEdge === 0) return true;
            if (perpEdge < 0) continue;
            inside = !inside;
          }
        } else {
          if (inPt.y !== edgeLowPt.y) continue;
          if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true;
        }
      }
      return inside;
    }
    const isClockWise = ShapeUtils.isClockWise;
    const subPaths = this.subPaths;
    if (subPaths.length === 0) return [];
    let solid, tmpPath, tmpShape;
    const shapes = [];
    if (subPaths.length === 1) {
      tmpPath = subPaths[0];
      tmpShape = new Shape();
      tmpShape.curves = tmpPath.curves;
      shapes.push(tmpShape);
      return shapes;
    }
    let holesFirst = !isClockWise(subPaths[0].getPoints());
    holesFirst = isCCW ? !holesFirst : holesFirst;
    const betterShapeHoles = [];
    const newShapes = [];
    let newShapeHoles = [];
    let mainIdx = 0;
    let tmpPoints;
    newShapes[mainIdx] = void 0;
    newShapeHoles[mainIdx] = [];
    for (let i2 = 0, l2 = subPaths.length; i2 < l2; i2++) {
      tmpPath = subPaths[i2];
      tmpPoints = tmpPath.getPoints();
      solid = isClockWise(tmpPoints);
      solid = isCCW ? !solid : solid;
      if (solid) {
        if (!holesFirst && newShapes[mainIdx]) mainIdx++;
        newShapes[mainIdx] = { s: new Shape(), p: tmpPoints };
        newShapes[mainIdx].s.curves = tmpPath.curves;
        if (holesFirst) mainIdx++;
        newShapeHoles[mainIdx] = [];
      } else {
        newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] });
      }
    }
    if (!newShapes[0]) return toShapesNoHoles(subPaths);
    if (newShapes.length > 1) {
      let ambiguous = false;
      let toChange = 0;
      for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
        betterShapeHoles[sIdx] = [];
      }
      for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
        const sho = newShapeHoles[sIdx];
        for (let hIdx = 0; hIdx < sho.length; hIdx++) {
          const ho = sho[hIdx];
          let hole_unassigned = true;
          for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
            if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
              if (sIdx !== s2Idx) toChange++;
              if (hole_unassigned) {
                hole_unassigned = false;
                betterShapeHoles[s2Idx].push(ho);
              } else {
                ambiguous = true;
              }
            }
          }
          if (hole_unassigned) {
            betterShapeHoles[sIdx].push(ho);
          }
        }
      }
      if (toChange > 0 && ambiguous === false) {
        newShapeHoles = betterShapeHoles;
      }
    }
    let tmpHoles;
    for (let i2 = 0, il = newShapes.length; i2 < il; i2++) {
      tmpShape = newShapes[i2].s;
      shapes.push(tmpShape);
      tmpHoles = newShapeHoles[i2];
      for (let j2 = 0, jl = tmpHoles.length; j2 < jl; j2++) {
        tmpShape.holes.push(tmpHoles[j2].h);
      }
    }
    return shapes;
  }
}
class Controls extends EventDispatcher$1 {
  constructor(object, domElement = null) {
    super();
    this.object = object;
    this.domElement = domElement;
    this.enabled = true;
    this.state = -1;
    this.keys = {};
    this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
    this.touches = { ONE: null, TWO: null };
  }
  connect() {
  }
  disconnect() {
  }
  dispose() {
  }
  update() {
  }
}
function contain(texture, aspect2) {
  const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1;
  if (imageAspect > aspect2) {
    texture.repeat.x = 1;
    texture.repeat.y = imageAspect / aspect2;
    texture.offset.x = 0;
    texture.offset.y = (1 - texture.repeat.y) / 2;
  } else {
    texture.repeat.x = aspect2 / imageAspect;
    texture.repeat.y = 1;
    texture.offset.x = (1 - texture.repeat.x) / 2;
    texture.offset.y = 0;
  }
  return texture;
}
function cover(texture, aspect2) {
  const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1;
  if (imageAspect > aspect2) {
    texture.repeat.x = aspect2 / imageAspect;
    texture.repeat.y = 1;
    texture.offset.x = (1 - texture.repeat.x) / 2;
    texture.offset.y = 0;
  } else {
    texture.repeat.x = 1;
    texture.repeat.y = imageAspect / aspect2;
    texture.offset.x = 0;
    texture.offset.y = (1 - texture.repeat.y) / 2;
  }
  return texture;
}
function fill(texture) {
  texture.repeat.x = 1;
  texture.repeat.y = 1;
  texture.offset.x = 0;
  texture.offset.y = 0;
  return texture;
}
function getByteLength(width, height, format, type) {
  const typeByteLength = getTextureTypeByteLength(type);
  switch (format) {
    // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
    case AlphaFormat:
      return width * height;
    case LuminanceFormat:
      return width * height;
    case LuminanceAlphaFormat:
      return width * height * 2;
    case RedFormat:
      return width * height / typeByteLength.components * typeByteLength.byteLength;
    case RedIntegerFormat:
      return width * height / typeByteLength.components * typeByteLength.byteLength;
    case RGFormat:
      return width * height * 2 / typeByteLength.components * typeByteLength.byteLength;
    case RGIntegerFormat:
      return width * height * 2 / typeByteLength.components * typeByteLength.byteLength;
    case RGBFormat:
      return width * height * 3 / typeByteLength.components * typeByteLength.byteLength;
    case RGBAFormat:
      return width * height * 4 / typeByteLength.components * typeByteLength.byteLength;
    case RGBAIntegerFormat:
      return width * height * 4 / typeByteLength.components * typeByteLength.byteLength;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
    case RGB_S3TC_DXT1_Format:
    case RGBA_S3TC_DXT1_Format:
      return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8;
    case RGBA_S3TC_DXT3_Format:
    case RGBA_S3TC_DXT5_Format:
      return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
    case RGB_PVRTC_2BPPV1_Format:
    case RGBA_PVRTC_2BPPV1_Format:
      return Math.max(width, 16) * Math.max(height, 8) / 4;
    case RGB_PVRTC_4BPPV1_Format:
    case RGBA_PVRTC_4BPPV1_Format:
      return Math.max(width, 8) * Math.max(height, 8) / 2;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
    case RGB_ETC1_Format:
    case RGB_ETC2_Format:
      return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8;
    case RGBA_ETC2_EAC_Format:
      return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
    case RGBA_ASTC_4x4_Format:
      return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;
    case RGBA_ASTC_5x4_Format:
      return Math.floor((width + 4) / 5) * Math.floor((height + 3) / 4) * 16;
    case RGBA_ASTC_5x5_Format:
      return Math.floor((width + 4) / 5) * Math.floor((height + 4) / 5) * 16;
    case RGBA_ASTC_6x5_Format:
      return Math.floor((width + 5) / 6) * Math.floor((height + 4) / 5) * 16;
    case RGBA_ASTC_6x6_Format:
      return Math.floor((width + 5) / 6) * Math.floor((height + 5) / 6) * 16;
    case RGBA_ASTC_8x5_Format:
      return Math.floor((width + 7) / 8) * Math.floor((height + 4) / 5) * 16;
    case RGBA_ASTC_8x6_Format:
      return Math.floor((width + 7) / 8) * Math.floor((height + 5) / 6) * 16;
    case RGBA_ASTC_8x8_Format:
      return Math.floor((width + 7) / 8) * Math.floor((height + 7) / 8) * 16;
    case RGBA_ASTC_10x5_Format:
      return Math.floor((width + 9) / 10) * Math.floor((height + 4) / 5) * 16;
    case RGBA_ASTC_10x6_Format:
      return Math.floor((width + 9) / 10) * Math.floor((height + 5) / 6) * 16;
    case RGBA_ASTC_10x8_Format:
      return Math.floor((width + 9) / 10) * Math.floor((height + 7) / 8) * 16;
    case RGBA_ASTC_10x10_Format:
      return Math.floor((width + 9) / 10) * Math.floor((height + 9) / 10) * 16;
    case RGBA_ASTC_12x10_Format:
      return Math.floor((width + 11) / 12) * Math.floor((height + 9) / 10) * 16;
    case RGBA_ASTC_12x12_Format:
      return Math.floor((width + 11) / 12) * Math.floor((height + 11) / 12) * 16;
    // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
    case RGBA_BPTC_Format:
    case RGB_BPTC_SIGNED_Format:
    case RGB_BPTC_UNSIGNED_Format:
      return Math.ceil(width / 4) * Math.ceil(height / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
    case RED_RGTC1_Format:
    case SIGNED_RED_RGTC1_Format:
      return Math.ceil(width / 4) * Math.ceil(height / 4) * 8;
    case RED_GREEN_RGTC2_Format:
    case SIGNED_RED_GREEN_RGTC2_Format:
      return Math.ceil(width / 4) * Math.ceil(height / 4) * 16;
  }
  throw new Error(
    `Unable to determine texture byte length for ${format} format.`
  );
}
function getTextureTypeByteLength(type) {
  switch (type) {
    case UnsignedByteType:
    case ByteType:
      return { byteLength: 1, components: 1 };
    case UnsignedShortType:
    case ShortType:
    case HalfFloatType:
      return { byteLength: 2, components: 1 };
    case UnsignedShort4444Type:
    case UnsignedShort5551Type:
      return { byteLength: 2, components: 4 };
    case UnsignedIntType:
    case IntType:
    case FloatType:
      return { byteLength: 4, components: 1 };
    case UnsignedInt5999Type:
      return { byteLength: 4, components: 3 };
  }
  throw new Error(`Unknown texture type ${type}.`);
}
const TextureUtils = {
  contain,
  cover,
  fill,
  getByteLength
};
class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  // @deprecated, r162
  constructor(width = 1, height = 1, count = 1, options = {}) {
    console.warn('THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.');
    super(width, height, { ...options, count });
    this.isWebGLMultipleRenderTargets = true;
  }
  get texture() {
    return this.textures;
  }
}
if (typeof __THREE_DEVTOOLS__ !== "undefined") {
  __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
    revision: REVISION
  } }));
}
if (typeof window !== "undefined") {
  if (window.__THREE__) {
    console.warn("WARNING: Multiple instances of Three.js being imported.");
  } else {
    window.__THREE__ = REVISION;
  }
}
/**
 * @license
 * Copyright 2010-2024 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
function WebGLAnimation() {
  let context2 = null;
  let isAnimating = false;
  let animationLoop = null;
  let requestId = null;
  function onAnimationFrame(time, frame) {
    animationLoop(time, frame);
    requestId = context2.requestAnimationFrame(onAnimationFrame);
  }
  return {
    start: function() {
      if (isAnimating === true) return;
      if (animationLoop === null) return;
      requestId = context2.requestAnimationFrame(onAnimationFrame);
      isAnimating = true;
    },
    stop: function() {
      context2.cancelAnimationFrame(requestId);
      isAnimating = false;
    },
    setAnimationLoop: function(callback) {
      animationLoop = callback;
    },
    setContext: function(value) {
      context2 = value;
    }
  };
}
function WebGLAttributes(gl) {
  const buffers = /* @__PURE__ */ new WeakMap();
  function createBuffer(attribute, bufferType) {
    const array = attribute.array;
    const usage = attribute.usage;
    const size = array.byteLength;
    const buffer = gl.createBuffer();
    gl.bindBuffer(bufferType, buffer);
    gl.bufferData(bufferType, array, usage);
    attribute.onUploadCallback();
    let type;
    if (array instanceof Float32Array) {
      type = gl.FLOAT;
    } else if (array instanceof Uint16Array) {
      if (attribute.isFloat16BufferAttribute) {
        type = gl.HALF_FLOAT;
      } else {
        type = gl.UNSIGNED_SHORT;
      }
    } else if (array instanceof Int16Array) {
      type = gl.SHORT;
    } else if (array instanceof Uint32Array) {
      type = gl.UNSIGNED_INT;
    } else if (array instanceof Int32Array) {
      type = gl.INT;
    } else if (array instanceof Int8Array) {
      type = gl.BYTE;
    } else if (array instanceof Uint8Array) {
      type = gl.UNSIGNED_BYTE;
    } else if (array instanceof Uint8ClampedArray) {
      type = gl.UNSIGNED_BYTE;
    } else {
      throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array);
    }
    return {
      buffer,
      type,
      bytesPerElement: array.BYTES_PER_ELEMENT,
      version: attribute.version,
      size
    };
  }
  function updateBuffer(buffer, attribute, bufferType) {
    const array = attribute.array;
    const updateRanges = attribute.updateRanges;
    gl.bindBuffer(bufferType, buffer);
    if (updateRanges.length === 0) {
      gl.bufferSubData(bufferType, 0, array);
    } else {
      updateRanges.sort((a3, b2) => a3.start - b2.start);
      let mergeIndex = 0;
      for (let i2 = 1; i2 < updateRanges.length; i2++) {
        const previousRange = updateRanges[mergeIndex];
        const range = updateRanges[i2];
        if (range.start <= previousRange.start + previousRange.count + 1) {
          previousRange.count = Math.max(
            previousRange.count,
            range.start + range.count - previousRange.start
          );
        } else {
          ++mergeIndex;
          updateRanges[mergeIndex] = range;
        }
      }
      updateRanges.length = mergeIndex + 1;
      for (let i2 = 0, l2 = updateRanges.length; i2 < l2; i2++) {
        const range = updateRanges[i2];
        gl.bufferSubData(
          bufferType,
          range.start * array.BYTES_PER_ELEMENT,
          array,
          range.start,
          range.count
        );
      }
      attribute.clearUpdateRanges();
    }
    attribute.onUploadCallback();
  }
  function get(attribute) {
    if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
    return buffers.get(attribute);
  }
  function remove(attribute) {
    if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
    const data = buffers.get(attribute);
    if (data) {
      gl.deleteBuffer(data.buffer);
      buffers.delete(attribute);
    }
  }
  function update(attribute, bufferType) {
    if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
    if (attribute.isGLBufferAttribute) {
      const cached = buffers.get(attribute);
      if (!cached || cached.version < attribute.version) {
        buffers.set(attribute, {
          buffer: attribute.buffer,
          type: attribute.type,
          bytesPerElement: attribute.elementSize,
          version: attribute.version
        });
      }
      return;
    }
    const data = buffers.get(attribute);
    if (data === void 0) {
      buffers.set(attribute, createBuffer(attribute, bufferType));
    } else if (data.version < attribute.version) {
      if (data.size !== attribute.array.byteLength) {
        throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");
      }
      updateBuffer(data.buffer, attribute, bufferType);
      data.version = attribute.version;
    }
  }
  return {
    get,
    remove,
    update
  };
}
var alphahash_fragment = "#ifdef USE_ALPHAHASH\n	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n	const float ALPHA_HASH_SCALE = 0.05;\n	float hash2D( vec2 value ) {\n		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n	}\n	float hash3D( vec3 value ) {\n		return hash2D( vec2( hash2D( value.xy ), value.z ) );\n	}\n	float getAlphaHashThreshold( vec3 position ) {\n		float maxDeriv = max(\n			length( dFdx( position.xyz ) ),\n			length( dFdy( position.xyz ) )\n		);\n		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n		vec2 pixScales = vec2(\n			exp2( floor( log2( pixScale ) ) ),\n			exp2( ceil( log2( pixScale ) ) )\n		);\n		vec2 alpha = vec2(\n			hash3D( floor( pixScales.x * position.xyz ) ),\n			hash3D( floor( pixScales.y * position.xyz ) )\n		);\n		float lerpFactor = fract( log2( pixScale ) );\n		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n		float a = min( lerpFactor, 1.0 - lerpFactor );\n		vec3 cases = vec3(\n			x * x / ( 2.0 * a * ( 1.0 - a ) ),\n			( x - 0.5 * a ) / ( 1.0 - a ),\n			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n		);\n		float threshold = ( x < ( 1.0 - a ) )\n			? ( ( x < a ) ? cases.x : cases.y )\n			: cases.z;\n		return clamp( threshold , 1.0e-6, 1.0 );\n	}\n#endif";
var alphamap_fragment = "#ifdef USE_ALPHAMAP\n	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n	uniform sampler2D alphaMap;\n#endif";
var alphatest_fragment = "#ifdef USE_ALPHATEST\n	#ifdef ALPHA_TO_COVERAGE\n	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n	if ( diffuseColor.a == 0.0 ) discard;\n	#else\n	if ( diffuseColor.a < alphaTest ) discard;\n	#endif\n#endif";
var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n	uniform float alphaTest;\n#endif";
var aomap_fragment = "#ifdef USE_AOMAP\n	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n	reflectedLight.indirectDiffuse *= ambientOcclusion;\n	#if defined( USE_CLEARCOAT ) \n		clearcoatSpecularIndirect *= ambientOcclusion;\n	#endif\n	#if defined( USE_SHEEN ) \n		sheenSpecularIndirect *= ambientOcclusion;\n	#endif\n	#if defined( USE_ENVMAP ) && defined( STANDARD )\n		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n	#endif\n#endif";
var aomap_pars_fragment = "#ifdef USE_AOMAP\n	uniform sampler2D aoMap;\n	uniform float aoMapIntensity;\n#endif";
var batching_pars_vertex = "#ifdef USE_BATCHING\n	#if ! defined( GL_ANGLE_multi_draw )\n	#define gl_DrawID _gl_DrawID\n	uniform int _gl_DrawID;\n	#endif\n	uniform highp sampler2D batchingTexture;\n	uniform highp usampler2D batchingIdTexture;\n	mat4 getBatchingMatrix( const in float i ) {\n		int size = textureSize( batchingTexture, 0 ).x;\n		int j = int( i ) * 4;\n		int x = j % size;\n		int y = j / size;\n		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n		return mat4( v1, v2, v3, v4 );\n	}\n	float getIndirectIndex( const in int i ) {\n		int size = textureSize( batchingIdTexture, 0 ).x;\n		int x = i % size;\n		int y = i / size;\n		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n	}\n#endif\n#ifdef USE_BATCHING_COLOR\n	uniform sampler2D batchingColorTexture;\n	vec3 getBatchingColor( const in float i ) {\n		int size = textureSize( batchingColorTexture, 0 ).x;\n		int j = int( i );\n		int x = j % size;\n		int y = j / size;\n		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n	}\n#endif";
var batching_vertex = "#ifdef USE_BATCHING\n	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n	vPosition = vec3( position );\n#endif";
var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n	vec3 objectTangent = vec3( tangent.xyz );\n#endif";
var bsdfs = "float G_BlinnPhong_Implicit( ) {\n	return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n	vec3 halfDir = normalize( lightDir + viewDir );\n	float dotNH = saturate( dot( normal, halfDir ) );\n	float dotVH = saturate( dot( viewDir, halfDir ) );\n	vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n	float G = G_BlinnPhong_Implicit( );\n	float D = D_BlinnPhong( shininess, dotNH );\n	return F * ( G * D );\n} // validated";
var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n	const mat3 XYZ_TO_REC709 = mat3(\n		 3.2404542, -0.9692660,  0.0556434,\n		-1.5371385,  1.8760108, -0.2040259,\n		-0.4985314,  0.0415560,  1.0572252\n	);\n	vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n		vec3 sqrtF0 = sqrt( fresnel0 );\n		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n	}\n	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n	}\n	float IorToFresnel0( float transmittedIor, float incidentIor ) {\n		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n	}\n	vec3 evalSensitivity( float OPD, vec3 shift ) {\n		float phase = 2.0 * PI * OPD * 1.0e-9;\n		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n		xyz /= 1.0685e-7;\n		vec3 rgb = XYZ_TO_REC709 * xyz;\n		return rgb;\n	}\n	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n		vec3 I;\n		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n		float cosTheta2Sq = 1.0 - sinTheta2Sq;\n		if ( cosTheta2Sq < 0.0 ) {\n			return vec3( 1.0 );\n		}\n		float cosTheta2 = sqrt( cosTheta2Sq );\n		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n		float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n		float T121 = 1.0 - R12;\n		float phi12 = 0.0;\n		if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n		float phi21 = PI - phi12;\n		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n		vec3 phi23 = vec3( 0.0 );\n		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n		vec3 phi = vec3( phi21 ) + phi23;\n		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n		vec3 r123 = sqrt( R123 );\n		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n		vec3 C0 = R12 + Rs;\n		I = C0;\n		vec3 Cm = Rs - T121;\n		for ( int m = 1; m <= 2; ++ m ) {\n			Cm *= r123;\n			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n			I += Cm * Sm;\n		}\n		return max( I, vec3( 0.0 ) );\n	}\n#endif";
var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n	uniform sampler2D bumpMap;\n	uniform float bumpScale;\n	vec2 dHdxy_fwd() {\n		vec2 dSTdx = dFdx( vBumpMapUv );\n		vec2 dSTdy = dFdy( vBumpMapUv );\n		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n		return vec2( dBx, dBy );\n	}\n	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n		vec3 vN = surf_norm;\n		vec3 R1 = cross( vSigmaY, vN );\n		vec3 R2 = cross( vN, vSigmaX );\n		float fDet = dot( vSigmaX, R1 ) * faceDirection;\n		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n		return normalize( abs( fDet ) * surf_norm - vGrad );\n	}\n#endif";
var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n	vec4 plane;\n	#ifdef ALPHA_TO_COVERAGE\n		float distanceToPlane, distanceGradient;\n		float clipOpacity = 1.0;\n		#pragma unroll_loop_start\n		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n			plane = clippingPlanes[ i ];\n			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n			distanceGradient = fwidth( distanceToPlane ) / 2.0;\n			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n			if ( clipOpacity == 0.0 ) discard;\n		}\n		#pragma unroll_loop_end\n		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n			float unionClipOpacity = 1.0;\n			#pragma unroll_loop_start\n			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n				plane = clippingPlanes[ i ];\n				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n				distanceGradient = fwidth( distanceToPlane ) / 2.0;\n				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n			}\n			#pragma unroll_loop_end\n			clipOpacity *= 1.0 - unionClipOpacity;\n		#endif\n		diffuseColor.a *= clipOpacity;\n		if ( diffuseColor.a == 0.0 ) discard;\n	#else\n		#pragma unroll_loop_start\n		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n			plane = clippingPlanes[ i ];\n			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n		}\n		#pragma unroll_loop_end\n		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n			bool clipped = true;\n			#pragma unroll_loop_start\n			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n				plane = clippingPlanes[ i ];\n				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n			}\n			#pragma unroll_loop_end\n			if ( clipped ) discard;\n		#endif\n	#endif\n#endif";
var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n	varying vec3 vClipPosition;\n	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n	varying vec3 vClipPosition;\n#endif";
var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n	vClipPosition = - mvPosition.xyz;\n#endif";
var color_fragment = "#if defined( USE_COLOR_ALPHA )\n	diffuseColor *= vColor;\n#elif defined( USE_COLOR )\n	diffuseColor.rgb *= vColor;\n#endif";
var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n	varying vec4 vColor;\n#elif defined( USE_COLOR )\n	varying vec3 vColor;\n#endif";
var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n	varying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n	varying vec3 vColor;\n#endif";
var color_vertex = "#if defined( USE_COLOR_ALPHA )\n	vColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n	vColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n	vColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n	vColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n	vColor.xyz *= batchingColor.xyz;\n#endif";
var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n	const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n	return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n	float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n	float precisionSafeLength( vec3 v ) {\n		float maxComponent = max3( abs( v ) );\n		return length( v / maxComponent ) * maxComponent;\n	}\n#endif\nstruct IncidentLight {\n	vec3 color;\n	vec3 direction;\n	bool visible;\n};\nstruct ReflectedLight {\n	vec3 directDiffuse;\n	vec3 directSpecular;\n	vec3 indirectDiffuse;\n	vec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n	varying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n	mat3 tmp;\n	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n	return tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n	return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n	return vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n	return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n	#define cubeUV_minMipLevel 4.0\n	#define cubeUV_minTileSize 16.0\n	float getFace( vec3 direction ) {\n		vec3 absDirection = abs( direction );\n		float face = - 1.0;\n		if ( absDirection.x > absDirection.z ) {\n			if ( absDirection.x > absDirection.y )\n				face = direction.x > 0.0 ? 0.0 : 3.0;\n			else\n				face = direction.y > 0.0 ? 1.0 : 4.0;\n		} else {\n			if ( absDirection.z > absDirection.y )\n				face = direction.z > 0.0 ? 2.0 : 5.0;\n			else\n				face = direction.y > 0.0 ? 1.0 : 4.0;\n		}\n		return face;\n	}\n	vec2 getUV( vec3 direction, float face ) {\n		vec2 uv;\n		if ( face == 0.0 ) {\n			uv = vec2( direction.z, direction.y ) / abs( direction.x );\n		} else if ( face == 1.0 ) {\n			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n		} else if ( face == 2.0 ) {\n			uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n		} else if ( face == 3.0 ) {\n			uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n		} else if ( face == 4.0 ) {\n			uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n		} else {\n			uv = vec2( direction.x, direction.y ) / abs( direction.z );\n		}\n		return 0.5 * ( uv + 1.0 );\n	}\n	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n		float face = getFace( direction );\n		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n		mipInt = max( mipInt, cubeUV_minMipLevel );\n		float faceSize = exp2( mipInt );\n		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n		if ( face > 2.0 ) {\n			uv.y += faceSize;\n			face -= 3.0;\n		}\n		uv.x += face * faceSize;\n		uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n		uv.x *= CUBEUV_TEXEL_WIDTH;\n		uv.y *= CUBEUV_TEXEL_HEIGHT;\n		#ifdef texture2DGradEXT\n			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n		#else\n			return texture2D( envMap, uv ).rgb;\n		#endif\n	}\n	#define cubeUV_r0 1.0\n	#define cubeUV_m0 - 2.0\n	#define cubeUV_r1 0.8\n	#define cubeUV_m1 - 1.0\n	#define cubeUV_r4 0.4\n	#define cubeUV_m4 2.0\n	#define cubeUV_r5 0.305\n	#define cubeUV_m5 3.0\n	#define cubeUV_r6 0.21\n	#define cubeUV_m6 4.0\n	float roughnessToMip( float roughness ) {\n		float mip = 0.0;\n		if ( roughness >= cubeUV_r1 ) {\n			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n		} else if ( roughness >= cubeUV_r4 ) {\n			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n		} else if ( roughness >= cubeUV_r5 ) {\n			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n		} else if ( roughness >= cubeUV_r6 ) {\n			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n		} else {\n			mip = - 2.0 * log2( 1.16 * roughness );		}\n		return mip;\n	}\n	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n		float mipF = fract( mip );\n		float mipInt = floor( mip );\n		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n		if ( mipF == 0.0 ) {\n			return vec4( color0, 1.0 );\n		} else {\n			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n			return vec4( mix( color0, color1, mipF ), 1.0 );\n		}\n	}\n#endif";
var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n	vec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n	mat3 bm = mat3( batchingMatrix );\n	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n	transformedNormal = bm * transformedNormal;\n	#ifdef USE_TANGENT\n		transformedTangent = bm * transformedTangent;\n	#endif\n#endif\n#ifdef USE_INSTANCING\n	mat3 im = mat3( instanceMatrix );\n	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n	transformedNormal = im * transformedNormal;\n	#ifdef USE_TANGENT\n		transformedTangent = im * transformedTangent;\n	#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n	transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n	#ifdef FLIP_SIDED\n		transformedTangent = - transformedTangent;\n	#endif\n#endif";
var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n	uniform sampler2D displacementMap;\n	uniform float displacementScale;\n	uniform float displacementBias;\n#endif";
var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n		emissiveColor = sRGBTransferEOTF( emissiveColor );\n	#endif\n	totalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n	uniform sampler2D emissiveMap;\n#endif";
var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n	return value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
var envmap_fragment = "#ifdef USE_ENVMAP\n	#ifdef ENV_WORLDPOS\n		vec3 cameraToFrag;\n		if ( isOrthographic ) {\n			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n		} else {\n			cameraToFrag = normalize( vWorldPosition - cameraPosition );\n		}\n		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n		#ifdef ENVMAP_MODE_REFLECTION\n			vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n		#else\n			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n		#endif\n	#else\n		vec3 reflectVec = vReflect;\n	#endif\n	#ifdef ENVMAP_TYPE_CUBE\n		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n	#else\n		vec4 envColor = vec4( 0.0 );\n	#endif\n	#ifdef ENVMAP_BLENDING_MULTIPLY\n		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n	#elif defined( ENVMAP_BLENDING_MIX )\n		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n	#elif defined( ENVMAP_BLENDING_ADD )\n		outgoingLight += envColor.xyz * specularStrength * reflectivity;\n	#endif\n#endif";
var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n	uniform float envMapIntensity;\n	uniform float flipEnvMap;\n	uniform mat3 envMapRotation;\n	#ifdef ENVMAP_TYPE_CUBE\n		uniform samplerCube envMap;\n	#else\n		uniform sampler2D envMap;\n	#endif\n	\n#endif";
var envmap_pars_fragment = "#ifdef USE_ENVMAP\n	uniform float reflectivity;\n	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n		#define ENV_WORLDPOS\n	#endif\n	#ifdef ENV_WORLDPOS\n		varying vec3 vWorldPosition;\n		uniform float refractionRatio;\n	#else\n		varying vec3 vReflect;\n	#endif\n#endif";
var envmap_pars_vertex = "#ifdef USE_ENVMAP\n	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n		#define ENV_WORLDPOS\n	#endif\n	#ifdef ENV_WORLDPOS\n		\n		varying vec3 vWorldPosition;\n	#else\n		varying vec3 vReflect;\n		uniform float refractionRatio;\n	#endif\n#endif";
var envmap_vertex = "#ifdef USE_ENVMAP\n	#ifdef ENV_WORLDPOS\n		vWorldPosition = worldPosition.xyz;\n	#else\n		vec3 cameraToVertex;\n		if ( isOrthographic ) {\n			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n		} else {\n			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n		}\n		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n		#ifdef ENVMAP_MODE_REFLECTION\n			vReflect = reflect( cameraToVertex, worldNormal );\n		#else\n			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n		#endif\n	#endif\n#endif";
var fog_vertex = "#ifdef USE_FOG\n	vFogDepth = - mvPosition.z;\n#endif";
var fog_pars_vertex = "#ifdef USE_FOG\n	varying float vFogDepth;\n#endif";
var fog_fragment = "#ifdef USE_FOG\n	#ifdef FOG_EXP2\n		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n	#else\n		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n	#endif\n	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
var fog_pars_fragment = "#ifdef USE_FOG\n	uniform vec3 fogColor;\n	varying float vFogDepth;\n	#ifdef FOG_EXP2\n		uniform float fogDensity;\n	#else\n		uniform float fogNear;\n		uniform float fogFar;\n	#endif\n#endif";
var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n	uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n	float dotNL = dot( normal, lightDirection );\n	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n	#ifdef USE_GRADIENTMAP\n		return vec3( texture2D( gradientMap, coord ).r );\n	#else\n		vec2 fw = fwidth( coord ) * 0.5;\n		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n	#endif\n}";
var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n	uniform sampler2D lightMap;\n	uniform float lightMapIntensity;\n#endif";
var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n	vec3 diffuseColor;\n	float specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n	vec3 irradiance = dotNL * directLight.color;\n	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct				RE_Direct_Lambert\n#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert";
var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n	uniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n	float x = normal.x, y = normal.y, z = normal.z;\n	vec3 result = shCoefficients[ 0 ] * 0.886227;\n	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n	return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n	return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n	vec3 irradiance = ambientLightColor;\n	return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n	if ( cutoffDistance > 0.0 ) {\n		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n	}\n	return distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n	return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n	struct DirectionalLight {\n		vec3 direction;\n		vec3 color;\n	};\n	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n		light.color = directionalLight.color;\n		light.direction = directionalLight.direction;\n		light.visible = true;\n	}\n#endif\n#if NUM_POINT_LIGHTS > 0\n	struct PointLight {\n		vec3 position;\n		vec3 color;\n		float distance;\n		float decay;\n	};\n	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n		vec3 lVector = pointLight.position - geometryPosition;\n		light.direction = normalize( lVector );\n		float lightDistance = length( lVector );\n		light.color = pointLight.color;\n		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n		light.visible = ( light.color != vec3( 0.0 ) );\n	}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n	struct SpotLight {\n		vec3 position;\n		vec3 direction;\n		vec3 color;\n		float distance;\n		float decay;\n		float coneCos;\n		float penumbraCos;\n	};\n	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n		vec3 lVector = spotLight.position - geometryPosition;\n		light.direction = normalize( lVector );\n		float angleCos = dot( light.direction, spotLight.direction );\n		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n		if ( spotAttenuation > 0.0 ) {\n			float lightDistance = length( lVector );\n			light.color = spotLight.color * spotAttenuation;\n			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n			light.visible = ( light.color != vec3( 0.0 ) );\n		} else {\n			light.color = vec3( 0.0 );\n			light.visible = false;\n		}\n	}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n	struct RectAreaLight {\n		vec3 color;\n		vec3 position;\n		vec3 halfWidth;\n		vec3 halfHeight;\n	};\n	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;\n	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n	struct HemisphereLight {\n		vec3 direction;\n		vec3 skyColor;\n		vec3 groundColor;\n	};\n	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n		float dotNL = dot( normal, hemiLight.direction );\n		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n		return irradiance;\n	}\n#endif";
var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n	vec3 getIBLIrradiance( const in vec3 normal ) {\n		#ifdef ENVMAP_TYPE_CUBE_UV\n			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n			return PI * envMapColor.rgb * envMapIntensity;\n		#else\n			return vec3( 0.0 );\n		#endif\n	}\n	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n		#ifdef ENVMAP_TYPE_CUBE_UV\n			vec3 reflectVec = reflect( - viewDir, normal );\n			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n			return envMapColor.rgb * envMapIntensity;\n		#else\n			return vec3( 0.0 );\n		#endif\n	}\n	#ifdef USE_ANISOTROPY\n		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n			#ifdef ENVMAP_TYPE_CUBE_UV\n				vec3 bentNormal = cross( bitangent, viewDir );\n				bentNormal = normalize( cross( bentNormal, bitangent ) );\n				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n				return getIBLRadiance( viewDir, bentNormal, roughness );\n			#else\n				return vec3( 0.0 );\n			#endif\n		}\n	#endif\n#endif";
var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n	vec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct				RE_Direct_Toon\n#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon";
var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n	vec3 diffuseColor;\n	vec3 specularColor;\n	float specularShininess;\n	float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n	vec3 irradiance = dotNL * directLight.color;\n	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct				RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong";
var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n	material.ior = ior;\n	#ifdef USE_SPECULAR\n		float specularIntensityFactor = specularIntensity;\n		vec3 specularColorFactor = specularColor;\n		#ifdef USE_SPECULAR_COLORMAP\n			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n		#endif\n		#ifdef USE_SPECULAR_INTENSITYMAP\n			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n		#endif\n		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n	#else\n		float specularIntensityFactor = 1.0;\n		vec3 specularColorFactor = vec3( 1.0 );\n		material.specularF90 = 1.0;\n	#endif\n	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n	material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n	material.clearcoat = clearcoat;\n	material.clearcoatRoughness = clearcoatRoughness;\n	material.clearcoatF0 = vec3( 0.04 );\n	material.clearcoatF90 = 1.0;\n	#ifdef USE_CLEARCOATMAP\n		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n	#endif\n	#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n	#endif\n	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n	material.clearcoatRoughness += geometryRoughness;\n	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n	material.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n	material.iridescence = iridescence;\n	material.iridescenceIOR = iridescenceIOR;\n	#ifdef USE_IRIDESCENCEMAP\n		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n	#endif\n	#ifdef USE_IRIDESCENCE_THICKNESSMAP\n		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n	#else\n		material.iridescenceThickness = iridescenceThicknessMaximum;\n	#endif\n#endif\n#ifdef USE_SHEEN\n	material.sheenColor = sheenColor;\n	#ifdef USE_SHEEN_COLORMAP\n		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n	#endif\n	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n	#ifdef USE_SHEEN_ROUGHNESSMAP\n		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n	#endif\n#endif\n#ifdef USE_ANISOTROPY\n	#ifdef USE_ANISOTROPYMAP\n		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n	#else\n		vec2 anisotropyV = anisotropyVector;\n	#endif\n	material.anisotropy = length( anisotropyV );\n	if( material.anisotropy == 0.0 ) {\n		anisotropyV = vec2( 1.0, 0.0 );\n	} else {\n		anisotropyV /= material.anisotropy;\n		material.anisotropy = saturate( material.anisotropy );\n	}\n	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
var lights_physical_pars_fragment = "struct PhysicalMaterial {\n	vec3 diffuseColor;\n	float roughness;\n	vec3 specularColor;\n	float specularF90;\n	float dispersion;\n	#ifdef USE_CLEARCOAT\n		float clearcoat;\n		float clearcoatRoughness;\n		vec3 clearcoatF0;\n		float clearcoatF90;\n	#endif\n	#ifdef USE_IRIDESCENCE\n		float iridescence;\n		float iridescenceIOR;\n		float iridescenceThickness;\n		vec3 iridescenceFresnel;\n		vec3 iridescenceF0;\n	#endif\n	#ifdef USE_SHEEN\n		vec3 sheenColor;\n		float sheenRoughness;\n	#endif\n	#ifdef IOR\n		float ior;\n	#endif\n	#ifdef USE_TRANSMISSION\n		float transmission;\n		float transmissionAlpha;\n		float thickness;\n		float attenuationDistance;\n		vec3 attenuationColor;\n	#endif\n	#ifdef USE_ANISOTROPY\n		float anisotropy;\n		float alphaT;\n		vec3 anisotropyT;\n		vec3 anisotropyB;\n	#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n    float x2 = x * x;\n    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n	float a2 = pow2( alpha );\n	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n	return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n	float a2 = pow2( alpha );\n	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n	return RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n		float v = 0.5 / ( gv + gl );\n		return saturate(v);\n	}\n	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n		float a2 = alphaT * alphaB;\n		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n		highp float v2 = dot( v, v );\n		float w2 = a2 / v2;\n		return RECIPROCAL_PI * a2 * pow2 ( w2 );\n	}\n#endif\n#ifdef USE_CLEARCOAT\n	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n		vec3 f0 = material.clearcoatF0;\n		float f90 = material.clearcoatF90;\n		float roughness = material.clearcoatRoughness;\n		float alpha = pow2( roughness );\n		vec3 halfDir = normalize( lightDir + viewDir );\n		float dotNL = saturate( dot( normal, lightDir ) );\n		float dotNV = saturate( dot( normal, viewDir ) );\n		float dotNH = saturate( dot( normal, halfDir ) );\n		float dotVH = saturate( dot( viewDir, halfDir ) );\n		vec3 F = F_Schlick( f0, f90, dotVH );\n		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n		float D = D_GGX( alpha, dotNH );\n		return F * ( V * D );\n	}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n	vec3 f0 = material.specularColor;\n	float f90 = material.specularF90;\n	float roughness = material.roughness;\n	float alpha = pow2( roughness );\n	vec3 halfDir = normalize( lightDir + viewDir );\n	float dotNL = saturate( dot( normal, lightDir ) );\n	float dotNV = saturate( dot( normal, viewDir ) );\n	float dotNH = saturate( dot( normal, halfDir ) );\n	float dotVH = saturate( dot( viewDir, halfDir ) );\n	vec3 F = F_Schlick( f0, f90, dotVH );\n	#ifdef USE_IRIDESCENCE\n		F = mix( F, material.iridescenceFresnel, material.iridescence );\n	#endif\n	#ifdef USE_ANISOTROPY\n		float dotTL = dot( material.anisotropyT, lightDir );\n		float dotTV = dot( material.anisotropyT, viewDir );\n		float dotTH = dot( material.anisotropyT, halfDir );\n		float dotBL = dot( material.anisotropyB, lightDir );\n		float dotBV = dot( material.anisotropyB, viewDir );\n		float dotBH = dot( material.anisotropyB, halfDir );\n		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n	#else\n		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n		float D = D_GGX( alpha, dotNH );\n	#endif\n	return F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n	const float LUT_SIZE = 64.0;\n	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n	const float LUT_BIAS = 0.5 / LUT_SIZE;\n	float dotNV = saturate( dot( N, V ) );\n	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n	uv = uv * LUT_SCALE + LUT_BIAS;\n	return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n	float l = length( f );\n	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n	float x = dot( v1, v2 );\n	float y = abs( x );\n	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n	float b = 3.4175940 + ( 4.1616724 + y ) * y;\n	float v = a / b;\n	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n	return cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n	vec3 lightNormal = cross( v1, v2 );\n	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n	vec3 T1, T2;\n	T1 = normalize( V - N * dot( V, N ) );\n	T2 = - cross( N, T1 );\n	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n	vec3 coords[ 4 ];\n	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n	coords[ 0 ] = normalize( coords[ 0 ] );\n	coords[ 1 ] = normalize( coords[ 1 ] );\n	coords[ 2 ] = normalize( coords[ 2 ] );\n	coords[ 3 ] = normalize( coords[ 3 ] );\n	vec3 vectorFormFactor = vec3( 0.0 );\n	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n	return vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n	float alpha = pow2( roughness );\n	float invAlpha = 1.0 / alpha;\n	float cos2h = dotNH * dotNH;\n	float sin2h = max( 1.0 - cos2h, 0.0078125 );\n	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n	vec3 halfDir = normalize( lightDir + viewDir );\n	float dotNL = saturate( dot( normal, lightDir ) );\n	float dotNV = saturate( dot( normal, viewDir ) );\n	float dotNH = saturate( dot( normal, halfDir ) );\n	float D = D_Charlie( sheenRoughness, dotNH );\n	float V = V_Neubelt( dotNV, dotNL );\n	return sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n	float dotNV = saturate( dot( normal, viewDir ) );\n	float r2 = roughness * roughness;\n	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n	return saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n	float dotNV = saturate( dot( normal, viewDir ) );\n	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n	vec4 r = roughness * c0 + c1;\n	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n	return fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n	vec2 fab = DFGApprox( normal, viewDir, roughness );\n	return specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n	vec2 fab = DFGApprox( normal, viewDir, roughness );\n	#ifdef USE_IRIDESCENCE\n		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n	#else\n		vec3 Fr = specularColor;\n	#endif\n	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n	float Ess = fab.x + fab.y;\n	float Ems = 1.0 - Ess;\n	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n	singleScatter += FssEss;\n	multiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n		vec3 normal = geometryNormal;\n		vec3 viewDir = geometryViewDir;\n		vec3 position = geometryPosition;\n		vec3 lightPos = rectAreaLight.position;\n		vec3 halfWidth = rectAreaLight.halfWidth;\n		vec3 halfHeight = rectAreaLight.halfHeight;\n		vec3 lightColor = rectAreaLight.color;\n		float roughness = material.roughness;\n		vec3 rectCoords[ 4 ];\n		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n		vec2 uv = LTC_Uv( normal, viewDir, roughness );\n		vec4 t1 = texture2D( ltc_1, uv );\n		vec4 t2 = texture2D( ltc_2, uv );\n		mat3 mInv = mat3(\n			vec3( t1.x, 0, t1.y ),\n			vec3(    0, 1,    0 ),\n			vec3( t1.z, 0, t1.w )\n		);\n		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n	}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n	vec3 irradiance = dotNL * directLight.color;\n	#ifdef USE_CLEARCOAT\n		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n		vec3 ccIrradiance = dotNLcc * directLight.color;\n		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n	#endif\n	#ifdef USE_SHEEN\n		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n	#endif\n	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n	#ifdef USE_CLEARCOAT\n		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n	#endif\n	#ifdef USE_SHEEN\n		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n	#endif\n	vec3 singleScattering = vec3( 0.0 );\n	vec3 multiScattering = vec3( 0.0 );\n	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n	#ifdef USE_IRIDESCENCE\n		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n	#else\n		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n	#endif\n	vec3 totalScattering = singleScattering + multiScattering;\n	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n	reflectedLight.indirectSpecular += radiance * singleScattering;\n	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct				RE_Direct_Physical\n#define RE_Direct_RectArea		RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular		RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n	geometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n	float dotNVi = saturate( dot( normal, geometryViewDir ) );\n	if ( material.iridescenceThickness == 0.0 ) {\n		material.iridescence = 0.0;\n	} else {\n		material.iridescence = saturate( material.iridescence );\n	}\n	if ( material.iridescence > 0.0 ) {\n		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n	}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n	PointLight pointLight;\n	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n	PointLightShadow pointLightShadow;\n	#endif\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n		pointLight = pointLights[ i ];\n		getPointLightInfo( pointLight, geometryPosition, directLight );\n		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n		pointLightShadow = pointLightShadows[ i ];\n		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n		#endif\n		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n	}\n	#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n	SpotLight spotLight;\n	vec4 spotColor;\n	vec3 spotLightCoord;\n	bool inSpotLightMap;\n	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n	SpotLightShadow spotLightShadow;\n	#endif\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n		spotLight = spotLights[ i ];\n		getSpotLightInfo( spotLight, geometryPosition, directLight );\n		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n		#else\n		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n		#endif\n		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n		#endif\n		#undef SPOT_LIGHT_MAP_INDEX\n		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n		spotLightShadow = spotLightShadows[ i ];\n		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n		#endif\n		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n	}\n	#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n	DirectionalLight directionalLight;\n	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n	DirectionalLightShadow directionalLightShadow;\n	#endif\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n		directionalLight = directionalLights[ i ];\n		getDirectionalLightInfo( directionalLight, directLight );\n		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n		directionalLightShadow = directionalLightShadows[ i ];\n		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n		#endif\n		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n	}\n	#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n	RectAreaLight rectAreaLight;\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n		rectAreaLight = rectAreaLights[ i ];\n		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n	}\n	#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n	vec3 iblIrradiance = vec3( 0.0 );\n	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n	#if defined( USE_LIGHT_PROBES )\n		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n	#endif\n	#if ( NUM_HEMI_LIGHTS > 0 )\n		#pragma unroll_loop_start\n		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n		}\n		#pragma unroll_loop_end\n	#endif\n#endif\n#if defined( RE_IndirectSpecular )\n	vec3 radiance = vec3( 0.0 );\n	vec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n	#ifdef USE_LIGHTMAP\n		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n		irradiance += lightMapIrradiance;\n	#endif\n	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n		iblIrradiance += getIBLIrradiance( geometryNormal );\n	#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n	#ifdef USE_ANISOTROPY\n		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n	#else\n		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n	#endif\n	#ifdef USE_CLEARCOAT\n		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n	#endif\n#endif";
var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n	uniform float logDepthBufFC;\n	varying float vFragDepth;\n	varying float vIsPerspective;\n#endif";
var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n	varying float vFragDepth;\n	varying float vIsPerspective;\n#endif";
var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n	vFragDepth = 1.0 + gl_Position.w;\n	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
var map_fragment = "#ifdef USE_MAP\n	vec4 sampledDiffuseColor = texture2D( map, vMapUv );\n	#ifdef DECODE_VIDEO_TEXTURE\n		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n	#endif\n	diffuseColor *= sampledDiffuseColor;\n#endif";
var map_pars_fragment = "#ifdef USE_MAP\n	uniform sampler2D map;\n#endif";
var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n	#if defined( USE_POINTS_UV )\n		vec2 uv = vUv;\n	#else\n		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n	#endif\n#endif\n#ifdef USE_MAP\n	diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n	diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n	varying vec2 vUv;\n#else\n	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n		uniform mat3 uvTransform;\n	#endif\n#endif\n#ifdef USE_MAP\n	uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n	uniform sampler2D alphaMap;\n#endif";
var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n	metalnessFactor *= texelMetalness.b;\n#endif";
var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n	uniform sampler2D metalnessMap;\n#endif";
var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n	float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n	}\n#endif";
var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n	vColor *= morphTargetBaseInfluence;\n	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n		#if defined( USE_COLOR_ALPHA )\n			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n		#elif defined( USE_COLOR )\n			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n		#endif\n	}\n#endif";
var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n	objectNormal *= morphTargetBaseInfluence;\n	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n	}\n#endif";
var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n	#ifndef USE_INSTANCING_MORPH\n		uniform float morphTargetBaseInfluence;\n		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n	#endif\n	uniform sampler2DArray morphTargetsTexture;\n	uniform ivec2 morphTargetsTextureSize;\n	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n		int y = texelIndex / morphTargetsTextureSize.x;\n		int x = texelIndex - y * morphTargetsTextureSize.x;\n		ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n		return texelFetch( morphTargetsTexture, morphUV, 0 );\n	}\n#endif";
var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n	transformed *= morphTargetBaseInfluence;\n	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n	}\n#endif";
var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n	vec3 fdx = dFdx( vViewPosition );\n	vec3 fdy = dFdy( vViewPosition );\n	vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n	vec3 normal = normalize( vNormal );\n	#ifdef DOUBLE_SIDED\n		normal *= faceDirection;\n	#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n	#ifdef USE_TANGENT\n		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n	#else\n		mat3 tbn = getTangentFrame( - vViewPosition, normal,\n		#if defined( USE_NORMALMAP )\n			vNormalMapUv\n		#elif defined( USE_CLEARCOAT_NORMALMAP )\n			vClearcoatNormalMapUv\n		#else\n			vUv\n		#endif\n		);\n	#endif\n	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n		tbn[0] *= faceDirection;\n		tbn[1] *= faceDirection;\n	#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n	#ifdef USE_TANGENT\n		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n	#else\n		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n	#endif\n	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n		tbn2[0] *= faceDirection;\n		tbn2[1] *= faceDirection;\n	#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n	#ifdef FLIP_SIDED\n		normal = - normal;\n	#endif\n	#ifdef DOUBLE_SIDED\n		normal = normal * faceDirection;\n	#endif\n	normal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n	mapN.xy *= normalScale;\n	normal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
var normal_pars_fragment = "#ifndef FLAT_SHADED\n	varying vec3 vNormal;\n	#ifdef USE_TANGENT\n		varying vec3 vTangent;\n		varying vec3 vBitangent;\n	#endif\n#endif";
var normal_pars_vertex = "#ifndef FLAT_SHADED\n	varying vec3 vNormal;\n	#ifdef USE_TANGENT\n		varying vec3 vTangent;\n		varying vec3 vBitangent;\n	#endif\n#endif";
var normal_vertex = "#ifndef FLAT_SHADED\n	vNormal = normalize( transformedNormal );\n	#ifdef USE_TANGENT\n		vTangent = normalize( transformedTangent );\n		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n	#endif\n#endif";
var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n	uniform sampler2D normalMap;\n	uniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n	uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n		vec3 q0 = dFdx( eye_pos.xyz );\n		vec3 q1 = dFdy( eye_pos.xyz );\n		vec2 st0 = dFdx( uv.st );\n		vec2 st1 = dFdy( uv.st );\n		vec3 N = surf_norm;\n		vec3 q1perp = cross( q1, N );\n		vec3 q0perp = cross( N, q0 );\n		vec3 T = q1perp * st0.x + q0perp * st1.x;\n		vec3 B = q1perp * st0.y + q0perp * st1.y;\n		float det = max( dot( T, T ), dot( B, B ) );\n		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n		return mat3( T * scale, B * scale, N );\n	}\n#endif";
var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n	vec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n	clearcoatMapN.xy *= clearcoatNormalScale;\n	clearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n	uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n	uniform sampler2D clearcoatNormalMap;\n	uniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n	uniform sampler2D clearcoatRoughnessMap;\n#endif";
var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n	uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n	uniform sampler2D iridescenceThicknessMap;\n#endif";
var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n	return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n	return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n	if( v <= 0.0 )\n		return vec4( 0., 0., 0., 0. );\n	if( v >= 1.0 )\n		return vec4( 1., 1., 1., 1. );\n	float vuf;\n	float af = modf( v * PackFactors.a, vuf );\n	float bf = modf( vuf * ShiftRight8, vuf );\n	float gf = modf( vuf * ShiftRight8, vuf );\n	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n	if( v <= 0.0 )\n		return vec3( 0., 0., 0. );\n	if( v >= 1.0 )\n		return vec3( 1., 1., 1. );\n	float vuf;\n	float bf = modf( v * PackFactors.b, vuf );\n	float gf = modf( vuf * ShiftRight8, vuf );\n	return vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n	if( v <= 0.0 )\n		return vec2( 0., 0. );\n	if( v >= 1.0 )\n		return vec2( 1., 1. );\n	float vuf;\n	float gf = modf( v * 256., vuf );\n	return vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n	return dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n	return dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n	return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n	return depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n	return ( near * far ) / ( ( far - near ) * depth - far );\n}";
var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n	gl_FragColor.rgb *= gl_FragColor.a;\n#endif";
var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n	mvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n	mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
var dithering_fragment = "#ifdef DITHERING\n	gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
var dithering_pars_fragment = "#ifdef DITHERING\n	vec3 dithering( vec3 color ) {\n		float grid_position = rand( gl_FragCoord.xy );\n		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n		return color + dither_shift_RGB;\n	}\n#endif";
var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n	roughnessFactor *= texelRoughness.g;\n#endif";
var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n	uniform sampler2D roughnessMap;\n#endif";
var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n	#if NUM_DIR_LIGHT_SHADOWS > 0\n		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n		struct DirectionalLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n		};\n		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n	#endif\n	#if NUM_SPOT_LIGHT_SHADOWS > 0\n		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n		struct SpotLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n		};\n		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n	#endif\n	#if NUM_POINT_LIGHT_SHADOWS > 0\n		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n		struct PointLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n			float shadowCameraNear;\n			float shadowCameraFar;\n		};\n		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n	#endif\n	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n	}\n	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n		return unpackRGBATo2Half( texture2D( shadow, uv ) );\n	}\n	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n		float occlusion = 1.0;\n		vec2 distribution = texture2DDistribution( shadow, uv );\n		float hard_shadow = step( compare , distribution.x );\n		if (hard_shadow != 1.0 ) {\n			float distance = compare - distribution.x ;\n			float variance = max( 0.00000, distribution.y * distribution.y );\n			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n		}\n		return occlusion;\n	}\n	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n		float shadow = 1.0;\n		shadowCoord.xyz /= shadowCoord.w;\n		shadowCoord.z += shadowBias;\n		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n		if ( frustumTest ) {\n		#if defined( SHADOWMAP_TYPE_PCF )\n			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n			float dx0 = - texelSize.x * shadowRadius;\n			float dy0 = - texelSize.y * shadowRadius;\n			float dx1 = + texelSize.x * shadowRadius;\n			float dy1 = + texelSize.y * shadowRadius;\n			float dx2 = dx0 / 2.0;\n			float dy2 = dy0 / 2.0;\n			float dx3 = dx1 / 2.0;\n			float dy3 = dy1 / 2.0;\n			shadow = (\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n			) * ( 1.0 / 17.0 );\n		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n			float dx = texelSize.x;\n			float dy = texelSize.y;\n			vec2 uv = shadowCoord.xy;\n			vec2 f = fract( uv * shadowMapSize + 0.5 );\n			uv -= f * texelSize;\n			shadow = (\n				texture2DCompare( shadowMap, uv, shadowCoord.z ) +\n				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n					 f.x ) +\n				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n					 f.x ) +\n				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n					 f.y ) +\n				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n					 f.y ) +\n				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n						  f.x ),\n					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n						  f.x ),\n					 f.y )\n			) * ( 1.0 / 9.0 );\n		#elif defined( SHADOWMAP_TYPE_VSM )\n			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n		#else\n			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n		#endif\n		}\n		return mix( 1.0, shadow, shadowIntensity );\n	}\n	vec2 cubeToUV( vec3 v, float texelSizeY ) {\n		vec3 absV = abs( v );\n		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n		absV *= scaleToCube;\n		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n		vec2 planar = v.xy;\n		float almostATexel = 1.5 * texelSizeY;\n		float almostOne = 1.0 - almostATexel;\n		if ( absV.z >= almostOne ) {\n			if ( v.z > 0.0 )\n				planar.x = 4.0 - v.x;\n		} else if ( absV.x >= almostOne ) {\n			float signX = sign( v.x );\n			planar.x = v.z * signX + 2.0 * signX;\n		} else if ( absV.y >= almostOne ) {\n			float signY = sign( v.y );\n			planar.x = v.x + 2.0 * signY + 2.0;\n			planar.y = v.z * signY - 2.0;\n		}\n		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n	}\n	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n		float shadow = 1.0;\n		vec3 lightToPosition = shadowCoord.xyz;\n		\n		float lightToPositionLength = length( lightToPosition );\n		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;\n			vec3 bd3D = normalize( lightToPosition );\n			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n				shadow = (\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n				) * ( 1.0 / 9.0 );\n			#else\n				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n			#endif\n		}\n		return mix( 1.0, shadow, shadowIntensity );\n	}\n#endif";
var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n	#if NUM_DIR_LIGHT_SHADOWS > 0\n		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n		struct DirectionalLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n		};\n		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n	#endif\n	#if NUM_SPOT_LIGHT_SHADOWS > 0\n		struct SpotLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n		};\n		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n	#endif\n	#if NUM_POINT_LIGHT_SHADOWS > 0\n		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n		struct PointLightShadow {\n			float shadowIntensity;\n			float shadowBias;\n			float shadowNormalBias;\n			float shadowRadius;\n			vec2 shadowMapSize;\n			float shadowCameraNear;\n			float shadowCameraFar;\n		};\n		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n	#endif\n#endif";
var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n	vec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n	#if NUM_DIR_LIGHT_SHADOWS > 0\n		#pragma unroll_loop_start\n		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n		}\n		#pragma unroll_loop_end\n	#endif\n	#if NUM_POINT_LIGHT_SHADOWS > 0\n		#pragma unroll_loop_start\n		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n		}\n		#pragma unroll_loop_end\n	#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n		shadowWorldPosition = worldPosition;\n		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n		#endif\n		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n	}\n	#pragma unroll_loop_end\n#endif";
var shadowmask_pars_fragment = "float getShadowMask() {\n	float shadow = 1.0;\n	#ifdef USE_SHADOWMAP\n	#if NUM_DIR_LIGHT_SHADOWS > 0\n	DirectionalLightShadow directionalLight;\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n		directionalLight = directionalLightShadows[ i ];\n		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n	}\n	#pragma unroll_loop_end\n	#endif\n	#if NUM_SPOT_LIGHT_SHADOWS > 0\n	SpotLightShadow spotLight;\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n		spotLight = spotLightShadows[ i ];\n		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n	}\n	#pragma unroll_loop_end\n	#endif\n	#if NUM_POINT_LIGHT_SHADOWS > 0\n	PointLightShadow pointLight;\n	#pragma unroll_loop_start\n	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n		pointLight = pointLightShadows[ i ];\n		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n	}\n	#pragma unroll_loop_end\n	#endif\n	#endif\n	return shadow;\n}";
var skinbase_vertex = "#ifdef USE_SKINNING\n	mat4 boneMatX = getBoneMatrix( skinIndex.x );\n	mat4 boneMatY = getBoneMatrix( skinIndex.y );\n	mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n	mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
var skinning_pars_vertex = "#ifdef USE_SKINNING\n	uniform mat4 bindMatrix;\n	uniform mat4 bindMatrixInverse;\n	uniform highp sampler2D boneTexture;\n	mat4 getBoneMatrix( const in float i ) {\n		int size = textureSize( boneTexture, 0 ).x;\n		int j = int( i ) * 4;\n		int x = j % size;\n		int y = j / size;\n		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n		return mat4( v1, v2, v3, v4 );\n	}\n#endif";
var skinning_vertex = "#ifdef USE_SKINNING\n	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n	vec4 skinned = vec4( 0.0 );\n	skinned += boneMatX * skinVertex * skinWeight.x;\n	skinned += boneMatY * skinVertex * skinWeight.y;\n	skinned += boneMatZ * skinVertex * skinWeight.z;\n	skinned += boneMatW * skinVertex * skinWeight.w;\n	transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
var skinnormal_vertex = "#ifdef USE_SKINNING\n	mat4 skinMatrix = mat4( 0.0 );\n	skinMatrix += skinWeight.x * boneMatX;\n	skinMatrix += skinWeight.y * boneMatY;\n	skinMatrix += skinWeight.z * boneMatZ;\n	skinMatrix += skinWeight.w * boneMatW;\n	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n	#ifdef USE_TANGENT\n		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n	#endif\n#endif";
var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n	specularStrength = texelSpecular.r;\n#else\n	specularStrength = 1.0;\n#endif";
var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n	uniform sampler2D specularMap;\n#endif";
var tonemapping_fragment = "#if defined( TONE_MAPPING )\n	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n	return saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n	color *= toneMappingExposure;\n	return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n	color *= toneMappingExposure;\n	color = max( vec3( 0.0 ), color - 0.004 );\n	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n	return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n	const mat3 ACESInputMat = mat3(\n		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),\n		vec3( 0.04823, 0.01566, 0.83777 )\n	);\n	const mat3 ACESOutputMat = mat3(\n		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),\n		vec3( -0.07367, -0.00605,  1.07602 )\n	);\n	color *= toneMappingExposure / 0.6;\n	color = ACESInputMat * color;\n	color = RRTAndODTFit( color );\n	color = ACESOutputMat * color;\n	return saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n	vec3( 1.6605, - 0.1246, - 0.0182 ),\n	vec3( - 0.5876, 1.1329, - 0.1006 ),\n	vec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n	vec3( 0.6274, 0.0691, 0.0164 ),\n	vec3( 0.3293, 0.9195, 0.0880 ),\n	vec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n	vec3 x2 = x * x;\n	vec3 x4 = x2 * x2;\n	return + 15.5 * x4 * x2\n		- 40.14 * x4 * x\n		+ 31.96 * x4\n		- 6.868 * x2 * x\n		+ 0.4298 * x2\n		+ 0.1191 * x\n		- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n	const mat3 AgXInsetMatrix = mat3(\n		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n	);\n	const mat3 AgXOutsetMatrix = mat3(\n		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n	);\n	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;\n	color *= toneMappingExposure;\n	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n	color = AgXInsetMatrix * color;\n	color = max( color, 1e-10 );	color = log2( color );\n	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n	color = clamp( color, 0.0, 1.0 );\n	color = agxDefaultContrastApprox( color );\n	color = AgXOutsetMatrix * color;\n	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n	color = clamp( color, 0.0, 1.0 );\n	return color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n	const float StartCompression = 0.8 - 0.04;\n	const float Desaturation = 0.15;\n	color *= toneMappingExposure;\n	float x = min( color.r, min( color.g, color.b ) );\n	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n	color -= offset;\n	float peak = max( color.r, max( color.g, color.b ) );\n	if ( peak < StartCompression ) return color;\n	float d = 1. - StartCompression;\n	float newPeak = 1. - d * d / ( peak + d - StartCompression );\n	color *= newPeak / peak;\n	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n	return mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
var transmission_fragment = "#ifdef USE_TRANSMISSION\n	material.transmission = transmission;\n	material.transmissionAlpha = 1.0;\n	material.thickness = thickness;\n	material.attenuationDistance = attenuationDistance;\n	material.attenuationColor = attenuationColor;\n	#ifdef USE_TRANSMISSIONMAP\n		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n	#endif\n	#ifdef USE_THICKNESSMAP\n		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n	#endif\n	vec3 pos = vWorldPosition;\n	vec3 v = normalize( cameraPosition - pos );\n	vec3 n = inverseTransformDirection( normal, viewMatrix );\n	vec4 transmitted = getIBLVolumeRefraction(\n		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n		material.attenuationColor, material.attenuationDistance );\n	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n	uniform float transmission;\n	uniform float thickness;\n	uniform float attenuationDistance;\n	uniform vec3 attenuationColor;\n	#ifdef USE_TRANSMISSIONMAP\n		uniform sampler2D transmissionMap;\n	#endif\n	#ifdef USE_THICKNESSMAP\n		uniform sampler2D thicknessMap;\n	#endif\n	uniform vec2 transmissionSamplerSize;\n	uniform sampler2D transmissionSamplerMap;\n	uniform mat4 modelMatrix;\n	uniform mat4 projectionMatrix;\n	varying vec3 vWorldPosition;\n	float w0( float a ) {\n		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n	}\n	float w1( float a ) {\n		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );\n	}\n	float w2( float a ){\n		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n	}\n	float w3( float a ) {\n		return ( 1.0 / 6.0 ) * ( a * a * a );\n	}\n	float g0( float a ) {\n		return w0( a ) + w1( a );\n	}\n	float g1( float a ) {\n		return w2( a ) + w3( a );\n	}\n	float h0( float a ) {\n		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n	}\n	float h1( float a ) {\n		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n	}\n	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n		uv = uv * texelSize.zw + 0.5;\n		vec2 iuv = floor( uv );\n		vec2 fuv = fract( uv );\n		float g0x = g0( fuv.x );\n		float g1x = g1( fuv.x );\n		float h0x = h0( fuv.x );\n		float h1x = h1( fuv.x );\n		float h0y = h0( fuv.y );\n		float h1y = h1( fuv.y );\n		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n	}\n	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n		vec2 fLodSizeInv = 1.0 / fLodSize;\n		vec2 cLodSizeInv = 1.0 / cLodSize;\n		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n		return mix( fSample, cSample, fract( lod ) );\n	}\n	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n		vec3 modelScale;\n		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n		return normalize( refractionVector ) * thickness * modelScale;\n	}\n	float applyIorToRoughness( const in float roughness, const in float ior ) {\n		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n	}\n	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n	}\n	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n		if ( isinf( attenuationDistance ) ) {\n			return vec3( 1.0 );\n		} else {\n			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;\n		}\n	}\n	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n		const in vec3 attenuationColor, const in float attenuationDistance ) {\n		vec4 transmittedLight;\n		vec3 transmittance;\n		#ifdef USE_DISPERSION\n			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n			for ( int i = 0; i < 3; i ++ ) {\n				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n				vec3 refractedRayExit = position + transmissionRay;\n		\n				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n				vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n				refractionCoords += 1.0;\n				refractionCoords /= 2.0;\n		\n				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n				transmittedLight[ i ] = transmissionSample[ i ];\n				transmittedLight.a += transmissionSample.a;\n				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n			}\n			transmittedLight.a /= 3.0;\n		\n		#else\n		\n			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n			vec3 refractedRayExit = position + transmissionRay;\n			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n			vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n			refractionCoords += 1.0;\n			refractionCoords /= 2.0;\n			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n		\n		#endif\n		vec3 attenuatedColor = transmittance * transmittedLight.rgb;\n		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n	}\n#endif";
var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n	varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n	varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n	varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n	varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n	varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n	varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n	varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n	varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n	varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n	varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n	varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n	varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n	varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n	varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n	varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n	varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n	varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n	varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n	varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n	varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n	varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n	uniform mat3 transmissionMapTransform;\n	varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n	uniform mat3 thicknessMapTransform;\n	varying vec2 vThicknessMapUv;\n#endif";
var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n	varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n	uniform mat3 mapTransform;\n	varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n	uniform mat3 alphaMapTransform;\n	varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n	uniform mat3 lightMapTransform;\n	varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n	uniform mat3 aoMapTransform;\n	varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n	uniform mat3 bumpMapTransform;\n	varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n	uniform mat3 normalMapTransform;\n	varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n	uniform mat3 displacementMapTransform;\n	varying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n	uniform mat3 emissiveMapTransform;\n	varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n	uniform mat3 metalnessMapTransform;\n	varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n	uniform mat3 roughnessMapTransform;\n	varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n	uniform mat3 anisotropyMapTransform;\n	varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n	uniform mat3 clearcoatMapTransform;\n	varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n	uniform mat3 clearcoatNormalMapTransform;\n	varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n	uniform mat3 clearcoatRoughnessMapTransform;\n	varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n	uniform mat3 sheenColorMapTransform;\n	varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n	uniform mat3 sheenRoughnessMapTransform;\n	varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n	uniform mat3 iridescenceMapTransform;\n	varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n	uniform mat3 iridescenceThicknessMapTransform;\n	varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n	uniform mat3 specularMapTransform;\n	varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n	uniform mat3 specularColorMapTransform;\n	varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n	uniform mat3 specularIntensityMapTransform;\n	varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n	uniform mat3 transmissionMapTransform;\n	varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n	uniform mat3 thicknessMapTransform;\n	varying vec2 vThicknessMapUv;\n#endif";
var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n	vUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n	vec4 worldPosition = vec4( transformed, 1.0 );\n	#ifdef USE_BATCHING\n		worldPosition = batchingMatrix * worldPosition;\n	#endif\n	#ifdef USE_INSTANCING\n		worldPosition = instanceMatrix * worldPosition;\n	#endif\n	worldPosition = modelMatrix * worldPosition;\n#endif";
const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n	gl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n	vec4 texColor = texture2D( t2D, vUv );\n	#ifdef DECODE_VIDEO_TEXTURE\n		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n	#endif\n	texColor.rgb *= backgroundIntensity;\n	gl_FragColor = texColor;\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n}";
const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n	vWorldDirection = transformDirection( position, modelMatrix );\n	#include <begin_vertex>\n	#include <project_vertex>\n	gl_Position.z = gl_Position.w;\n}";
const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n	uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n	uniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n	#ifdef ENVMAP_TYPE_CUBE\n		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n	#elif defined( ENVMAP_TYPE_CUBE_UV )\n		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n	#else\n		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n	#endif\n	texColor.rgb *= backgroundIntensity;\n	gl_FragColor = texColor;\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n}";
const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n	vWorldDirection = transformDirection( position, modelMatrix );\n	#include <begin_vertex>\n	#include <project_vertex>\n	gl_Position.z = gl_Position.w;\n}";
const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n	gl_FragColor = texColor;\n	gl_FragColor.a *= opacity;\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n}";
const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n	#include <uv_vertex>\n	#include <batching_vertex>\n	#include <skinbase_vertex>\n	#include <morphinstance_vertex>\n	#ifdef USE_DISPLACEMENTMAP\n		#include <beginnormal_vertex>\n		#include <morphnormal_vertex>\n		#include <skinnormal_vertex>\n	#endif\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	vHighPrecisionZW = gl_Position.zw;\n}";
const fragment$e = "#if DEPTH_PACKING == 3200\n	uniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n	vec4 diffuseColor = vec4( 1.0 );\n	#include <clipping_planes_fragment>\n	#if DEPTH_PACKING == 3200\n		diffuseColor.a = opacity;\n	#endif\n	#include <map_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <logdepthbuf_fragment>\n	float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n	#if DEPTH_PACKING == 3200\n		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n	#elif DEPTH_PACKING == 3201\n		gl_FragColor = packDepthToRGBA( fragCoordZ );\n	#elif DEPTH_PACKING == 3202\n		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n	#elif DEPTH_PACKING == 3203\n		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n	#endif\n}";
const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <batching_vertex>\n	#include <skinbase_vertex>\n	#include <morphinstance_vertex>\n	#ifdef USE_DISPLACEMENTMAP\n		#include <beginnormal_vertex>\n		#include <morphnormal_vertex>\n		#include <skinnormal_vertex>\n	#endif\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <worldpos_vertex>\n	#include <clipping_planes_vertex>\n	vWorldPosition = worldPosition.xyz;\n}";
const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n	vec4 diffuseColor = vec4( 1.0 );\n	#include <clipping_planes_fragment>\n	#include <map_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	float dist = length( vWorldPosition - referencePosition );\n	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n	dist = saturate( dist );\n	gl_FragColor = packDepthToRGBA( dist );\n}";
const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n	vWorldDirection = transformDirection( position, modelMatrix );\n	#include <begin_vertex>\n	#include <project_vertex>\n}";
const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n	vec3 direction = normalize( vWorldDirection );\n	vec2 sampleUV = equirectUv( direction );\n	gl_FragColor = texture2D( tEquirect, sampleUV );\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n}";
const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	vLineDistance = scale * lineDistance;\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	#include <fog_vertex>\n}";
const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	if ( mod( vLineDistance, totalSize ) > dashSize ) {\n		discard;\n	}\n	vec3 outgoingLight = vec3( 0.0 );\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	outgoingLight = diffuseColor.rgb;\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n}";
const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n		#include <beginnormal_vertex>\n		#include <morphnormal_vertex>\n		#include <skinbase_vertex>\n		#include <skinnormal_vertex>\n		#include <defaultnormal_vertex>\n	#endif\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	#include <worldpos_vertex>\n	#include <envmap_vertex>\n	#include <fog_vertex>\n}";
const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n	varying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <specularmap_fragment>\n	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n	#ifdef USE_LIGHTMAP\n		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n	#else\n		reflectedLight.indirectDiffuse += vec3( 1.0 );\n	#endif\n	#include <aomap_fragment>\n	reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n	vec3 outgoingLight = reflectedLight.indirectDiffuse;\n	#include <envmap_fragment>\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	vViewPosition = - mvPosition.xyz;\n	#include <worldpos_vertex>\n	#include <envmap_vertex>\n	#include <shadowmap_vertex>\n	#include <fog_vertex>\n}";
const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n	vec3 totalEmissiveRadiance = emissive;\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <specularmap_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	#include <emissivemap_fragment>\n	#include <lights_lambert_fragment>\n	#include <lights_fragment_begin>\n	#include <lights_fragment_maps>\n	#include <lights_fragment_end>\n	#include <aomap_fragment>\n	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n	#include <envmap_fragment>\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	#include <fog_vertex>\n	vViewPosition = - mvPosition.xyz;\n}";
const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	vec3 viewDir = normalize( vViewPosition );\n	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n	vec3 y = cross( viewDir, x );\n	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n	#ifdef USE_MATCAP\n		vec4 matcapColor = texture2D( matcap, uv );\n	#else\n		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n	#endif\n	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n	varying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphinstance_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n	vViewPosition = - mvPosition.xyz;\n#endif\n}";
const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n	varying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n	#include <clipping_planes_fragment>\n	#include <logdepthbuf_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n	#ifdef OPAQUE\n		gl_FragColor.a = 1.0;\n	#endif\n}";
const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphinstance_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	vViewPosition = - mvPosition.xyz;\n	#include <worldpos_vertex>\n	#include <envmap_vertex>\n	#include <shadowmap_vertex>\n	#include <fog_vertex>\n}";
const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n	vec3 totalEmissiveRadiance = emissive;\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <specularmap_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	#include <emissivemap_fragment>\n	#include <lights_phong_fragment>\n	#include <lights_fragment_begin>\n	#include <lights_fragment_maps>\n	#include <lights_fragment_end>\n	#include <aomap_fragment>\n	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n	#include <envmap_fragment>\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n	varying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	vViewPosition = - mvPosition.xyz;\n	#include <worldpos_vertex>\n	#include <shadowmap_vertex>\n	#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n	vWorldPosition = worldPosition.xyz;\n#endif\n}";
const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n	#define IOR\n	#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n	uniform float ior;\n#endif\n#ifdef USE_SPECULAR\n	uniform float specularIntensity;\n	uniform vec3 specularColor;\n	#ifdef USE_SPECULAR_COLORMAP\n		uniform sampler2D specularColorMap;\n	#endif\n	#ifdef USE_SPECULAR_INTENSITYMAP\n		uniform sampler2D specularIntensityMap;\n	#endif\n#endif\n#ifdef USE_CLEARCOAT\n	uniform float clearcoat;\n	uniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n	uniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n	uniform float iridescence;\n	uniform float iridescenceIOR;\n	uniform float iridescenceThicknessMinimum;\n	uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n	uniform vec3 sheenColor;\n	uniform float sheenRoughness;\n	#ifdef USE_SHEEN_COLORMAP\n		uniform sampler2D sheenColorMap;\n	#endif\n	#ifdef USE_SHEEN_ROUGHNESSMAP\n		uniform sampler2D sheenRoughnessMap;\n	#endif\n#endif\n#ifdef USE_ANISOTROPY\n	uniform vec2 anisotropyVector;\n	#ifdef USE_ANISOTROPYMAP\n		uniform sampler2D anisotropyMap;\n	#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n	vec3 totalEmissiveRadiance = emissive;\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <roughnessmap_fragment>\n	#include <metalnessmap_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	#include <clearcoat_normal_fragment_begin>\n	#include <clearcoat_normal_fragment_maps>\n	#include <emissivemap_fragment>\n	#include <lights_physical_fragment>\n	#include <lights_fragment_begin>\n	#include <lights_fragment_maps>\n	#include <lights_fragment_end>\n	#include <aomap_fragment>\n	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n	#include <transmission_fragment>\n	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n	#ifdef USE_SHEEN\n		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n	#endif\n	#ifdef USE_CLEARCOAT\n		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n	#endif\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <normal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <displacementmap_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	vViewPosition = - mvPosition.xyz;\n	#include <worldpos_vertex>\n	#include <shadowmap_vertex>\n	#include <fog_vertex>\n}";
const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n	vec3 totalEmissiveRadiance = emissive;\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <color_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	#include <normal_fragment_begin>\n	#include <normal_fragment_maps>\n	#include <emissivemap_fragment>\n	#include <lights_toon_fragment>\n	#include <lights_fragment_begin>\n	#include <lights_fragment_maps>\n	#include <lights_fragment_end>\n	#include <aomap_fragment>\n	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n	#include <dithering_fragment>\n}";
const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n	varying vec2 vUv;\n	uniform mat3 uvTransform;\n#endif\nvoid main() {\n	#ifdef USE_POINTS_UV\n		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n	#endif\n	#include <color_vertex>\n	#include <morphinstance_vertex>\n	#include <morphcolor_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <project_vertex>\n	gl_PointSize = size;\n	#ifdef USE_SIZEATTENUATION\n		bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n	#endif\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	#include <worldpos_vertex>\n	#include <fog_vertex>\n}";
const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	vec3 outgoingLight = vec3( 0.0 );\n	#include <logdepthbuf_fragment>\n	#include <map_particle_fragment>\n	#include <color_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	outgoingLight = diffuseColor.rgb;\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n	#include <premultiplied_alpha_fragment>\n}";
const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n	#include <batching_vertex>\n	#include <beginnormal_vertex>\n	#include <morphinstance_vertex>\n	#include <morphnormal_vertex>\n	#include <skinbase_vertex>\n	#include <skinnormal_vertex>\n	#include <defaultnormal_vertex>\n	#include <begin_vertex>\n	#include <morphtarget_vertex>\n	#include <skinning_vertex>\n	#include <project_vertex>\n	#include <logdepthbuf_vertex>\n	#include <worldpos_vertex>\n	#include <shadowmap_vertex>\n	#include <fog_vertex>\n}";
const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n	#include <logdepthbuf_fragment>\n	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n}";
const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n	#include <uv_vertex>\n	vec4 mvPosition = modelViewMatrix[ 3 ];\n	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n	#ifndef USE_SIZEATTENUATION\n		bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n		if ( isPerspective ) scale *= - mvPosition.z;\n	#endif\n	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n	vec2 rotatedPosition;\n	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n	mvPosition.xy += rotatedPosition;\n	gl_Position = projectionMatrix * mvPosition;\n	#include <logdepthbuf_vertex>\n	#include <clipping_planes_vertex>\n	#include <fog_vertex>\n}";
const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n	vec4 diffuseColor = vec4( diffuse, opacity );\n	#include <clipping_planes_fragment>\n	vec3 outgoingLight = vec3( 0.0 );\n	#include <logdepthbuf_fragment>\n	#include <map_fragment>\n	#include <alphamap_fragment>\n	#include <alphatest_fragment>\n	#include <alphahash_fragment>\n	outgoingLight = diffuseColor.rgb;\n	#include <opaque_fragment>\n	#include <tonemapping_fragment>\n	#include <colorspace_fragment>\n	#include <fog_fragment>\n}";
const ShaderChunk = {
  alphahash_fragment,
  alphahash_pars_fragment,
  alphamap_fragment,
  alphamap_pars_fragment,
  alphatest_fragment,
  alphatest_pars_fragment,
  aomap_fragment,
  aomap_pars_fragment,
  batching_pars_vertex,
  batching_vertex,
  begin_vertex,
  beginnormal_vertex,
  bsdfs,
  iridescence_fragment,
  bumpmap_pars_fragment,
  clipping_planes_fragment,
  clipping_planes_pars_fragment,
  clipping_planes_pars_vertex,
  clipping_planes_vertex,
  color_fragment,
  color_pars_fragment,
  color_pars_vertex,
  color_vertex,
  common,
  cube_uv_reflection_fragment,
  defaultnormal_vertex,
  displacementmap_pars_vertex,
  displacementmap_vertex,
  emissivemap_fragment,
  emissivemap_pars_fragment,
  colorspace_fragment,
  colorspace_pars_fragment,
  envmap_fragment,
  envmap_common_pars_fragment,
  envmap_pars_fragment,
  envmap_pars_vertex,
  envmap_physical_pars_fragment,
  envmap_vertex,
  fog_vertex,
  fog_pars_vertex,
  fog_fragment,
  fog_pars_fragment,
  gradientmap_pars_fragment,
  lightmap_pars_fragment,
  lights_lambert_fragment,
  lights_lambert_pars_fragment,
  lights_pars_begin,
  lights_toon_fragment,
  lights_toon_pars_fragment,
  lights_phong_fragment,
  lights_phong_pars_fragment,
  lights_physical_fragment,
  lights_physical_pars_fragment,
  lights_fragment_begin,
  lights_fragment_maps,
  lights_fragment_end,
  logdepthbuf_fragment,
  logdepthbuf_pars_fragment,
  logdepthbuf_pars_vertex,
  logdepthbuf_vertex,
  map_fragment,
  map_pars_fragment,
  map_particle_fragment,
  map_particle_pars_fragment,
  metalnessmap_fragment,
  metalnessmap_pars_fragment,
  morphinstance_vertex,
  morphcolor_vertex,
  morphnormal_vertex,
  morphtarget_pars_vertex,
  morphtarget_vertex,
  normal_fragment_begin,
  normal_fragment_maps,
  normal_pars_fragment,
  normal_pars_vertex,
  normal_vertex,
  normalmap_pars_fragment,
  clearcoat_normal_fragment_begin,
  clearcoat_normal_fragment_maps,
  clearcoat_pars_fragment,
  iridescence_pars_fragment,
  opaque_fragment,
  packing,
  premultiplied_alpha_fragment,
  project_vertex,
  dithering_fragment,
  dithering_pars_fragment,
  roughnessmap_fragment,
  roughnessmap_pars_fragment,
  shadowmap_pars_fragment,
  shadowmap_pars_vertex,
  shadowmap_vertex,
  shadowmask_pars_fragment,
  skinbase_vertex,
  skinning_pars_vertex,
  skinning_vertex,
  skinnormal_vertex,
  specularmap_fragment,
  specularmap_pars_fragment,
  tonemapping_fragment,
  tonemapping_pars_fragment,
  transmission_fragment,
  transmission_pars_fragment,
  uv_pars_fragment,
  uv_pars_vertex,
  uv_vertex,
  worldpos_vertex,
  background_vert: vertex$h,
  background_frag: fragment$h,
  backgroundCube_vert: vertex$g,
  backgroundCube_frag: fragment$g,
  cube_vert: vertex$f,
  cube_frag: fragment$f,
  depth_vert: vertex$e,
  depth_frag: fragment$e,
  distanceRGBA_vert: vertex$d,
  distanceRGBA_frag: fragment$d,
  equirect_vert: vertex$c,
  equirect_frag: fragment$c,
  linedashed_vert: vertex$b,
  linedashed_frag: fragment$b,
  meshbasic_vert: vertex$a,
  meshbasic_frag: fragment$a,
  meshlambert_vert: vertex$9,
  meshlambert_frag: fragment$9,
  meshmatcap_vert: vertex$8,
  meshmatcap_frag: fragment$8,
  meshnormal_vert: vertex$7,
  meshnormal_frag: fragment$7,
  meshphong_vert: vertex$6,
  meshphong_frag: fragment$6,
  meshphysical_vert: vertex$5,
  meshphysical_frag: fragment$5,
  meshtoon_vert: vertex$4,
  meshtoon_frag: fragment$4,
  points_vert: vertex$3,
  points_frag: fragment$3,
  shadow_vert: vertex$2,
  shadow_frag: fragment$2,
  sprite_vert: vertex$1,
  sprite_frag: fragment$1
};
const UniformsLib = {
  common: {
    diffuse: { value: /* @__PURE__ */ new Color(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Matrix3() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    alphaTest: { value: 0 }
  },
  specularmap: {
    specularMap: { value: null },
    specularMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new Matrix3() },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    // basic, lambert, phong
    ior: { value: 1.5 },
    // physical
    refractionRatio: { value: 0.98 }
    // basic, lambert, phong
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  gradientmap: {
    gradientMap: { value: null }
  },
  fog: {
    fogDensity: { value: 25e-5 },
    fogNear: { value: 1 },
    fogFar: { value: 2e3 },
    fogColor: { value: /* @__PURE__ */ new Color(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMap: { value: [] },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotShadowMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    pointShadowMap: { value: [] },
    pointShadowMatrix: { value: [] },
    hemisphereLights: { value: [], properties: {
      direction: {},
      skyColor: {},
      groundColor: {}
    } },
    // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
    rectAreaLights: { value: [], properties: {
      color: {},
      position: {},
      width: {},
      height: {}
    } },
    ltc_1: { value: null },
    ltc_2: { value: null }
  },
  points: {
    diffuse: { value: /* @__PURE__ */ new Color(16777215) },
    opacity: { value: 1 },
    size: { value: 1 },
    scale: { value: 1 },
    map: { value: null },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    alphaTest: { value: 0 },
    uvTransform: { value: /* @__PURE__ */ new Matrix3() }
  },
  sprite: {
    diffuse: { value: /* @__PURE__ */ new Color(16777215) },
    opacity: { value: 1 },
    center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) },
    rotation: { value: 0 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Matrix3() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() },
    alphaTest: { value: 0 }
  }
};
const ShaderLib = {
  basic: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.meshbasic_vert,
    fragmentShader: ShaderChunk.meshbasic_frag
  },
  lambert: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color(0) }
      }
    ]),
    vertexShader: ShaderChunk.meshlambert_vert,
    fragmentShader: ShaderChunk.meshlambert_frag
  },
  phong: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color(0) },
        specular: { value: /* @__PURE__ */ new Color(1118481) },
        shininess: { value: 30 }
      }
    ]),
    vertexShader: ShaderChunk.meshphong_vert,
    fragmentShader: ShaderChunk.meshphong_frag
  },
  standard: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.roughnessmap,
      UniformsLib.metalnessmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.meshphysical_vert,
    fragmentShader: ShaderChunk.meshphysical_frag
  },
  toon: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.gradientmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color(0) }
      }
    ]),
    vertexShader: ShaderChunk.meshtoon_vert,
    fragmentShader: ShaderChunk.meshtoon_frag
  },
  matcap: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      {
        matcap: { value: null }
      }
    ]),
    vertexShader: ShaderChunk.meshmatcap_vert,
    fragmentShader: ShaderChunk.meshmatcap_frag
  },
  points: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.points,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.points_vert,
    fragmentShader: ShaderChunk.points_frag
  },
  dashed: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.fog,
      {
        scale: { value: 1 },
        dashSize: { value: 1 },
        totalSize: { value: 2 }
      }
    ]),
    vertexShader: ShaderChunk.linedashed_vert,
    fragmentShader: ShaderChunk.linedashed_frag
  },
  depth: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.displacementmap
    ]),
    vertexShader: ShaderChunk.depth_vert,
    fragmentShader: ShaderChunk.depth_frag
  },
  normal: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      {
        opacity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.meshnormal_vert,
    fragmentShader: ShaderChunk.meshnormal_frag
  },
  sprite: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.sprite,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.sprite_vert,
    fragmentShader: ShaderChunk.sprite_frag
  },
  background: {
    uniforms: {
      uvTransform: { value: /* @__PURE__ */ new Matrix3() },
      t2D: { value: null },
      backgroundIntensity: { value: 1 }
    },
    vertexShader: ShaderChunk.background_vert,
    fragmentShader: ShaderChunk.background_frag
  },
  backgroundCube: {
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 },
      backgroundBlurriness: { value: 0 },
      backgroundIntensity: { value: 1 },
      backgroundRotation: { value: /* @__PURE__ */ new Matrix3() }
    },
    vertexShader: ShaderChunk.backgroundCube_vert,
    fragmentShader: ShaderChunk.backgroundCube_frag
  },
  cube: {
    uniforms: {
      tCube: { value: null },
      tFlip: { value: -1 },
      opacity: { value: 1 }
    },
    vertexShader: ShaderChunk.cube_vert,
    fragmentShader: ShaderChunk.cube_frag
  },
  equirect: {
    uniforms: {
      tEquirect: { value: null }
    },
    vertexShader: ShaderChunk.equirect_vert,
    fragmentShader: ShaderChunk.equirect_frag
  },
  distanceRGBA: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.displacementmap,
      {
        referencePosition: { value: /* @__PURE__ */ new Vector3() },
        nearDistance: { value: 1 },
        farDistance: { value: 1e3 }
      }
    ]),
    vertexShader: ShaderChunk.distanceRGBA_vert,
    fragmentShader: ShaderChunk.distanceRGBA_frag
  },
  shadow: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.lights,
      UniformsLib.fog,
      {
        color: { value: /* @__PURE__ */ new Color(0) },
        opacity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.shadow_vert,
    fragmentShader: ShaderChunk.shadow_frag
  }
};
ShaderLib.physical = {
  uniforms: /* @__PURE__ */ mergeUniforms([
    ShaderLib.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new Color(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2() },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new Color(0) },
      specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3() },
      anisotropyVector: { value: /* @__PURE__ */ new Vector2() },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3() }
    }
  ]),
  vertexShader: ShaderChunk.meshphysical_vert,
  fragmentShader: ShaderChunk.meshphysical_frag
};
const _rgb = { r: 0, b: 0, g: 0 };
const _e1$1 = /* @__PURE__ */ new Euler();
const _m1$1 = /* @__PURE__ */ new Matrix4();
function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) {
  const clearColor = new Color(0);
  let clearAlpha = alpha === true ? 0 : 1;
  let planeMesh;
  let boxMesh;
  let currentBackground = null;
  let currentBackgroundVersion = 0;
  let currentTonemapping = null;
  function getBackground(scene) {
    let background = scene.isScene === true ? scene.background : null;
    if (background && background.isTexture) {
      const usePMREM = scene.backgroundBlurriness > 0;
      background = (usePMREM ? cubeuvmaps : cubemaps).get(background);
    }
    return background;
  }
  function render(scene) {
    let forceClear = false;
    const background = getBackground(scene);
    if (background === null) {
      setClear(clearColor, clearAlpha);
    } else if (background && background.isColor) {
      setClear(background, 1);
      forceClear = true;
    }
    const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
    if (environmentBlendMode === "additive") {
      state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha);
    } else if (environmentBlendMode === "alpha-blend") {
      state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha);
    }
    if (renderer.autoClear || forceClear) {
      state.buffers.depth.setTest(true);
      state.buffers.depth.setMask(true);
      state.buffers.color.setMask(true);
      renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
    }
  }
  function addToRenderList(renderList, scene) {
    const background = getBackground(scene);
    if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
      if (boxMesh === void 0) {
        boxMesh = new Mesh(
          new BoxGeometry(1, 1, 1),
          new ShaderMaterial({
            name: "BackgroundCubeMaterial",
            uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms),
            vertexShader: ShaderLib.backgroundCube.vertexShader,
            fragmentShader: ShaderLib.backgroundCube.fragmentShader,
            side: BackSide,
            depthTest: false,
            depthWrite: false,
            fog: false
          })
        );
        boxMesh.geometry.deleteAttribute("normal");
        boxMesh.geometry.deleteAttribute("uv");
        boxMesh.onBeforeRender = function(renderer2, scene2, camera) {
          this.matrixWorld.copyPosition(camera.matrixWorld);
        };
        Object.defineProperty(boxMesh.material, "envMap", {
          get: function() {
            return this.uniforms.envMap.value;
          }
        });
        objects.update(boxMesh);
      }
      _e1$1.copy(scene.backgroundRotation);
      _e1$1.x *= -1;
      _e1$1.y *= -1;
      _e1$1.z *= -1;
      if (background.isCubeTexture && background.isRenderTargetTexture === false) {
        _e1$1.y *= -1;
        _e1$1.z *= -1;
      }
      boxMesh.material.uniforms.envMap.value = background;
      boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
      boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
      boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
      boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$1.makeRotationFromEuler(_e1$1));
      boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer;
      if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
        boxMesh.material.needsUpdate = true;
        currentBackground = background;
        currentBackgroundVersion = background.version;
        currentTonemapping = renderer.toneMapping;
      }
      boxMesh.layers.enableAll();
      renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
    } else if (background && background.isTexture) {
      if (planeMesh === void 0) {
        planeMesh = new Mesh(
          new PlaneGeometry(2, 2),
          new ShaderMaterial({
            name: "BackgroundMaterial",
            uniforms: cloneUniforms(ShaderLib.background.uniforms),
            vertexShader: ShaderLib.background.vertexShader,
            fragmentShader: ShaderLib.background.fragmentShader,
            side: FrontSide,
            depthTest: false,
            depthWrite: false,
            fog: false
          })
        );
        planeMesh.geometry.deleteAttribute("normal");
        Object.defineProperty(planeMesh.material, "map", {
          get: function() {
            return this.uniforms.t2D.value;
          }
        });
        objects.update(planeMesh);
      }
      planeMesh.material.uniforms.t2D.value = background;
      planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
      planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer;
      if (background.matrixAutoUpdate === true) {
        background.updateMatrix();
      }
      planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
      if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
        planeMesh.material.needsUpdate = true;
        currentBackground = background;
        currentBackgroundVersion = background.version;
        currentTonemapping = renderer.toneMapping;
      }
      planeMesh.layers.enableAll();
      renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
    }
  }
  function setClear(color, alpha2) {
    color.getRGB(_rgb, getUnlitUniformColorSpace(renderer));
    state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha);
  }
  function dispose2() {
    if (boxMesh !== void 0) {
      boxMesh.geometry.dispose();
      boxMesh.material.dispose();
    }
    if (planeMesh !== void 0) {
      planeMesh.geometry.dispose();
      planeMesh.material.dispose();
    }
  }
  return {
    getClearColor: function() {
      return clearColor;
    },
    setClearColor: function(color, alpha2 = 1) {
      clearColor.set(color);
      clearAlpha = alpha2;
      setClear(clearColor, clearAlpha);
    },
    getClearAlpha: function() {
      return clearAlpha;
    },
    setClearAlpha: function(alpha2) {
      clearAlpha = alpha2;
      setClear(clearColor, clearAlpha);
    },
    render,
    addToRenderList,
    dispose: dispose2
  };
}
function WebGLBindingStates(gl, attributes) {
  const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  const bindingStates = {};
  const defaultState = createBindingState(null);
  let currentState = defaultState;
  let forceUpdate = false;
  function setup(object, material, program, geometry, index) {
    let updateBuffers = false;
    const state = getBindingState(geometry, program, material);
    if (currentState !== state) {
      currentState = state;
      bindVertexArrayObject(currentState.object);
    }
    updateBuffers = needsUpdate(object, geometry, program, index);
    if (updateBuffers) saveCache(object, geometry, program, index);
    if (index !== null) {
      attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
    }
    if (updateBuffers || forceUpdate) {
      forceUpdate = false;
      setupVertexAttributes(object, material, program, geometry);
      if (index !== null) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
      }
    }
  }
  function createVertexArrayObject() {
    return gl.createVertexArray();
  }
  function bindVertexArrayObject(vao) {
    return gl.bindVertexArray(vao);
  }
  function deleteVertexArrayObject(vao) {
    return gl.deleteVertexArray(vao);
  }
  function getBindingState(geometry, program, material) {
    const wireframe = material.wireframe === true;
    let programMap = bindingStates[geometry.id];
    if (programMap === void 0) {
      programMap = {};
      bindingStates[geometry.id] = programMap;
    }
    let stateMap = programMap[program.id];
    if (stateMap === void 0) {
      stateMap = {};
      programMap[program.id] = stateMap;
    }
    let state = stateMap[wireframe];
    if (state === void 0) {
      state = createBindingState(createVertexArrayObject());
      stateMap[wireframe] = state;
    }
    return state;
  }
  function createBindingState(vao) {
    const newAttributes = [];
    const enabledAttributes = [];
    const attributeDivisors = [];
    for (let i2 = 0; i2 < maxVertexAttributes; i2++) {
      newAttributes[i2] = 0;
      enabledAttributes[i2] = 0;
      attributeDivisors[i2] = 0;
    }
    return {
      // for backward compatibility on non-VAO support browser
      geometry: null,
      program: null,
      wireframe: false,
      newAttributes,
      enabledAttributes,
      attributeDivisors,
      object: vao,
      attributes: {},
      index: null
    };
  }
  function needsUpdate(object, geometry, program, index) {
    const cachedAttributes = currentState.attributes;
    const geometryAttributes = geometry.attributes;
    let attributesNum = 0;
    const programAttributes = program.getAttributes();
    for (const name in programAttributes) {
      const programAttribute = programAttributes[name];
      if (programAttribute.location >= 0) {
        const cachedAttribute = cachedAttributes[name];
        let geometryAttribute = geometryAttributes[name];
        if (geometryAttribute === void 0) {
          if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
          if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor;
        }
        if (cachedAttribute === void 0) return true;
        if (cachedAttribute.attribute !== geometryAttribute) return true;
        if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
        attributesNum++;
      }
    }
    if (currentState.attributesNum !== attributesNum) return true;
    if (currentState.index !== index) return true;
    return false;
  }
  function saveCache(object, geometry, program, index) {
    const cache = {};
    const attributes2 = geometry.attributes;
    let attributesNum = 0;
    const programAttributes = program.getAttributes();
    for (const name in programAttributes) {
      const programAttribute = programAttributes[name];
      if (programAttribute.location >= 0) {
        let attribute = attributes2[name];
        if (attribute === void 0) {
          if (name === "instanceMatrix" && object.instanceMatrix) attribute = object.instanceMatrix;
          if (name === "instanceColor" && object.instanceColor) attribute = object.instanceColor;
        }
        const data = {};
        data.attribute = attribute;
        if (attribute && attribute.data) {
          data.data = attribute.data;
        }
        cache[name] = data;
        attributesNum++;
      }
    }
    currentState.attributes = cache;
    currentState.attributesNum = attributesNum;
    currentState.index = index;
  }
  function initAttributes() {
    const newAttributes = currentState.newAttributes;
    for (let i2 = 0, il = newAttributes.length; i2 < il; i2++) {
      newAttributes[i2] = 0;
    }
  }
  function enableAttribute(attribute) {
    enableAttributeAndDivisor(attribute, 0);
  }
  function enableAttributeAndDivisor(attribute, meshPerAttribute) {
    const newAttributes = currentState.newAttributes;
    const enabledAttributes = currentState.enabledAttributes;
    const attributeDivisors = currentState.attributeDivisors;
    newAttributes[attribute] = 1;
    if (enabledAttributes[attribute] === 0) {
      gl.enableVertexAttribArray(attribute);
      enabledAttributes[attribute] = 1;
    }
    if (attributeDivisors[attribute] !== meshPerAttribute) {
      gl.vertexAttribDivisor(attribute, meshPerAttribute);
      attributeDivisors[attribute] = meshPerAttribute;
    }
  }
  function disableUnusedAttributes() {
    const newAttributes = currentState.newAttributes;
    const enabledAttributes = currentState.enabledAttributes;
    for (let i2 = 0, il = enabledAttributes.length; i2 < il; i2++) {
      if (enabledAttributes[i2] !== newAttributes[i2]) {
        gl.disableVertexAttribArray(i2);
        enabledAttributes[i2] = 0;
      }
    }
  }
  function vertexAttribPointer(index, size, type, normalized, stride, offset, integer) {
    if (integer === true) {
      gl.vertexAttribIPointer(index, size, type, stride, offset);
    } else {
      gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
    }
  }
  function setupVertexAttributes(object, material, program, geometry) {
    initAttributes();
    const geometryAttributes = geometry.attributes;
    const programAttributes = program.getAttributes();
    const materialDefaultAttributeValues = material.defaultAttributeValues;
    for (const name in programAttributes) {
      const programAttribute = programAttributes[name];
      if (programAttribute.location >= 0) {
        let geometryAttribute = geometryAttributes[name];
        if (geometryAttribute === void 0) {
          if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
          if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor;
        }
        if (geometryAttribute !== void 0) {
          const normalized = geometryAttribute.normalized;
          const size = geometryAttribute.itemSize;
          const attribute = attributes.get(geometryAttribute);
          if (attribute === void 0) continue;
          const buffer = attribute.buffer;
          const type = attribute.type;
          const bytesPerElement = attribute.bytesPerElement;
          const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType;
          if (geometryAttribute.isInterleavedBufferAttribute) {
            const data = geometryAttribute.data;
            const stride = data.stride;
            const offset = geometryAttribute.offset;
            if (data.isInstancedInterleavedBuffer) {
              for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
                enableAttributeAndDivisor(programAttribute.location + i2, data.meshPerAttribute);
              }
              if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) {
                geometry._maxInstanceCount = data.meshPerAttribute * data.count;
              }
            } else {
              for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
                enableAttribute(programAttribute.location + i2);
              }
            }
            gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
              vertexAttribPointer(
                programAttribute.location + i2,
                size / programAttribute.locationSize,
                type,
                normalized,
                stride * bytesPerElement,
                (offset + size / programAttribute.locationSize * i2) * bytesPerElement,
                integer
              );
            }
          } else {
            if (geometryAttribute.isInstancedBufferAttribute) {
              for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
                enableAttributeAndDivisor(programAttribute.location + i2, geometryAttribute.meshPerAttribute);
              }
              if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) {
                geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
              }
            } else {
              for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
                enableAttribute(programAttribute.location + i2);
              }
            }
            gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            for (let i2 = 0; i2 < programAttribute.locationSize; i2++) {
              vertexAttribPointer(
                programAttribute.location + i2,
                size / programAttribute.locationSize,
                type,
                normalized,
                size * bytesPerElement,
                size / programAttribute.locationSize * i2 * bytesPerElement,
                integer
              );
            }
          }
        } else if (materialDefaultAttributeValues !== void 0) {
          const value = materialDefaultAttributeValues[name];
          if (value !== void 0) {
            switch (value.length) {
              case 2:
                gl.vertexAttrib2fv(programAttribute.location, value);
                break;
              case 3:
                gl.vertexAttrib3fv(programAttribute.location, value);
                break;
              case 4:
                gl.vertexAttrib4fv(programAttribute.location, value);
                break;
              default:
                gl.vertexAttrib1fv(programAttribute.location, value);
            }
          }
        }
      }
    }
    disableUnusedAttributes();
  }
  function dispose2() {
    reset();
    for (const geometryId in bindingStates) {
      const programMap = bindingStates[geometryId];
      for (const programId in programMap) {
        const stateMap = programMap[programId];
        for (const wireframe in stateMap) {
          deleteVertexArrayObject(stateMap[wireframe].object);
          delete stateMap[wireframe];
        }
        delete programMap[programId];
      }
      delete bindingStates[geometryId];
    }
  }
  function releaseStatesOfGeometry(geometry) {
    if (bindingStates[geometry.id] === void 0) return;
    const programMap = bindingStates[geometry.id];
    for (const programId in programMap) {
      const stateMap = programMap[programId];
      for (const wireframe in stateMap) {
        deleteVertexArrayObject(stateMap[wireframe].object);
        delete stateMap[wireframe];
      }
      delete programMap[programId];
    }
    delete bindingStates[geometry.id];
  }
  function releaseStatesOfProgram(program) {
    for (const geometryId in bindingStates) {
      const programMap = bindingStates[geometryId];
      if (programMap[program.id] === void 0) continue;
      const stateMap = programMap[program.id];
      for (const wireframe in stateMap) {
        deleteVertexArrayObject(stateMap[wireframe].object);
        delete stateMap[wireframe];
      }
      delete programMap[program.id];
    }
  }
  function reset() {
    resetDefaultState();
    forceUpdate = true;
    if (currentState === defaultState) return;
    currentState = defaultState;
    bindVertexArrayObject(currentState.object);
  }
  function resetDefaultState() {
    defaultState.geometry = null;
    defaultState.program = null;
    defaultState.wireframe = false;
  }
  return {
    setup,
    reset,
    resetDefaultState,
    dispose: dispose2,
    releaseStatesOfGeometry,
    releaseStatesOfProgram,
    initAttributes,
    enableAttribute,
    disableUnusedAttributes
  };
}
function WebGLBufferRenderer(gl, extensions, info) {
  let mode2;
  function setMode(value) {
    mode2 = value;
  }
  function render(start, count) {
    gl.drawArrays(mode2, start, count);
    info.update(count, mode2, 1);
  }
  function renderInstances(start, count, primcount) {
    if (primcount === 0) return;
    gl.drawArraysInstanced(mode2, start, count, primcount);
    info.update(count, mode2, primcount);
  }
  function renderMultiDraw(starts, counts, drawCount) {
    if (drawCount === 0) return;
    const extension = extensions.get("WEBGL_multi_draw");
    extension.multiDrawArraysWEBGL(mode2, starts, 0, counts, 0, drawCount);
    let elementCount = 0;
    for (let i2 = 0; i2 < drawCount; i2++) {
      elementCount += counts[i2];
    }
    info.update(elementCount, mode2, 1);
  }
  function renderMultiDrawInstances(starts, counts, drawCount, primcount) {
    if (drawCount === 0) return;
    const extension = extensions.get("WEBGL_multi_draw");
    if (extension === null) {
      for (let i2 = 0; i2 < starts.length; i2++) {
        renderInstances(starts[i2], counts[i2], primcount[i2]);
      }
    } else {
      extension.multiDrawArraysInstancedWEBGL(mode2, starts, 0, counts, 0, primcount, 0, drawCount);
      let elementCount = 0;
      for (let i2 = 0; i2 < drawCount; i2++) {
        elementCount += counts[i2] * primcount[i2];
      }
      info.update(elementCount, mode2, 1);
    }
  }
  this.setMode = setMode;
  this.render = render;
  this.renderInstances = renderInstances;
  this.renderMultiDraw = renderMultiDraw;
  this.renderMultiDrawInstances = renderMultiDrawInstances;
}
function WebGLCapabilities(gl, extensions, parameters, utils) {
  let maxAnisotropy;
  function getMaxAnisotropy() {
    if (maxAnisotropy !== void 0) return maxAnisotropy;
    if (extensions.has("EXT_texture_filter_anisotropic") === true) {
      const extension = extensions.get("EXT_texture_filter_anisotropic");
      maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
    } else {
      maxAnisotropy = 0;
    }
    return maxAnisotropy;
  }
  function textureFormatReadable(textureFormat) {
    if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
      return false;
    }
    return true;
  }
  function textureTypeReadable(textureType) {
    const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float"));
    if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
    textureType !== FloatType && !halfFloatSupportedByExt) {
      return false;
    }
    return true;
  }
  function getMaxPrecision(precision2) {
    if (precision2 === "highp") {
      if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
        return "highp";
      }
      precision2 = "mediump";
    }
    if (precision2 === "mediump") {
      if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
        return "mediump";
      }
    }
    return "lowp";
  }
  let precision = parameters.precision !== void 0 ? parameters.precision : "highp";
  const maxPrecision = getMaxPrecision(precision);
  if (maxPrecision !== precision) {
    console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead.");
    precision = maxPrecision;
  }
  const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control");
  const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  const vertexTextures = maxVertexTextures > 0;
  const maxSamples = gl.getParameter(gl.MAX_SAMPLES);
  return {
    isWebGL2: true,
    // keeping this for backwards compatibility
    getMaxAnisotropy,
    getMaxPrecision,
    textureFormatReadable,
    textureTypeReadable,
    precision,
    logarithmicDepthBuffer,
    reverseDepthBuffer,
    maxTextures,
    maxVertexTextures,
    maxTextureSize,
    maxCubemapSize,
    maxAttributes,
    maxVertexUniforms,
    maxVaryings,
    maxFragmentUniforms,
    vertexTextures,
    maxSamples
  };
}
function WebGLClipping(properties) {
  const scope = this;
  let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false;
  const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false };
  this.uniform = uniform;
  this.numPlanes = 0;
  this.numIntersection = 0;
  this.init = function(planes, enableLocalClipping) {
    const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
    // run another frame in order to reset the state:
    numGlobalPlanes !== 0 || localClippingEnabled;
    localClippingEnabled = enableLocalClipping;
    numGlobalPlanes = planes.length;
    return enabled;
  };
  this.beginShadows = function() {
    renderingShadows = true;
    projectPlanes(null);
  };
  this.endShadows = function() {
    renderingShadows = false;
  };
  this.setGlobalState = function(planes, camera) {
    globalState = projectPlanes(planes, camera, 0);
  };
  this.setState = function(material, camera, useCache) {
    const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows;
    const materialProperties = properties.get(material);
    if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
      if (renderingShadows) {
        projectPlanes(null);
      } else {
        resetGlobalState();
      }
    } else {
      const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4;
      let dstArray = materialProperties.clippingState || null;
      uniform.value = dstArray;
      dstArray = projectPlanes(planes, camera, lGlobal, useCache);
      for (let i2 = 0; i2 !== lGlobal; ++i2) {
        dstArray[i2] = globalState[i2];
      }
      materialProperties.clippingState = dstArray;
      this.numIntersection = clipIntersection ? this.numPlanes : 0;
      this.numPlanes += nGlobal;
    }
  };
  function resetGlobalState() {
    if (uniform.value !== globalState) {
      uniform.value = globalState;
      uniform.needsUpdate = numGlobalPlanes > 0;
    }
    scope.numPlanes = numGlobalPlanes;
    scope.numIntersection = 0;
  }
  function projectPlanes(planes, camera, dstOffset, skipTransform) {
    const nPlanes = planes !== null ? planes.length : 0;
    let dstArray = null;
    if (nPlanes !== 0) {
      dstArray = uniform.value;
      if (skipTransform !== true || dstArray === null) {
        const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse;
        viewNormalMatrix.getNormalMatrix(viewMatrix);
        if (dstArray === null || dstArray.length < flatSize) {
          dstArray = new Float32Array(flatSize);
        }
        for (let i2 = 0, i4 = dstOffset; i2 !== nPlanes; ++i2, i4 += 4) {
          plane.copy(planes[i2]).applyMatrix4(viewMatrix, viewNormalMatrix);
          plane.normal.toArray(dstArray, i4);
          dstArray[i4 + 3] = plane.constant;
        }
      }
      uniform.value = dstArray;
      uniform.needsUpdate = true;
    }
    scope.numPlanes = nPlanes;
    scope.numIntersection = 0;
    return dstArray;
  }
}
function WebGLCubeMaps(renderer) {
  let cubemaps = /* @__PURE__ */ new WeakMap();
  function mapTextureMapping(texture, mapping) {
    if (mapping === EquirectangularReflectionMapping) {
      texture.mapping = CubeReflectionMapping;
    } else if (mapping === EquirectangularRefractionMapping) {
      texture.mapping = CubeRefractionMapping;
    }
    return texture;
  }
  function get(texture) {
    if (texture && texture.isTexture) {
      const mapping = texture.mapping;
      if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
        if (cubemaps.has(texture)) {
          const cubemap = cubemaps.get(texture).texture;
          return mapTextureMapping(cubemap, texture.mapping);
        } else {
          const image = texture.image;
          if (image && image.height > 0) {
            const renderTarget = new WebGLCubeRenderTarget(image.height);
            renderTarget.fromEquirectangularTexture(renderer, texture);
            cubemaps.set(texture, renderTarget);
            texture.addEventListener("dispose", onTextureDispose);
            return mapTextureMapping(renderTarget.texture, texture.mapping);
          } else {
            return null;
          }
        }
      }
    }
    return texture;
  }
  function onTextureDispose(event) {
    const texture = event.target;
    texture.removeEventListener("dispose", onTextureDispose);
    const cubemap = cubemaps.get(texture);
    if (cubemap !== void 0) {
      cubemaps.delete(texture);
      cubemap.dispose();
    }
  }
  function dispose2() {
    cubemaps = /* @__PURE__ */ new WeakMap();
  }
  return {
    get,
    dispose: dispose2
  };
}
const LOD_MIN = 4;
const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
const MAX_SAMPLES = 20;
const _flatCamera = /* @__PURE__ */ new OrthographicCamera();
const _clearColor = /* @__PURE__ */ new Color();
let _oldTarget = null;
let _oldActiveCubeFace = 0;
let _oldActiveMipmapLevel = 0;
let _oldXrEnabled = false;
const PHI = (1 + Math.sqrt(5)) / 2;
const INV_PHI = 1 / PHI;
const _axisDirections = [
  /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0),
  /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0),
  /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI),
  /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI),
  /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI),
  /* @__PURE__ */ new Vector3(0, PHI, INV_PHI),
  /* @__PURE__ */ new Vector3(-1, 1, -1),
  /* @__PURE__ */ new Vector3(1, 1, -1),
  /* @__PURE__ */ new Vector3(-1, 1, 1),
  /* @__PURE__ */ new Vector3(1, 1, 1)
];
class PMREMGenerator {
  constructor(renderer) {
    this._renderer = renderer;
    this._pingPongRenderTarget = null;
    this._lodMax = 0;
    this._cubeSize = 0;
    this._lodPlanes = [];
    this._sizeLods = [];
    this._sigmas = [];
    this._blurMaterial = null;
    this._cubemapMaterial = null;
    this._equirectMaterial = null;
    this._compileMaterial(this._blurMaterial);
  }
  /**
   * Generates a PMREM from a supplied Scene, which can be faster than using an
   * image if networking bandwidth is low. Optional sigma specifies a blur radius
   * in radians to be applied to the scene before PMREM generation. Optional near
   * and far planes ensure the scene is rendered in its entirety (the cubeCamera
   * is placed at the origin).
   */
  fromScene(scene, sigma = 0, near = 0.1, far = 100) {
    _oldTarget = this._renderer.getRenderTarget();
    _oldActiveCubeFace = this._renderer.getActiveCubeFace();
    _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
    _oldXrEnabled = this._renderer.xr.enabled;
    this._renderer.xr.enabled = false;
    this._setSize(256);
    const cubeUVRenderTarget = this._allocateTargets();
    cubeUVRenderTarget.depthBuffer = true;
    this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
    if (sigma > 0) {
      this._blur(cubeUVRenderTarget, 0, 0, sigma);
    }
    this._applyPMREM(cubeUVRenderTarget);
    this._cleanup(cubeUVRenderTarget);
    return cubeUVRenderTarget;
  }
  /**
   * Generates a PMREM from an equirectangular texture, which can be either LDR
   * or HDR. The ideal input image size is 1k (1024 x 512),
   * as this matches best with the 256 x 256 cubemap output.
   * The smallest supported equirectangular image size is 64 x 32.
   */
  fromEquirectangular(equirectangular, renderTarget = null) {
    return this._fromTexture(equirectangular, renderTarget);
  }
  /**
   * Generates a PMREM from an cubemap texture, which can be either LDR
   * or HDR. The ideal input cube size is 256 x 256,
   * as this matches best with the 256 x 256 cubemap output.
   * The smallest supported cube size is 16 x 16.
   */
  fromCubemap(cubemap, renderTarget = null) {
    return this._fromTexture(cubemap, renderTarget);
  }
  /**
   * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileCubemapShader() {
    if (this._cubemapMaterial === null) {
      this._cubemapMaterial = _getCubemapMaterial();
      this._compileMaterial(this._cubemapMaterial);
    }
  }
  /**
   * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileEquirectangularShader() {
    if (this._equirectMaterial === null) {
      this._equirectMaterial = _getEquirectMaterial();
      this._compileMaterial(this._equirectMaterial);
    }
  }
  /**
   * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
   * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
   * one of them will cause any others to also become unusable.
   */
  dispose() {
    this._dispose();
    if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
    if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  }
  // private interface
  _setSize(cubeSize) {
    this._lodMax = Math.floor(Math.log2(cubeSize));
    this._cubeSize = Math.pow(2, this._lodMax);
  }
  _dispose() {
    if (this._blurMaterial !== null) this._blurMaterial.dispose();
    if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
    for (let i2 = 0; i2 < this._lodPlanes.length; i2++) {
      this._lodPlanes[i2].dispose();
    }
  }
  _cleanup(outputTarget) {
    this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel);
    this._renderer.xr.enabled = _oldXrEnabled;
    outputTarget.scissorTest = false;
    _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  }
  _fromTexture(texture, renderTarget) {
    if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
      this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
    } else {
      this._setSize(texture.image.width / 4);
    }
    _oldTarget = this._renderer.getRenderTarget();
    _oldActiveCubeFace = this._renderer.getActiveCubeFace();
    _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
    _oldXrEnabled = this._renderer.xr.enabled;
    this._renderer.xr.enabled = false;
    const cubeUVRenderTarget = renderTarget || this._allocateTargets();
    this._textureToCubeUV(texture, cubeUVRenderTarget);
    this._applyPMREM(cubeUVRenderTarget);
    this._cleanup(cubeUVRenderTarget);
    return cubeUVRenderTarget;
  }
  _allocateTargets() {
    const width = 3 * Math.max(this._cubeSize, 16 * 7);
    const height = 4 * this._cubeSize;
    const params = {
      magFilter: LinearFilter,
      minFilter: LinearFilter,
      generateMipmaps: false,
      type: HalfFloatType,
      format: RGBAFormat,
      colorSpace: LinearSRGBColorSpace,
      depthBuffer: false
    };
    const cubeUVRenderTarget = _createRenderTarget(width, height, params);
    if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height) {
      if (this._pingPongRenderTarget !== null) {
        this._dispose();
      }
      this._pingPongRenderTarget = _createRenderTarget(width, height, params);
      const { _lodMax } = this;
      ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax));
      this._blurMaterial = _getBlurShader(_lodMax, width, height);
    }
    return cubeUVRenderTarget;
  }
  _compileMaterial(material) {
    const tmpMesh = new Mesh(this._lodPlanes[0], material);
    this._renderer.compile(tmpMesh, _flatCamera);
  }
  _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
    const fov2 = 90;
    const aspect2 = 1;
    const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far);
    const upSign = [1, -1, 1, 1, 1, 1];
    const forwardSign = [1, 1, 1, -1, -1, -1];
    const renderer = this._renderer;
    const originalAutoClear = renderer.autoClear;
    const toneMapping = renderer.toneMapping;
    renderer.getClearColor(_clearColor);
    renderer.toneMapping = NoToneMapping;
    renderer.autoClear = false;
    const backgroundMaterial = new MeshBasicMaterial({
      name: "PMREM.Background",
      side: BackSide,
      depthWrite: false,
      depthTest: false
    });
    const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
    let useSolidColor = false;
    const background = scene.background;
    if (background) {
      if (background.isColor) {
        backgroundMaterial.color.copy(background);
        scene.background = null;
        useSolidColor = true;
      }
    } else {
      backgroundMaterial.color.copy(_clearColor);
      useSolidColor = true;
    }
    for (let i2 = 0; i2 < 6; i2++) {
      const col = i2 % 3;
      if (col === 0) {
        cubeCamera.up.set(0, upSign[i2], 0);
        cubeCamera.lookAt(forwardSign[i2], 0, 0);
      } else if (col === 1) {
        cubeCamera.up.set(0, 0, upSign[i2]);
        cubeCamera.lookAt(0, forwardSign[i2], 0);
      } else {
        cubeCamera.up.set(0, upSign[i2], 0);
        cubeCamera.lookAt(0, 0, forwardSign[i2]);
      }
      const size = this._cubeSize;
      _setViewport(cubeUVRenderTarget, col * size, i2 > 2 ? size : 0, size, size);
      renderer.setRenderTarget(cubeUVRenderTarget);
      if (useSolidColor) {
        renderer.render(backgroundBox, cubeCamera);
      }
      renderer.render(scene, cubeCamera);
    }
    backgroundBox.geometry.dispose();
    backgroundBox.material.dispose();
    renderer.toneMapping = toneMapping;
    renderer.autoClear = originalAutoClear;
    scene.background = background;
  }
  _textureToCubeUV(texture, cubeUVRenderTarget) {
    const renderer = this._renderer;
    const isCubeTexture2 = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
    if (isCubeTexture2) {
      if (this._cubemapMaterial === null) {
        this._cubemapMaterial = _getCubemapMaterial();
      }
      this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
    } else {
      if (this._equirectMaterial === null) {
        this._equirectMaterial = _getEquirectMaterial();
      }
    }
    const material = isCubeTexture2 ? this._cubemapMaterial : this._equirectMaterial;
    const mesh = new Mesh(this._lodPlanes[0], material);
    const uniforms = material.uniforms;
    uniforms["envMap"].value = texture;
    const size = this._cubeSize;
    _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
    renderer.setRenderTarget(cubeUVRenderTarget);
    renderer.render(mesh, _flatCamera);
  }
  _applyPMREM(cubeUVRenderTarget) {
    const renderer = this._renderer;
    const autoClear = renderer.autoClear;
    renderer.autoClear = false;
    const n2 = this._lodPlanes.length;
    for (let i2 = 1; i2 < n2; i2++) {
      const sigma = Math.sqrt(this._sigmas[i2] * this._sigmas[i2] - this._sigmas[i2 - 1] * this._sigmas[i2 - 1]);
      const poleAxis = _axisDirections[(n2 - i2 - 1) % _axisDirections.length];
      this._blur(cubeUVRenderTarget, i2 - 1, i2, sigma, poleAxis);
    }
    renderer.autoClear = autoClear;
  }
  /**
   * This is a two-pass Gaussian blur for a cubemap. Normally this is done
   * vertically and horizontally, but this breaks down on a cube. Here we apply
   * the blur latitudinally (around the poles), and then longitudinally (towards
   * the poles) to approximate the orthogonally-separable blur. It is least
   * accurate at the poles, but still does a decent job.
   */
  _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
    const pingPongRenderTarget = this._pingPongRenderTarget;
    this._halfBlur(
      cubeUVRenderTarget,
      pingPongRenderTarget,
      lodIn,
      lodOut,
      sigma,
      "latitudinal",
      poleAxis
    );
    this._halfBlur(
      pingPongRenderTarget,
      cubeUVRenderTarget,
      lodOut,
      lodOut,
      sigma,
      "longitudinal",
      poleAxis
    );
  }
  _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
    const renderer = this._renderer;
    const blurMaterial = this._blurMaterial;
    if (direction !== "latitudinal" && direction !== "longitudinal") {
      console.error(
        "blur direction must be either latitudinal or longitudinal!"
      );
    }
    const STANDARD_DEVIATIONS = 3;
    const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
    const blurUniforms = blurMaterial.uniforms;
    const pixels = this._sizeLods[lodIn] - 1;
    const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
    const sigmaPixels = sigmaRadians / radiansPerPixel;
    const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
    if (samples > MAX_SAMPLES) {
      console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
    }
    const weights = [];
    let sum = 0;
    for (let i2 = 0; i2 < MAX_SAMPLES; ++i2) {
      const x2 = i2 / sigmaPixels;
      const weight = Math.exp(-x2 * x2 / 2);
      weights.push(weight);
      if (i2 === 0) {
        sum += weight;
      } else if (i2 < samples) {
        sum += 2 * weight;
      }
    }
    for (let i2 = 0; i2 < weights.length; i2++) {
      weights[i2] = weights[i2] / sum;
    }
    blurUniforms["envMap"].value = targetIn.texture;
    blurUniforms["samples"].value = samples;
    blurUniforms["weights"].value = weights;
    blurUniforms["latitudinal"].value = direction === "latitudinal";
    if (poleAxis) {
      blurUniforms["poleAxis"].value = poleAxis;
    }
    const { _lodMax } = this;
    blurUniforms["dTheta"].value = radiansPerPixel;
    blurUniforms["mipInt"].value = _lodMax - lodIn;
    const outputSize = this._sizeLods[lodOut];
    const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
    const y2 = 4 * (this._cubeSize - outputSize);
    _setViewport(targetOut, x, y2, 3 * outputSize, 2 * outputSize);
    renderer.setRenderTarget(targetOut);
    renderer.render(blurMesh, _flatCamera);
  }
}
function _createPlanes(lodMax) {
  const lodPlanes = [];
  const sizeLods = [];
  const sigmas = [];
  let lod = lodMax;
  const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  for (let i2 = 0; i2 < totalLods; i2++) {
    const sizeLod = Math.pow(2, lod);
    sizeLods.push(sizeLod);
    let sigma = 1 / sizeLod;
    if (i2 > lodMax - LOD_MIN) {
      sigma = EXTRA_LOD_SIGMA[i2 - lodMax + LOD_MIN - 1];
    } else if (i2 === 0) {
      sigma = 0;
    }
    sigmas.push(sigma);
    const texelSize = 1 / (sizeLod - 2);
    const min = -texelSize;
    const max2 = 1 + texelSize;
    const uv1 = [min, min, max2, min, max2, max2, min, min, max2, max2, min, max2];
    const cubeFaces = 6;
    const vertices = 6;
    const positionSize = 3;
    const uvSize = 2;
    const faceIndexSize = 1;
    const position = new Float32Array(positionSize * vertices * cubeFaces);
    const uv = new Float32Array(uvSize * vertices * cubeFaces);
    const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
    for (let face = 0; face < cubeFaces; face++) {
      const x = face % 3 * 2 / 3 - 1;
      const y2 = face > 2 ? 0 : -1;
      const coordinates = [
        x,
        y2,
        0,
        x + 2 / 3,
        y2,
        0,
        x + 2 / 3,
        y2 + 1,
        0,
        x,
        y2,
        0,
        x + 2 / 3,
        y2 + 1,
        0,
        x,
        y2 + 1,
        0
      ];
      position.set(coordinates, positionSize * vertices * face);
      uv.set(uv1, uvSize * vertices * face);
      const fill2 = [face, face, face, face, face, face];
      faceIndex.set(fill2, faceIndexSize * vertices * face);
    }
    const planes = new BufferGeometry();
    planes.setAttribute("position", new BufferAttribute(position, positionSize));
    planes.setAttribute("uv", new BufferAttribute(uv, uvSize));
    planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize));
    lodPlanes.push(planes);
    if (lod > LOD_MIN) {
      lod--;
    }
  }
  return { lodPlanes, sizeLods, sigmas };
}
function _createRenderTarget(width, height, params) {
  const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  cubeUVRenderTarget.texture.name = "PMREM.cubeUv";
  cubeUVRenderTarget.scissorTest = true;
  return cubeUVRenderTarget;
}
function _setViewport(target, x, y2, width, height) {
  target.viewport.set(x, y2, width, height);
  target.scissor.set(x, y2, width, height);
}
function _getBlurShader(lodMax, width, height) {
  const weights = new Float32Array(MAX_SAMPLES);
  const poleAxis = new Vector3(0, 1, 0);
  const shaderMaterial2 = new ShaderMaterial({
    name: "SphericalGaussianBlur",
    defines: {
      "n": MAX_SAMPLES,
      "CUBEUV_TEXEL_WIDTH": 1 / width,
      "CUBEUV_TEXEL_HEIGHT": 1 / height,
      "CUBEUV_MAX_MIP": `${lodMax}.0`
    },
    uniforms: {
      "envMap": { value: null },
      "samples": { value: 1 },
      "weights": { value: weights },
      "latitudinal": { value: false },
      "dTheta": { value: 0 },
      "mipInt": { value: 0 },
      "poleAxis": { value: poleAxis }
    },
    vertexShader: _getCommonVertexShader(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`
    ),
    blending: NoBlending,
    depthTest: false,
    depthWrite: false
  });
  return shaderMaterial2;
}
function _getEquirectMaterial() {
  return new ShaderMaterial({
    name: "EquirectangularToCubeUV",
    uniforms: {
      "envMap": { value: null }
    },
    vertexShader: _getCommonVertexShader(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`
    ),
    blending: NoBlending,
    depthTest: false,
    depthWrite: false
  });
}
function _getCubemapMaterial() {
  return new ShaderMaterial({
    name: "CubemapToCubeUV",
    uniforms: {
      "envMap": { value: null },
      "flipEnvMap": { value: -1 }
    },
    vertexShader: _getCommonVertexShader(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`
    ),
    blending: NoBlending,
    depthTest: false,
    depthWrite: false
  });
}
function _getCommonVertexShader() {
  return (
    /* glsl */
    `

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`
  );
}
function WebGLCubeUVMaps(renderer) {
  let cubeUVmaps = /* @__PURE__ */ new WeakMap();
  let pmremGenerator = null;
  function get(texture) {
    if (texture && texture.isTexture) {
      const mapping = texture.mapping;
      const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
      const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
      if (isEquirectMap || isCubeMap) {
        let renderTarget = cubeUVmaps.get(texture);
        const currentPMREMVersion = renderTarget !== void 0 ? renderTarget.texture.pmremVersion : 0;
        if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) {
          if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
          renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
          renderTarget.texture.pmremVersion = texture.pmremVersion;
          cubeUVmaps.set(texture, renderTarget);
          return renderTarget.texture;
        } else {
          if (renderTarget !== void 0) {
            return renderTarget.texture;
          } else {
            const image = texture.image;
            if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
              if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
              renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
              renderTarget.texture.pmremVersion = texture.pmremVersion;
              cubeUVmaps.set(texture, renderTarget);
              texture.addEventListener("dispose", onTextureDispose);
              return renderTarget.texture;
            } else {
              return null;
            }
          }
        }
      }
    }
    return texture;
  }
  function isCubeTextureComplete(image) {
    let count = 0;
    const length = 6;
    for (let i2 = 0; i2 < length; i2++) {
      if (image[i2] !== void 0) count++;
    }
    return count === length;
  }
  function onTextureDispose(event) {
    const texture = event.target;
    texture.removeEventListener("dispose", onTextureDispose);
    const cubemapUV = cubeUVmaps.get(texture);
    if (cubemapUV !== void 0) {
      cubeUVmaps.delete(texture);
      cubemapUV.dispose();
    }
  }
  function dispose2() {
    cubeUVmaps = /* @__PURE__ */ new WeakMap();
    if (pmremGenerator !== null) {
      pmremGenerator.dispose();
      pmremGenerator = null;
    }
  }
  return {
    get,
    dispose: dispose2
  };
}
function WebGLExtensions(gl) {
  const extensions = {};
  function getExtension2(name) {
    if (extensions[name] !== void 0) {
      return extensions[name];
    }
    let extension;
    switch (name) {
      case "WEBGL_depth_texture":
        extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture");
        break;
      case "EXT_texture_filter_anisotropic":
        extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
        break;
      case "WEBGL_compressed_texture_s3tc":
        extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
        break;
      case "WEBGL_compressed_texture_pvrtc":
        extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
        break;
      default:
        extension = gl.getExtension(name);
    }
    extensions[name] = extension;
    return extension;
  }
  return {
    has: function(name) {
      return getExtension2(name) !== null;
    },
    init: function() {
      getExtension2("EXT_color_buffer_float");
      getExtension2("WEBGL_clip_cull_distance");
      getExtension2("OES_texture_float_linear");
      getExtension2("EXT_color_buffer_half_float");
      getExtension2("WEBGL_multisampled_render_to_texture");
      getExtension2("WEBGL_render_shared_exponent");
    },
    get: function(name) {
      const extension = getExtension2(name);
      if (extension === null) {
        warnOnce("THREE.WebGLRenderer: " + name + " extension not supported.");
      }
      return extension;
    }
  };
}
function WebGLGeometries(gl, attributes, info, bindingStates) {
  const geometries = {};
  const wireframeAttributes = /* @__PURE__ */ new WeakMap();
  function onGeometryDispose(event) {
    const geometry = event.target;
    if (geometry.index !== null) {
      attributes.remove(geometry.index);
    }
    for (const name in geometry.attributes) {
      attributes.remove(geometry.attributes[name]);
    }
    geometry.removeEventListener("dispose", onGeometryDispose);
    delete geometries[geometry.id];
    const attribute = wireframeAttributes.get(geometry);
    if (attribute) {
      attributes.remove(attribute);
      wireframeAttributes.delete(geometry);
    }
    bindingStates.releaseStatesOfGeometry(geometry);
    if (geometry.isInstancedBufferGeometry === true) {
      delete geometry._maxInstanceCount;
    }
    info.memory.geometries--;
  }
  function get(object, geometry) {
    if (geometries[geometry.id] === true) return geometry;
    geometry.addEventListener("dispose", onGeometryDispose);
    geometries[geometry.id] = true;
    info.memory.geometries++;
    return geometry;
  }
  function update(geometry) {
    const geometryAttributes = geometry.attributes;
    for (const name in geometryAttributes) {
      attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
    }
  }
  function updateWireframeAttribute(geometry) {
    const indices = [];
    const geometryIndex = geometry.index;
    const geometryPosition = geometry.attributes.position;
    let version2 = 0;
    if (geometryIndex !== null) {
      const array = geometryIndex.array;
      version2 = geometryIndex.version;
      for (let i2 = 0, l2 = array.length; i2 < l2; i2 += 3) {
        const a3 = array[i2 + 0];
        const b2 = array[i2 + 1];
        const c2 = array[i2 + 2];
        indices.push(a3, b2, b2, c2, c2, a3);
      }
    } else if (geometryPosition !== void 0) {
      const array = geometryPosition.array;
      version2 = geometryPosition.version;
      for (let i2 = 0, l2 = array.length / 3 - 1; i2 < l2; i2 += 3) {
        const a3 = i2 + 0;
        const b2 = i2 + 1;
        const c2 = i2 + 2;
        indices.push(a3, b2, b2, c2, c2, a3);
      }
    } else {
      return;
    }
    const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
    attribute.version = version2;
    const previousAttribute = wireframeAttributes.get(geometry);
    if (previousAttribute) attributes.remove(previousAttribute);
    wireframeAttributes.set(geometry, attribute);
  }
  function getWireframeAttribute(geometry) {
    const currentAttribute = wireframeAttributes.get(geometry);
    if (currentAttribute) {
      const geometryIndex = geometry.index;
      if (geometryIndex !== null) {
        if (currentAttribute.version < geometryIndex.version) {
          updateWireframeAttribute(geometry);
        }
      }
    } else {
      updateWireframeAttribute(geometry);
    }
    return wireframeAttributes.get(geometry);
  }
  return {
    get,
    update,
    getWireframeAttribute
  };
}
function WebGLIndexedBufferRenderer(gl, extensions, info) {
  let mode2;
  function setMode(value) {
    mode2 = value;
  }
  let type, bytesPerElement;
  function setIndex(value) {
    type = value.type;
    bytesPerElement = value.bytesPerElement;
  }
  function render(start, count) {
    gl.drawElements(mode2, count, type, start * bytesPerElement);
    info.update(count, mode2, 1);
  }
  function renderInstances(start, count, primcount) {
    if (primcount === 0) return;
    gl.drawElementsInstanced(mode2, count, type, start * bytesPerElement, primcount);
    info.update(count, mode2, primcount);
  }
  function renderMultiDraw(starts, counts, drawCount) {
    if (drawCount === 0) return;
    const extension = extensions.get("WEBGL_multi_draw");
    extension.multiDrawElementsWEBGL(mode2, counts, 0, type, starts, 0, drawCount);
    let elementCount = 0;
    for (let i2 = 0; i2 < drawCount; i2++) {
      elementCount += counts[i2];
    }
    info.update(elementCount, mode2, 1);
  }
  function renderMultiDrawInstances(starts, counts, drawCount, primcount) {
    if (drawCount === 0) return;
    const extension = extensions.get("WEBGL_multi_draw");
    if (extension === null) {
      for (let i2 = 0; i2 < starts.length; i2++) {
        renderInstances(starts[i2] / bytesPerElement, counts[i2], primcount[i2]);
      }
    } else {
      extension.multiDrawElementsInstancedWEBGL(mode2, counts, 0, type, starts, 0, primcount, 0, drawCount);
      let elementCount = 0;
      for (let i2 = 0; i2 < drawCount; i2++) {
        elementCount += counts[i2] * primcount[i2];
      }
      info.update(elementCount, mode2, 1);
    }
  }
  this.setMode = setMode;
  this.setIndex = setIndex;
  this.render = render;
  this.renderInstances = renderInstances;
  this.renderMultiDraw = renderMultiDraw;
  this.renderMultiDrawInstances = renderMultiDrawInstances;
}
function WebGLInfo(gl) {
  const memory = {
    geometries: 0,
    textures: 0
  };
  const render = {
    frame: 0,
    calls: 0,
    triangles: 0,
    points: 0,
    lines: 0
  };
  function update(count, mode2, instanceCount) {
    render.calls++;
    switch (mode2) {
      case gl.TRIANGLES:
        render.triangles += instanceCount * (count / 3);
        break;
      case gl.LINES:
        render.lines += instanceCount * (count / 2);
        break;
      case gl.LINE_STRIP:
        render.lines += instanceCount * (count - 1);
        break;
      case gl.LINE_LOOP:
        render.lines += instanceCount * count;
        break;
      case gl.POINTS:
        render.points += instanceCount * count;
        break;
      default:
        console.error("THREE.WebGLInfo: Unknown draw mode:", mode2);
        break;
    }
  }
  function reset() {
    render.calls = 0;
    render.triangles = 0;
    render.points = 0;
    render.lines = 0;
  }
  return {
    memory,
    render,
    programs: null,
    autoReset: true,
    reset,
    update
  };
}
function WebGLMorphtargets(gl, capabilities, textures) {
  const morphTextures = /* @__PURE__ */ new WeakMap();
  const morph = new Vector4();
  function update(object, geometry, program) {
    const objectInfluences = object.morphTargetInfluences;
    const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
    const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0;
    let entry2 = morphTextures.get(geometry);
    if (entry2 === void 0 || entry2.count !== morphTargetsCount) {
      let disposeTexture = function() {
        texture.dispose();
        morphTextures.delete(geometry);
        geometry.removeEventListener("dispose", disposeTexture);
      };
      if (entry2 !== void 0) entry2.texture.dispose();
      const hasMorphPosition = geometry.morphAttributes.position !== void 0;
      const hasMorphNormals = geometry.morphAttributes.normal !== void 0;
      const hasMorphColors = geometry.morphAttributes.color !== void 0;
      const morphTargets = geometry.morphAttributes.position || [];
      const morphNormals = geometry.morphAttributes.normal || [];
      const morphColors = geometry.morphAttributes.color || [];
      let vertexDataCount = 0;
      if (hasMorphPosition === true) vertexDataCount = 1;
      if (hasMorphNormals === true) vertexDataCount = 2;
      if (hasMorphColors === true) vertexDataCount = 3;
      let width = geometry.attributes.position.count * vertexDataCount;
      let height = 1;
      if (width > capabilities.maxTextureSize) {
        height = Math.ceil(width / capabilities.maxTextureSize);
        width = capabilities.maxTextureSize;
      }
      const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
      const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
      texture.type = FloatType;
      texture.needsUpdate = true;
      const vertexDataStride = vertexDataCount * 4;
      for (let i2 = 0; i2 < morphTargetsCount; i2++) {
        const morphTarget = morphTargets[i2];
        const morphNormal = morphNormals[i2];
        const morphColor = morphColors[i2];
        const offset = width * height * 4 * i2;
        for (let j2 = 0; j2 < morphTarget.count; j2++) {
          const stride = j2 * vertexDataStride;
          if (hasMorphPosition === true) {
            morph.fromBufferAttribute(morphTarget, j2);
            buffer[offset + stride + 0] = morph.x;
            buffer[offset + stride + 1] = morph.y;
            buffer[offset + stride + 2] = morph.z;
            buffer[offset + stride + 3] = 0;
          }
          if (hasMorphNormals === true) {
            morph.fromBufferAttribute(morphNormal, j2);
            buffer[offset + stride + 4] = morph.x;
            buffer[offset + stride + 5] = morph.y;
            buffer[offset + stride + 6] = morph.z;
            buffer[offset + stride + 7] = 0;
          }
          if (hasMorphColors === true) {
            morph.fromBufferAttribute(morphColor, j2);
            buffer[offset + stride + 8] = morph.x;
            buffer[offset + stride + 9] = morph.y;
            buffer[offset + stride + 10] = morph.z;
            buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
          }
        }
      }
      entry2 = {
        count: morphTargetsCount,
        texture,
        size: new Vector2(width, height)
      };
      morphTextures.set(geometry, entry2);
      geometry.addEventListener("dispose", disposeTexture);
    }
    if (object.isInstancedMesh === true && object.morphTexture !== null) {
      program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures);
    } else {
      let morphInfluencesSum = 0;
      for (let i2 = 0; i2 < objectInfluences.length; i2++) {
        morphInfluencesSum += objectInfluences[i2];
      }
      const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
      program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence);
      program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences);
    }
    program.getUniforms().setValue(gl, "morphTargetsTexture", entry2.texture, textures);
    program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry2.size);
  }
  return {
    update
  };
}
function WebGLObjects(gl, geometries, attributes, info) {
  let updateMap = /* @__PURE__ */ new WeakMap();
  function update(object) {
    const frame = info.render.frame;
    const geometry = object.geometry;
    const buffergeometry = geometries.get(object, geometry);
    if (updateMap.get(buffergeometry) !== frame) {
      geometries.update(buffergeometry);
      updateMap.set(buffergeometry, frame);
    }
    if (object.isInstancedMesh) {
      if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) {
        object.addEventListener("dispose", onInstancedMeshDispose);
      }
      if (updateMap.get(object) !== frame) {
        attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
        if (object.instanceColor !== null) {
          attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
        }
        updateMap.set(object, frame);
      }
    }
    if (object.isSkinnedMesh) {
      const skeleton = object.skeleton;
      if (updateMap.get(skeleton) !== frame) {
        skeleton.update();
        updateMap.set(skeleton, frame);
      }
    }
    return buffergeometry;
  }
  function dispose2() {
    updateMap = /* @__PURE__ */ new WeakMap();
  }
  function onInstancedMeshDispose(event) {
    const instancedMesh = event.target;
    instancedMesh.removeEventListener("dispose", onInstancedMeshDispose);
    attributes.remove(instancedMesh.instanceMatrix);
    if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  }
  return {
    update,
    dispose: dispose2
  };
}
const emptyTexture = /* @__PURE__ */ new Texture();
const emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1);
const emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture();
const empty3dTexture = /* @__PURE__ */ new Data3DTexture();
const emptyCubeTexture = /* @__PURE__ */ new CubeTexture();
const arrayCacheF32 = [];
const arrayCacheI32 = [];
const mat4array = new Float32Array(16);
const mat3array = new Float32Array(9);
const mat2array = new Float32Array(4);
function flatten(array, nBlocks, blockSize) {
  const firstElem = array[0];
  if (firstElem <= 0 || firstElem > 0) return array;
  const n2 = nBlocks * blockSize;
  let r2 = arrayCacheF32[n2];
  if (r2 === void 0) {
    r2 = new Float32Array(n2);
    arrayCacheF32[n2] = r2;
  }
  if (nBlocks !== 0) {
    firstElem.toArray(r2, 0);
    for (let i2 = 1, offset = 0; i2 !== nBlocks; ++i2) {
      offset += blockSize;
      array[i2].toArray(r2, offset);
    }
  }
  return r2;
}
function arraysEqual(a3, b2) {
  if (a3.length !== b2.length) return false;
  for (let i2 = 0, l2 = a3.length; i2 < l2; i2++) {
    if (a3[i2] !== b2[i2]) return false;
  }
  return true;
}
function copyArray(a3, b2) {
  for (let i2 = 0, l2 = b2.length; i2 < l2; i2++) {
    a3[i2] = b2[i2];
  }
}
function allocTexUnits(textures, n2) {
  let r2 = arrayCacheI32[n2];
  if (r2 === void 0) {
    r2 = new Int32Array(n2);
    arrayCacheI32[n2] = r2;
  }
  for (let i2 = 0; i2 !== n2; ++i2) {
    r2[i2] = textures.allocateTextureUnit();
  }
  return r2;
}
function setValueV1f(gl, v5) {
  const cache = this.cache;
  if (cache[0] === v5) return;
  gl.uniform1f(this.addr, v5);
  cache[0] = v5;
}
function setValueV2f(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y) {
      gl.uniform2f(this.addr, v5.x, v5.y);
      cache[0] = v5.x;
      cache[1] = v5.y;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform2fv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV3f(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z) {
      gl.uniform3f(this.addr, v5.x, v5.y, v5.z);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
    }
  } else if (v5.r !== void 0) {
    if (cache[0] !== v5.r || cache[1] !== v5.g || cache[2] !== v5.b) {
      gl.uniform3f(this.addr, v5.r, v5.g, v5.b);
      cache[0] = v5.r;
      cache[1] = v5.g;
      cache[2] = v5.b;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform3fv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV4f(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z || cache[3] !== v5.w) {
      gl.uniform4f(this.addr, v5.x, v5.y, v5.z, v5.w);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
      cache[3] = v5.w;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform4fv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueM2(gl, v5) {
  const cache = this.cache;
  const elements = v5.elements;
  if (elements === void 0) {
    if (arraysEqual(cache, v5)) return;
    gl.uniformMatrix2fv(this.addr, false, v5);
    copyArray(cache, v5);
  } else {
    if (arraysEqual(cache, elements)) return;
    mat2array.set(elements);
    gl.uniformMatrix2fv(this.addr, false, mat2array);
    copyArray(cache, elements);
  }
}
function setValueM3(gl, v5) {
  const cache = this.cache;
  const elements = v5.elements;
  if (elements === void 0) {
    if (arraysEqual(cache, v5)) return;
    gl.uniformMatrix3fv(this.addr, false, v5);
    copyArray(cache, v5);
  } else {
    if (arraysEqual(cache, elements)) return;
    mat3array.set(elements);
    gl.uniformMatrix3fv(this.addr, false, mat3array);
    copyArray(cache, elements);
  }
}
function setValueM4(gl, v5) {
  const cache = this.cache;
  const elements = v5.elements;
  if (elements === void 0) {
    if (arraysEqual(cache, v5)) return;
    gl.uniformMatrix4fv(this.addr, false, v5);
    copyArray(cache, v5);
  } else {
    if (arraysEqual(cache, elements)) return;
    mat4array.set(elements);
    gl.uniformMatrix4fv(this.addr, false, mat4array);
    copyArray(cache, elements);
  }
}
function setValueV1i(gl, v5) {
  const cache = this.cache;
  if (cache[0] === v5) return;
  gl.uniform1i(this.addr, v5);
  cache[0] = v5;
}
function setValueV2i(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y) {
      gl.uniform2i(this.addr, v5.x, v5.y);
      cache[0] = v5.x;
      cache[1] = v5.y;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform2iv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV3i(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z) {
      gl.uniform3i(this.addr, v5.x, v5.y, v5.z);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform3iv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV4i(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z || cache[3] !== v5.w) {
      gl.uniform4i(this.addr, v5.x, v5.y, v5.z, v5.w);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
      cache[3] = v5.w;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform4iv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV1ui(gl, v5) {
  const cache = this.cache;
  if (cache[0] === v5) return;
  gl.uniform1ui(this.addr, v5);
  cache[0] = v5;
}
function setValueV2ui(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y) {
      gl.uniform2ui(this.addr, v5.x, v5.y);
      cache[0] = v5.x;
      cache[1] = v5.y;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform2uiv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV3ui(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z) {
      gl.uniform3ui(this.addr, v5.x, v5.y, v5.z);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform3uiv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueV4ui(gl, v5) {
  const cache = this.cache;
  if (v5.x !== void 0) {
    if (cache[0] !== v5.x || cache[1] !== v5.y || cache[2] !== v5.z || cache[3] !== v5.w) {
      gl.uniform4ui(this.addr, v5.x, v5.y, v5.z, v5.w);
      cache[0] = v5.x;
      cache[1] = v5.y;
      cache[2] = v5.z;
      cache[3] = v5.w;
    }
  } else {
    if (arraysEqual(cache, v5)) return;
    gl.uniform4uiv(this.addr, v5);
    copyArray(cache, v5);
  }
}
function setValueT1(gl, v5, textures) {
  const cache = this.cache;
  const unit = textures.allocateTextureUnit();
  if (cache[0] !== unit) {
    gl.uniform1i(this.addr, unit);
    cache[0] = unit;
  }
  let emptyTexture2D;
  if (this.type === gl.SAMPLER_2D_SHADOW) {
    emptyShadowTexture.compareFunction = LessEqualCompare;
    emptyTexture2D = emptyShadowTexture;
  } else {
    emptyTexture2D = emptyTexture;
  }
  textures.setTexture2D(v5 || emptyTexture2D, unit);
}
function setValueT3D1(gl, v5, textures) {
  const cache = this.cache;
  const unit = textures.allocateTextureUnit();
  if (cache[0] !== unit) {
    gl.uniform1i(this.addr, unit);
    cache[0] = unit;
  }
  textures.setTexture3D(v5 || empty3dTexture, unit);
}
function setValueT6(gl, v5, textures) {
  const cache = this.cache;
  const unit = textures.allocateTextureUnit();
  if (cache[0] !== unit) {
    gl.uniform1i(this.addr, unit);
    cache[0] = unit;
  }
  textures.setTextureCube(v5 || emptyCubeTexture, unit);
}
function setValueT2DArray1(gl, v5, textures) {
  const cache = this.cache;
  const unit = textures.allocateTextureUnit();
  if (cache[0] !== unit) {
    gl.uniform1i(this.addr, unit);
    cache[0] = unit;
  }
  textures.setTexture2DArray(v5 || emptyArrayTexture, unit);
}
function getSingularSetter(type) {
  switch (type) {
    case 5126:
      return setValueV1f;
    // FLOAT
    case 35664:
      return setValueV2f;
    // _VEC2
    case 35665:
      return setValueV3f;
    // _VEC3
    case 35666:
      return setValueV4f;
    // _VEC4
    case 35674:
      return setValueM2;
    // _MAT2
    case 35675:
      return setValueM3;
    // _MAT3
    case 35676:
      return setValueM4;
    // _MAT4
    case 5124:
    case 35670:
      return setValueV1i;
    // INT, BOOL
    case 35667:
    case 35671:
      return setValueV2i;
    // _VEC2
    case 35668:
    case 35672:
      return setValueV3i;
    // _VEC3
    case 35669:
    case 35673:
      return setValueV4i;
    // _VEC4
    case 5125:
      return setValueV1ui;
    // UINT
    case 36294:
      return setValueV2ui;
    // _VEC2
    case 36295:
      return setValueV3ui;
    // _VEC3
    case 36296:
      return setValueV4ui;
    // _VEC4
    case 35678:
    // SAMPLER_2D
    case 36198:
    // SAMPLER_EXTERNAL_OES
    case 36298:
    // INT_SAMPLER_2D
    case 36306:
    // UNSIGNED_INT_SAMPLER_2D
    case 35682:
      return setValueT1;
    case 35679:
    // SAMPLER_3D
    case 36299:
    // INT_SAMPLER_3D
    case 36307:
      return setValueT3D1;
    case 35680:
    // SAMPLER_CUBE
    case 36300:
    // INT_SAMPLER_CUBE
    case 36308:
    // UNSIGNED_INT_SAMPLER_CUBE
    case 36293:
      return setValueT6;
    case 36289:
    // SAMPLER_2D_ARRAY
    case 36303:
    // INT_SAMPLER_2D_ARRAY
    case 36311:
    // UNSIGNED_INT_SAMPLER_2D_ARRAY
    case 36292:
      return setValueT2DArray1;
  }
}
function setValueV1fArray(gl, v5) {
  gl.uniform1fv(this.addr, v5);
}
function setValueV2fArray(gl, v5) {
  const data = flatten(v5, this.size, 2);
  gl.uniform2fv(this.addr, data);
}
function setValueV3fArray(gl, v5) {
  const data = flatten(v5, this.size, 3);
  gl.uniform3fv(this.addr, data);
}
function setValueV4fArray(gl, v5) {
  const data = flatten(v5, this.size, 4);
  gl.uniform4fv(this.addr, data);
}
function setValueM2Array(gl, v5) {
  const data = flatten(v5, this.size, 4);
  gl.uniformMatrix2fv(this.addr, false, data);
}
function setValueM3Array(gl, v5) {
  const data = flatten(v5, this.size, 9);
  gl.uniformMatrix3fv(this.addr, false, data);
}
function setValueM4Array(gl, v5) {
  const data = flatten(v5, this.size, 16);
  gl.uniformMatrix4fv(this.addr, false, data);
}
function setValueV1iArray(gl, v5) {
  gl.uniform1iv(this.addr, v5);
}
function setValueV2iArray(gl, v5) {
  gl.uniform2iv(this.addr, v5);
}
function setValueV3iArray(gl, v5) {
  gl.uniform3iv(this.addr, v5);
}
function setValueV4iArray(gl, v5) {
  gl.uniform4iv(this.addr, v5);
}
function setValueV1uiArray(gl, v5) {
  gl.uniform1uiv(this.addr, v5);
}
function setValueV2uiArray(gl, v5) {
  gl.uniform2uiv(this.addr, v5);
}
function setValueV3uiArray(gl, v5) {
  gl.uniform3uiv(this.addr, v5);
}
function setValueV4uiArray(gl, v5) {
  gl.uniform4uiv(this.addr, v5);
}
function setValueT1Array(gl, v5, textures) {
  const cache = this.cache;
  const n2 = v5.length;
  const units = allocTexUnits(textures, n2);
  if (!arraysEqual(cache, units)) {
    gl.uniform1iv(this.addr, units);
    copyArray(cache, units);
  }
  for (let i2 = 0; i2 !== n2; ++i2) {
    textures.setTexture2D(v5[i2] || emptyTexture, units[i2]);
  }
}
function setValueT3DArray(gl, v5, textures) {
  const cache = this.cache;
  const n2 = v5.length;
  const units = allocTexUnits(textures, n2);
  if (!arraysEqual(cache, units)) {
    gl.uniform1iv(this.addr, units);
    copyArray(cache, units);
  }
  for (let i2 = 0; i2 !== n2; ++i2) {
    textures.setTexture3D(v5[i2] || empty3dTexture, units[i2]);
  }
}
function setValueT6Array(gl, v5, textures) {
  const cache = this.cache;
  const n2 = v5.length;
  const units = allocTexUnits(textures, n2);
  if (!arraysEqual(cache, units)) {
    gl.uniform1iv(this.addr, units);
    copyArray(cache, units);
  }
  for (let i2 = 0; i2 !== n2; ++i2) {
    textures.setTextureCube(v5[i2] || emptyCubeTexture, units[i2]);
  }
}
function setValueT2DArrayArray(gl, v5, textures) {
  const cache = this.cache;
  const n2 = v5.length;
  const units = allocTexUnits(textures, n2);
  if (!arraysEqual(cache, units)) {
    gl.uniform1iv(this.addr, units);
    copyArray(cache, units);
  }
  for (let i2 = 0; i2 !== n2; ++i2) {
    textures.setTexture2DArray(v5[i2] || emptyArrayTexture, units[i2]);
  }
}
function getPureArraySetter(type) {
  switch (type) {
    case 5126:
      return setValueV1fArray;
    // FLOAT
    case 35664:
      return setValueV2fArray;
    // _VEC2
    case 35665:
      return setValueV3fArray;
    // _VEC3
    case 35666:
      return setValueV4fArray;
    // _VEC4
    case 35674:
      return setValueM2Array;
    // _MAT2
    case 35675:
      return setValueM3Array;
    // _MAT3
    case 35676:
      return setValueM4Array;
    // _MAT4
    case 5124:
    case 35670:
      return setValueV1iArray;
    // INT, BOOL
    case 35667:
    case 35671:
      return setValueV2iArray;
    // _VEC2
    case 35668:
    case 35672:
      return setValueV3iArray;
    // _VEC3
    case 35669:
    case 35673:
      return setValueV4iArray;
    // _VEC4
    case 5125:
      return setValueV1uiArray;
    // UINT
    case 36294:
      return setValueV2uiArray;
    // _VEC2
    case 36295:
      return setValueV3uiArray;
    // _VEC3
    case 36296:
      return setValueV4uiArray;
    // _VEC4
    case 35678:
    // SAMPLER_2D
    case 36198:
    // SAMPLER_EXTERNAL_OES
    case 36298:
    // INT_SAMPLER_2D
    case 36306:
    // UNSIGNED_INT_SAMPLER_2D
    case 35682:
      return setValueT1Array;
    case 35679:
    // SAMPLER_3D
    case 36299:
    // INT_SAMPLER_3D
    case 36307:
      return setValueT3DArray;
    case 35680:
    // SAMPLER_CUBE
    case 36300:
    // INT_SAMPLER_CUBE
    case 36308:
    // UNSIGNED_INT_SAMPLER_CUBE
    case 36293:
      return setValueT6Array;
    case 36289:
    // SAMPLER_2D_ARRAY
    case 36303:
    // INT_SAMPLER_2D_ARRAY
    case 36311:
    // UNSIGNED_INT_SAMPLER_2D_ARRAY
    case 36292:
      return setValueT2DArrayArray;
  }
}
class SingleUniform {
  constructor(id, activeInfo, addr) {
    this.id = id;
    this.addr = addr;
    this.cache = [];
    this.type = activeInfo.type;
    this.setValue = getSingularSetter(activeInfo.type);
  }
}
class PureArrayUniform {
  constructor(id, activeInfo, addr) {
    this.id = id;
    this.addr = addr;
    this.cache = [];
    this.type = activeInfo.type;
    this.size = activeInfo.size;
    this.setValue = getPureArraySetter(activeInfo.type);
  }
}
class StructuredUniform {
  constructor(id) {
    this.id = id;
    this.seq = [];
    this.map = {};
  }
  setValue(gl, value, textures) {
    const seq = this.seq;
    for (let i2 = 0, n2 = seq.length; i2 !== n2; ++i2) {
      const u2 = seq[i2];
      u2.setValue(gl, value[u2.id], textures);
    }
  }
}
const RePathPart = /(\w+)(\])?(\[|\.)?/g;
function addUniform(container, uniformObject) {
  container.seq.push(uniformObject);
  container.map[uniformObject.id] = uniformObject;
}
function parseUniform(activeInfo, addr, container) {
  const path = activeInfo.name, pathLength = path.length;
  RePathPart.lastIndex = 0;
  while (true) {
    const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex;
    let id = match[1];
    const idIsIndex = match[2] === "]", subscript = match[3];
    if (idIsIndex) id = id | 0;
    if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) {
      addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
      break;
    } else {
      const map = container.map;
      let next = map[id];
      if (next === void 0) {
        next = new StructuredUniform(id);
        addUniform(container, next);
      }
      container = next;
    }
  }
}
class WebGLUniforms {
  constructor(gl, program) {
    this.seq = [];
    this.map = {};
    const n2 = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
    for (let i2 = 0; i2 < n2; ++i2) {
      const info = gl.getActiveUniform(program, i2), addr = gl.getUniformLocation(program, info.name);
      parseUniform(info, addr, this);
    }
  }
  setValue(gl, name, value, textures) {
    const u2 = this.map[name];
    if (u2 !== void 0) u2.setValue(gl, value, textures);
  }
  setOptional(gl, object, name) {
    const v5 = object[name];
    if (v5 !== void 0) this.setValue(gl, name, v5);
  }
  static upload(gl, seq, values, textures) {
    for (let i2 = 0, n2 = seq.length; i2 !== n2; ++i2) {
      const u2 = seq[i2], v5 = values[u2.id];
      if (v5.needsUpdate !== false) {
        u2.setValue(gl, v5.value, textures);
      }
    }
  }
  static seqWithValue(seq, values) {
    const r2 = [];
    for (let i2 = 0, n2 = seq.length; i2 !== n2; ++i2) {
      const u2 = seq[i2];
      if (u2.id in values) r2.push(u2);
    }
    return r2;
  }
}
function WebGLShader(gl, type, string) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, string);
  gl.compileShader(shader);
  return shader;
}
const COMPLETION_STATUS_KHR = 37297;
let programIdCount = 0;
function handleSource(string, errorLine) {
  const lines = string.split("\n");
  const lines2 = [];
  const from = Math.max(errorLine - 6, 0);
  const to = Math.min(errorLine + 6, lines.length);
  for (let i2 = from; i2 < to; i2++) {
    const line = i2 + 1;
    lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i2]}`);
  }
  return lines2.join("\n");
}
const _m0 = /* @__PURE__ */ new Matrix3();
function getEncodingComponents(colorSpace) {
  ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace);
  const encodingMatrix = `mat3( ${_m0.elements.map((v5) => v5.toFixed(4))} )`;
  switch (ColorManagement.getTransfer(colorSpace)) {
    case LinearTransfer:
      return [encodingMatrix, "LinearTransferOETF"];
    case SRGBTransfer:
      return [encodingMatrix, "sRGBTransferOETF"];
    default:
      console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace);
      return [encodingMatrix, "LinearTransferOETF"];
  }
}
function getShaderErrors(gl, shader, type) {
  const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  const errors = gl.getShaderInfoLog(shader).trim();
  if (status && errors === "") return "";
  const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  if (errorMatches) {
    const errorLine = parseInt(errorMatches[1]);
    return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine);
  } else {
    return errors;
  }
}
function getTexelEncodingFunction(functionName, colorSpace) {
  const components = getEncodingComponents(colorSpace);
  return [
    `vec4 ${functionName}( vec4 value ) {`,
    `	return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`,
    "}"
  ].join("\n");
}
function getToneMappingFunction(functionName, toneMapping) {
  let toneMappingName;
  switch (toneMapping) {
    case LinearToneMapping:
      toneMappingName = "Linear";
      break;
    case ReinhardToneMapping:
      toneMappingName = "Reinhard";
      break;
    case CineonToneMapping:
      toneMappingName = "Cineon";
      break;
    case ACESFilmicToneMapping:
      toneMappingName = "ACESFilmic";
      break;
    case AgXToneMapping:
      toneMappingName = "AgX";
      break;
    case NeutralToneMapping:
      toneMappingName = "Neutral";
      break;
    case CustomToneMapping:
      toneMappingName = "Custom";
      break;
    default:
      console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping);
      toneMappingName = "Linear";
  }
  return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
}
const _v0 = /* @__PURE__ */ new Vector3();
function getLuminanceFunction() {
  ColorManagement.getLuminanceCoefficients(_v0);
  const r2 = _v0.x.toFixed(4);
  const g2 = _v0.y.toFixed(4);
  const b2 = _v0.z.toFixed(4);
  return [
    "float luminance( const in vec3 rgb ) {",
    `	const vec3 weights = vec3( ${r2}, ${g2}, ${b2} );`,
    "	return dot( weights, rgb );",
    "}"
  ].join("\n");
}
function generateVertexExtensions(parameters) {
  const chunks = [
    parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "",
    parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""
  ];
  return chunks.filter(filterEmptyLine).join("\n");
}
function generateDefines(defines) {
  const chunks = [];
  for (const name in defines) {
    const value = defines[name];
    if (value === false) continue;
    chunks.push("#define " + name + " " + value);
  }
  return chunks.join("\n");
}
function fetchAttributeLocations(gl, program) {
  const attributes = {};
  const n2 = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  for (let i2 = 0; i2 < n2; i2++) {
    const info = gl.getActiveAttrib(program, i2);
    const name = info.name;
    let locationSize = 1;
    if (info.type === gl.FLOAT_MAT2) locationSize = 2;
    if (info.type === gl.FLOAT_MAT3) locationSize = 3;
    if (info.type === gl.FLOAT_MAT4) locationSize = 4;
    attributes[name] = {
      type: info.type,
      location: gl.getAttribLocation(program, name),
      locationSize
    };
  }
  return attributes;
}
function filterEmptyLine(string) {
  return string !== "";
}
function replaceLightNums(string, parameters) {
  const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
}
function replaceClippingPlaneNums(string, parameters) {
  return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
}
const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
function resolveIncludes(string) {
  return string.replace(includePattern, includeReplacer);
}
const shaderChunkMap = /* @__PURE__ */ new Map();
function includeReplacer(match, include) {
  let string = ShaderChunk[include];
  if (string === void 0) {
    const newInclude = shaderChunkMap.get(include);
    if (newInclude !== void 0) {
      string = ShaderChunk[newInclude];
      console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude);
    } else {
      throw new Error("Can not resolve #include <" + include + ">");
    }
  }
  return resolveIncludes(string);
}
const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
function unrollLoops(string) {
  return string.replace(unrollLoopPattern, loopReplacer);
}
function loopReplacer(match, start, end, snippet) {
  let string = "";
  for (let i2 = parseInt(start); i2 < parseInt(end); i2++) {
    string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i2 + " ]").replace(/UNROLLED_LOOP_INDEX/g, i2);
  }
  return string;
}
function generatePrecision(parameters) {
  let precisionstring = `precision ${parameters.precision} float;
	precision ${parameters.precision} int;
	precision ${parameters.precision} sampler2D;
	precision ${parameters.precision} samplerCube;
	precision ${parameters.precision} sampler3D;
	precision ${parameters.precision} sampler2DArray;
	precision ${parameters.precision} sampler2DShadow;
	precision ${parameters.precision} samplerCubeShadow;
	precision ${parameters.precision} sampler2DArrayShadow;
	precision ${parameters.precision} isampler2D;
	precision ${parameters.precision} isampler3D;
	precision ${parameters.precision} isamplerCube;
	precision ${parameters.precision} isampler2DArray;
	precision ${parameters.precision} usampler2D;
	precision ${parameters.precision} usampler3D;
	precision ${parameters.precision} usamplerCube;
	precision ${parameters.precision} usampler2DArray;
	`;
  if (parameters.precision === "highp") {
    precisionstring += "\n#define HIGH_PRECISION";
  } else if (parameters.precision === "mediump") {
    precisionstring += "\n#define MEDIUM_PRECISION";
  } else if (parameters.precision === "lowp") {
    precisionstring += "\n#define LOW_PRECISION";
  }
  return precisionstring;
}
function generateShadowMapTypeDefine(parameters) {
  let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  if (parameters.shadowMapType === PCFShadowMap) {
    shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  } else if (parameters.shadowMapType === PCFSoftShadowMap) {
    shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  } else if (parameters.shadowMapType === VSMShadowMap) {
    shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM";
  }
  return shadowMapTypeDefine;
}
function generateEnvMapTypeDefine(parameters) {
  let envMapTypeDefine = "ENVMAP_TYPE_CUBE";
  if (parameters.envMap) {
    switch (parameters.envMapMode) {
      case CubeReflectionMapping:
      case CubeRefractionMapping:
        envMapTypeDefine = "ENVMAP_TYPE_CUBE";
        break;
      case CubeUVReflectionMapping:
        envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV";
        break;
    }
  }
  return envMapTypeDefine;
}
function generateEnvMapModeDefine(parameters) {
  let envMapModeDefine = "ENVMAP_MODE_REFLECTION";
  if (parameters.envMap) {
    switch (parameters.envMapMode) {
      case CubeRefractionMapping:
        envMapModeDefine = "ENVMAP_MODE_REFRACTION";
        break;
    }
  }
  return envMapModeDefine;
}
function generateEnvMapBlendingDefine(parameters) {
  let envMapBlendingDefine = "ENVMAP_BLENDING_NONE";
  if (parameters.envMap) {
    switch (parameters.combine) {
      case MultiplyOperation:
        envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY";
        break;
      case MixOperation:
        envMapBlendingDefine = "ENVMAP_BLENDING_MIX";
        break;
      case AddOperation:
        envMapBlendingDefine = "ENVMAP_BLENDING_ADD";
        break;
    }
  }
  return envMapBlendingDefine;
}
function generateCubeUVSize(parameters) {
  const imageHeight = parameters.envMapCubeUVHeight;
  if (imageHeight === null) return null;
  const maxMip = Math.log2(imageHeight) - 2;
  const texelHeight = 1 / imageHeight;
  const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  return { texelWidth, texelHeight, maxMip };
}
function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  const gl = renderer.getContext();
  const defines = parameters.defines;
  let vertexShader2 = parameters.vertexShader;
  let fragmentShader2 = parameters.fragmentShader;
  const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  const envMapModeDefine = generateEnvMapModeDefine(parameters);
  const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  const envMapCubeUVSize = generateCubeUVSize(parameters);
  const customVertexExtensions = generateVertexExtensions(parameters);
  const customDefines = generateDefines(defines);
  const program = gl.createProgram();
  let prefixVertex, prefixFragment;
  let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : "";
  if (parameters.isRawShaderMaterial) {
    prefixVertex = [
      "#define SHADER_TYPE " + parameters.shaderType,
      "#define SHADER_NAME " + parameters.shaderName,
      customDefines
    ].filter(filterEmptyLine).join("\n");
    if (prefixVertex.length > 0) {
      prefixVertex += "\n";
    }
    prefixFragment = [
      "#define SHADER_TYPE " + parameters.shaderType,
      "#define SHADER_NAME " + parameters.shaderName,
      customDefines
    ].filter(filterEmptyLine).join("\n");
    if (prefixFragment.length > 0) {
      prefixFragment += "\n";
    }
  } else {
    prefixVertex = [
      generatePrecision(parameters),
      "#define SHADER_TYPE " + parameters.shaderType,
      "#define SHADER_NAME " + parameters.shaderName,
      customDefines,
      parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "",
      parameters.batching ? "#define USE_BATCHING" : "",
      parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "",
      parameters.instancing ? "#define USE_INSTANCING" : "",
      parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "",
      parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "",
      parameters.useFog && parameters.fog ? "#define USE_FOG" : "",
      parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "",
      parameters.map ? "#define USE_MAP" : "",
      parameters.envMap ? "#define USE_ENVMAP" : "",
      parameters.envMap ? "#define " + envMapModeDefine : "",
      parameters.lightMap ? "#define USE_LIGHTMAP" : "",
      parameters.aoMap ? "#define USE_AOMAP" : "",
      parameters.bumpMap ? "#define USE_BUMPMAP" : "",
      parameters.normalMap ? "#define USE_NORMALMAP" : "",
      parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
      parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
      parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "",
      parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
      parameters.anisotropy ? "#define USE_ANISOTROPY" : "",
      parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
      parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
      parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
      parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
      parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
      parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
      parameters.specularMap ? "#define USE_SPECULARMAP" : "",
      parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
      parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
      parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
      parameters.metalnessMap ? "#define USE_METALNESSMAP" : "",
      parameters.alphaMap ? "#define USE_ALPHAMAP" : "",
      parameters.alphaHash ? "#define USE_ALPHAHASH" : "",
      parameters.transmission ? "#define USE_TRANSMISSION" : "",
      parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
      parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "",
      parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
      parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
      //
      parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "",
      parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "",
      parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "",
      parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "",
      parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "",
      parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "",
      parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "",
      parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "",
      parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "",
      parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "",
      parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "",
      parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "",
      parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "",
      parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "",
      parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "",
      parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "",
      parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "",
      parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "",
      parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "",
      parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "",
      parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "",
      parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "",
      parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "",
      //
      parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "",
      parameters.vertexColors ? "#define USE_COLOR" : "",
      parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
      parameters.vertexUv1s ? "#define USE_UV1" : "",
      parameters.vertexUv2s ? "#define USE_UV2" : "",
      parameters.vertexUv3s ? "#define USE_UV3" : "",
      parameters.pointsUvs ? "#define USE_POINTS_UV" : "",
      parameters.flatShading ? "#define FLAT_SHADED" : "",
      parameters.skinning ? "#define USE_SKINNING" : "",
      parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
      parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "",
      parameters.morphColors ? "#define USE_MORPHCOLORS" : "",
      parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "",
      parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "",
      parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
      parameters.flipSided ? "#define FLIP_SIDED" : "",
      parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
      parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
      parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
      parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
      parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
      parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "",
      "uniform mat4 modelMatrix;",
      "uniform mat4 modelViewMatrix;",
      "uniform mat4 projectionMatrix;",
      "uniform mat4 viewMatrix;",
      "uniform mat3 normalMatrix;",
      "uniform vec3 cameraPosition;",
      "uniform bool isOrthographic;",
      "#ifdef USE_INSTANCING",
      "	attribute mat4 instanceMatrix;",
      "#endif",
      "#ifdef USE_INSTANCING_COLOR",
      "	attribute vec3 instanceColor;",
      "#endif",
      "#ifdef USE_INSTANCING_MORPH",
      "	uniform sampler2D morphTexture;",
      "#endif",
      "attribute vec3 position;",
      "attribute vec3 normal;",
      "attribute vec2 uv;",
      "#ifdef USE_UV1",
      "	attribute vec2 uv1;",
      "#endif",
      "#ifdef USE_UV2",
      "	attribute vec2 uv2;",
      "#endif",
      "#ifdef USE_UV3",
      "	attribute vec2 uv3;",
      "#endif",
      "#ifdef USE_TANGENT",
      "	attribute vec4 tangent;",
      "#endif",
      "#if defined( USE_COLOR_ALPHA )",
      "	attribute vec4 color;",
      "#elif defined( USE_COLOR )",
      "	attribute vec3 color;",
      "#endif",
      "#ifdef USE_SKINNING",
      "	attribute vec4 skinIndex;",
      "	attribute vec4 skinWeight;",
      "#endif",
      "\n"
    ].filter(filterEmptyLine).join("\n");
    prefixFragment = [
      generatePrecision(parameters),
      "#define SHADER_TYPE " + parameters.shaderType,
      "#define SHADER_NAME " + parameters.shaderName,
      customDefines,
      parameters.useFog && parameters.fog ? "#define USE_FOG" : "",
      parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "",
      parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "",
      parameters.map ? "#define USE_MAP" : "",
      parameters.matcap ? "#define USE_MATCAP" : "",
      parameters.envMap ? "#define USE_ENVMAP" : "",
      parameters.envMap ? "#define " + envMapTypeDefine : "",
      parameters.envMap ? "#define " + envMapModeDefine : "",
      parameters.envMap ? "#define " + envMapBlendingDefine : "",
      envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "",
      envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "",
      envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "",
      parameters.lightMap ? "#define USE_LIGHTMAP" : "",
      parameters.aoMap ? "#define USE_AOMAP" : "",
      parameters.bumpMap ? "#define USE_BUMPMAP" : "",
      parameters.normalMap ? "#define USE_NORMALMAP" : "",
      parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
      parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
      parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
      parameters.anisotropy ? "#define USE_ANISOTROPY" : "",
      parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
      parameters.clearcoat ? "#define USE_CLEARCOAT" : "",
      parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
      parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
      parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
      parameters.dispersion ? "#define USE_DISPERSION" : "",
      parameters.iridescence ? "#define USE_IRIDESCENCE" : "",
      parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
      parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
      parameters.specularMap ? "#define USE_SPECULARMAP" : "",
      parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
      parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
      parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
      parameters.metalnessMap ? "#define USE_METALNESSMAP" : "",
      parameters.alphaMap ? "#define USE_ALPHAMAP" : "",
      parameters.alphaTest ? "#define USE_ALPHATEST" : "",
      parameters.alphaHash ? "#define USE_ALPHAHASH" : "",
      parameters.sheen ? "#define USE_SHEEN" : "",
      parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
      parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
      parameters.transmission ? "#define USE_TRANSMISSION" : "",
      parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
      parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "",
      parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "",
      parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "",
      parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
      parameters.vertexUv1s ? "#define USE_UV1" : "",
      parameters.vertexUv2s ? "#define USE_UV2" : "",
      parameters.vertexUv3s ? "#define USE_UV3" : "",
      parameters.pointsUvs ? "#define USE_POINTS_UV" : "",
      parameters.gradientMap ? "#define USE_GRADIENTMAP" : "",
      parameters.flatShading ? "#define FLAT_SHADED" : "",
      parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
      parameters.flipSided ? "#define FLIP_SIDED" : "",
      parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
      parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
      parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "",
      parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
      parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "",
      parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "",
      parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
      parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "",
      "uniform mat4 viewMatrix;",
      "uniform vec3 cameraPosition;",
      "uniform bool isOrthographic;",
      parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "",
      parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "",
      // this code is required here because it is used by the toneMapping() function defined below
      parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "",
      parameters.dithering ? "#define DITHERING" : "",
      parameters.opaque ? "#define OPAQUE" : "",
      ShaderChunk["colorspace_pars_fragment"],
      // this code is required here because it is used by the various encoding/decoding function defined below
      getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace),
      getLuminanceFunction(),
      parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "",
      "\n"
    ].filter(filterEmptyLine).join("\n");
  }
  vertexShader2 = resolveIncludes(vertexShader2);
  vertexShader2 = replaceLightNums(vertexShader2, parameters);
  vertexShader2 = replaceClippingPlaneNums(vertexShader2, parameters);
  fragmentShader2 = resolveIncludes(fragmentShader2);
  fragmentShader2 = replaceLightNums(fragmentShader2, parameters);
  fragmentShader2 = replaceClippingPlaneNums(fragmentShader2, parameters);
  vertexShader2 = unrollLoops(vertexShader2);
  fragmentShader2 = unrollLoops(fragmentShader2);
  if (parameters.isRawShaderMaterial !== true) {
    versionString = "#version 300 es\n";
    prefixVertex = [
      customVertexExtensions,
      "#define attribute in",
      "#define varying out",
      "#define texture2D texture"
    ].join("\n") + "\n" + prefixVertex;
    prefixFragment = [
      "#define varying in",
      parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;",
      parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor",
      "#define gl_FragDepthEXT gl_FragDepth",
      "#define texture2D texture",
      "#define textureCube texture",
      "#define texture2DProj textureProj",
      "#define texture2DLodEXT textureLod",
      "#define texture2DProjLodEXT textureProjLod",
      "#define textureCubeLodEXT textureLod",
      "#define texture2DGradEXT textureGrad",
      "#define texture2DProjGradEXT textureProjGrad",
      "#define textureCubeGradEXT textureGrad"
    ].join("\n") + "\n" + prefixFragment;
  }
  const vertexGlsl = versionString + prefixVertex + vertexShader2;
  const fragmentGlsl = versionString + prefixFragment + fragmentShader2;
  const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  gl.attachShader(program, glVertexShader);
  gl.attachShader(program, glFragmentShader);
  if (parameters.index0AttributeName !== void 0) {
    gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  } else if (parameters.morphTargets === true) {
    gl.bindAttribLocation(program, 0, "position");
  }
  gl.linkProgram(program);
  function onFirstUse(self2) {
    if (renderer.debug.checkShaderErrors) {
      const programLog = gl.getProgramInfoLog(program).trim();
      const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
      const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
      let runnable = true;
      let haveDiagnostics = true;
      if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
        runnable = false;
        if (typeof renderer.debug.onShaderError === "function") {
          renderer.debug.onShaderError(gl, program, glVertexShader, glFragmentShader);
        } else {
          const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex");
          const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment");
          console.error(
            "THREE.WebGLProgram: Shader Error " + gl.getError() + " - VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + "\n\nMaterial Name: " + self2.name + "\nMaterial Type: " + self2.type + "\n\nProgram Info Log: " + programLog + "\n" + vertexErrors + "\n" + fragmentErrors
          );
        }
      } else if (programLog !== "") {
        console.warn("THREE.WebGLProgram: Program Info Log:", programLog);
      } else if (vertexLog === "" || fragmentLog === "") {
        haveDiagnostics = false;
      }
      if (haveDiagnostics) {
        self2.diagnostics = {
          runnable,
          programLog,
          vertexShader: {
            log: vertexLog,
            prefix: prefixVertex
          },
          fragmentShader: {
            log: fragmentLog,
            prefix: prefixFragment
          }
        };
      }
    }
    gl.deleteShader(glVertexShader);
    gl.deleteShader(glFragmentShader);
    cachedUniforms = new WebGLUniforms(gl, program);
    cachedAttributes = fetchAttributeLocations(gl, program);
  }
  let cachedUniforms;
  this.getUniforms = function() {
    if (cachedUniforms === void 0) {
      onFirstUse(this);
    }
    return cachedUniforms;
  };
  let cachedAttributes;
  this.getAttributes = function() {
    if (cachedAttributes === void 0) {
      onFirstUse(this);
    }
    return cachedAttributes;
  };
  let programReady = parameters.rendererExtensionParallelShaderCompile === false;
  this.isReady = function() {
    if (programReady === false) {
      programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR);
    }
    return programReady;
  };
  this.destroy = function() {
    bindingStates.releaseStatesOfProgram(this);
    gl.deleteProgram(program);
    this.program = void 0;
  };
  this.type = parameters.shaderType;
  this.name = parameters.shaderName;
  this.id = programIdCount++;
  this.cacheKey = cacheKey;
  this.usedTimes = 1;
  this.program = program;
  this.vertexShader = glVertexShader;
  this.fragmentShader = glFragmentShader;
  return this;
}
let _id = 0;
class WebGLShaderCache {
  constructor() {
    this.shaderCache = /* @__PURE__ */ new Map();
    this.materialCache = /* @__PURE__ */ new Map();
  }
  update(material) {
    const vertexShader2 = material.vertexShader;
    const fragmentShader2 = material.fragmentShader;
    const vertexShaderStage = this._getShaderStage(vertexShader2);
    const fragmentShaderStage = this._getShaderStage(fragmentShader2);
    const materialShaders = this._getShaderCacheForMaterial(material);
    if (materialShaders.has(vertexShaderStage) === false) {
      materialShaders.add(vertexShaderStage);
      vertexShaderStage.usedTimes++;
    }
    if (materialShaders.has(fragmentShaderStage) === false) {
      materialShaders.add(fragmentShaderStage);
      fragmentShaderStage.usedTimes++;
    }
    return this;
  }
  remove(material) {
    const materialShaders = this.materialCache.get(material);
    for (const shaderStage of materialShaders) {
      shaderStage.usedTimes--;
      if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
    }
    this.materialCache.delete(material);
    return this;
  }
  getVertexShaderID(material) {
    return this._getShaderStage(material.vertexShader).id;
  }
  getFragmentShaderID(material) {
    return this._getShaderStage(material.fragmentShader).id;
  }
  dispose() {
    this.shaderCache.clear();
    this.materialCache.clear();
  }
  _getShaderCacheForMaterial(material) {
    const cache = this.materialCache;
    let set = cache.get(material);
    if (set === void 0) {
      set = /* @__PURE__ */ new Set();
      cache.set(material, set);
    }
    return set;
  }
  _getShaderStage(code) {
    const cache = this.shaderCache;
    let stage = cache.get(code);
    if (stage === void 0) {
      stage = new WebGLShaderStage(code);
      cache.set(code, stage);
    }
    return stage;
  }
}
class WebGLShaderStage {
  constructor(code) {
    this.id = _id++;
    this.code = code;
    this.usedTimes = 0;
  }
}
function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  const _programLayers = new Layers();
  const _customShaders = new WebGLShaderCache();
  const _activeChannels = /* @__PURE__ */ new Set();
  const programs = [];
  const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  let precision = capabilities.precision;
  const shaderIDs = {
    MeshDepthMaterial: "depth",
    MeshDistanceMaterial: "distanceRGBA",
    MeshNormalMaterial: "normal",
    MeshBasicMaterial: "basic",
    MeshLambertMaterial: "lambert",
    MeshPhongMaterial: "phong",
    MeshToonMaterial: "toon",
    MeshStandardMaterial: "physical",
    MeshPhysicalMaterial: "physical",
    MeshMatcapMaterial: "matcap",
    LineBasicMaterial: "basic",
    LineDashedMaterial: "dashed",
    PointsMaterial: "points",
    ShadowMaterial: "shadow",
    SpriteMaterial: "sprite"
  };
  function getChannel(value) {
    _activeChannels.add(value);
    if (value === 0) return "uv";
    return `uv${value}`;
  }
  function getParameters(material, lights, shadows, scene, object) {
    const fog = scene.fog;
    const geometry = object.geometry;
    const environment = material.isMeshStandardMaterial ? scene.environment : null;
    const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
    const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
    const shaderID = shaderIDs[material.type];
    if (material.precision !== null) {
      precision = capabilities.getMaxPrecision(material.precision);
      if (precision !== material.precision) {
        console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead.");
      }
    }
    const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
    const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0;
    let morphTextureStride = 0;
    if (geometry.morphAttributes.position !== void 0) morphTextureStride = 1;
    if (geometry.morphAttributes.normal !== void 0) morphTextureStride = 2;
    if (geometry.morphAttributes.color !== void 0) morphTextureStride = 3;
    let vertexShader2, fragmentShader2;
    let customVertexShaderID, customFragmentShaderID;
    if (shaderID) {
      const shader = ShaderLib[shaderID];
      vertexShader2 = shader.vertexShader;
      fragmentShader2 = shader.fragmentShader;
    } else {
      vertexShader2 = material.vertexShader;
      fragmentShader2 = material.fragmentShader;
      _customShaders.update(material);
      customVertexShaderID = _customShaders.getVertexShaderID(material);
      customFragmentShaderID = _customShaders.getFragmentShaderID(material);
    }
    const currentRenderTarget = renderer.getRenderTarget();
    const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
    const IS_INSTANCEDMESH = object.isInstancedMesh === true;
    const IS_BATCHEDMESH = object.isBatchedMesh === true;
    const HAS_MAP = !!material.map;
    const HAS_MATCAP = !!material.matcap;
    const HAS_ENVMAP = !!envMap;
    const HAS_AOMAP = !!material.aoMap;
    const HAS_LIGHTMAP = !!material.lightMap;
    const HAS_BUMPMAP = !!material.bumpMap;
    const HAS_NORMALMAP = !!material.normalMap;
    const HAS_DISPLACEMENTMAP = !!material.displacementMap;
    const HAS_EMISSIVEMAP = !!material.emissiveMap;
    const HAS_METALNESSMAP = !!material.metalnessMap;
    const HAS_ROUGHNESSMAP = !!material.roughnessMap;
    const HAS_ANISOTROPY = material.anisotropy > 0;
    const HAS_CLEARCOAT = material.clearcoat > 0;
    const HAS_DISPERSION = material.dispersion > 0;
    const HAS_IRIDESCENCE = material.iridescence > 0;
    const HAS_SHEEN = material.sheen > 0;
    const HAS_TRANSMISSION = material.transmission > 0;
    const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap;
    const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap;
    const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap;
    const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap;
    const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap;
    const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap;
    const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap;
    const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap;
    const HAS_SPECULARMAP = !!material.specularMap;
    const HAS_SPECULAR_COLORMAP = !!material.specularColorMap;
    const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap;
    const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap;
    const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap;
    const HAS_GRADIENTMAP = !!material.gradientMap;
    const HAS_ALPHAMAP = !!material.alphaMap;
    const HAS_ALPHATEST = material.alphaTest > 0;
    const HAS_ALPHAHASH = !!material.alphaHash;
    const HAS_EXTENSIONS = !!material.extensions;
    let toneMapping = NoToneMapping;
    if (material.toneMapped) {
      if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) {
        toneMapping = renderer.toneMapping;
      }
    }
    const parameters = {
      shaderID,
      shaderType: material.type,
      shaderName: material.name,
      vertexShader: vertexShader2,
      fragmentShader: fragmentShader2,
      defines: material.defines,
      customVertexShaderID,
      customFragmentShaderID,
      isRawShaderMaterial: material.isRawShaderMaterial === true,
      glslVersion: material.glslVersion,
      precision,
      batching: IS_BATCHEDMESH,
      batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
      instancing: IS_INSTANCEDMESH,
      instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
      instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
      supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
      outputColorSpace: currentRenderTarget === null ? renderer.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace,
      alphaToCoverage: !!material.alphaToCoverage,
      map: HAS_MAP,
      matcap: HAS_MATCAP,
      envMap: HAS_ENVMAP,
      envMapMode: HAS_ENVMAP && envMap.mapping,
      envMapCubeUVHeight,
      aoMap: HAS_AOMAP,
      lightMap: HAS_LIGHTMAP,
      bumpMap: HAS_BUMPMAP,
      normalMap: HAS_NORMALMAP,
      displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
      emissiveMap: HAS_EMISSIVEMAP,
      normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
      normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
      metalnessMap: HAS_METALNESSMAP,
      roughnessMap: HAS_ROUGHNESSMAP,
      anisotropy: HAS_ANISOTROPY,
      anisotropyMap: HAS_ANISOTROPYMAP,
      clearcoat: HAS_CLEARCOAT,
      clearcoatMap: HAS_CLEARCOATMAP,
      clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
      clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
      dispersion: HAS_DISPERSION,
      iridescence: HAS_IRIDESCENCE,
      iridescenceMap: HAS_IRIDESCENCEMAP,
      iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
      sheen: HAS_SHEEN,
      sheenColorMap: HAS_SHEEN_COLORMAP,
      sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
      specularMap: HAS_SPECULARMAP,
      specularColorMap: HAS_SPECULAR_COLORMAP,
      specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
      transmission: HAS_TRANSMISSION,
      transmissionMap: HAS_TRANSMISSIONMAP,
      thicknessMap: HAS_THICKNESSMAP,
      gradientMap: HAS_GRADIENTMAP,
      opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
      alphaMap: HAS_ALPHAMAP,
      alphaTest: HAS_ALPHATEST,
      alphaHash: HAS_ALPHAHASH,
      combine: material.combine,
      //
      mapUv: HAS_MAP && getChannel(material.map.channel),
      aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel),
      lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel),
      bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel),
      normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel),
      displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel),
      emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel),
      metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel),
      roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel),
      anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel),
      clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel),
      clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel),
      clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel),
      iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel),
      iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel),
      sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel),
      sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel),
      specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel),
      specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel),
      specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel),
      transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel),
      thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel),
      alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel),
      //
      vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY),
      vertexColors: material.vertexColors,
      vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
      pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP),
      fog: !!fog,
      useFog: material.fog === true,
      fogExp2: !!fog && fog.isFogExp2,
      flatShading: material.flatShading === true,
      sizeAttenuation: material.sizeAttenuation === true,
      logarithmicDepthBuffer,
      reverseDepthBuffer,
      skinning: object.isSkinnedMesh === true,
      morphTargets: geometry.morphAttributes.position !== void 0,
      morphNormals: geometry.morphAttributes.normal !== void 0,
      morphColors: geometry.morphAttributes.color !== void 0,
      morphTargetsCount,
      morphTextureStride,
      numDirLights: lights.directional.length,
      numPointLights: lights.point.length,
      numSpotLights: lights.spot.length,
      numSpotLightMaps: lights.spotLightMap.length,
      numRectAreaLights: lights.rectArea.length,
      numHemiLights: lights.hemi.length,
      numDirLightShadows: lights.directionalShadowMap.length,
      numPointLightShadows: lights.pointShadowMap.length,
      numSpotLightShadows: lights.spotShadowMap.length,
      numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
      numLightProbes: lights.numLightProbes,
      numClippingPlanes: clipping.numPlanes,
      numClipIntersection: clipping.numIntersection,
      dithering: material.dithering,
      shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
      shadowMapType: renderer.shadowMap.type,
      toneMapping,
      decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer,
      decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer,
      premultipliedAlpha: material.premultipliedAlpha,
      doubleSided: material.side === DoubleSide,
      flipSided: material.side === BackSide,
      useDepthPacking: material.depthPacking >= 0,
      depthPacking: material.depthPacking || 0,
      index0AttributeName: material.index0AttributeName,
      extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"),
      extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"),
      rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"),
      customProgramCacheKey: material.customProgramCacheKey()
    };
    parameters.vertexUv1s = _activeChannels.has(1);
    parameters.vertexUv2s = _activeChannels.has(2);
    parameters.vertexUv3s = _activeChannels.has(3);
    _activeChannels.clear();
    return parameters;
  }
  function getProgramCacheKey(parameters) {
    const array = [];
    if (parameters.shaderID) {
      array.push(parameters.shaderID);
    } else {
      array.push(parameters.customVertexShaderID);
      array.push(parameters.customFragmentShaderID);
    }
    if (parameters.defines !== void 0) {
      for (const name in parameters.defines) {
        array.push(name);
        array.push(parameters.defines[name]);
      }
    }
    if (parameters.isRawShaderMaterial === false) {
      getProgramCacheKeyParameters(array, parameters);
      getProgramCacheKeyBooleans(array, parameters);
      array.push(renderer.outputColorSpace);
    }
    array.push(parameters.customProgramCacheKey);
    return array.join();
  }
  function getProgramCacheKeyParameters(array, parameters) {
    array.push(parameters.precision);
    array.push(parameters.outputColorSpace);
    array.push(parameters.envMapMode);
    array.push(parameters.envMapCubeUVHeight);
    array.push(parameters.mapUv);
    array.push(parameters.alphaMapUv);
    array.push(parameters.lightMapUv);
    array.push(parameters.aoMapUv);
    array.push(parameters.bumpMapUv);
    array.push(parameters.normalMapUv);
    array.push(parameters.displacementMapUv);
    array.push(parameters.emissiveMapUv);
    array.push(parameters.metalnessMapUv);
    array.push(parameters.roughnessMapUv);
    array.push(parameters.anisotropyMapUv);
    array.push(parameters.clearcoatMapUv);
    array.push(parameters.clearcoatNormalMapUv);
    array.push(parameters.clearcoatRoughnessMapUv);
    array.push(parameters.iridescenceMapUv);
    array.push(parameters.iridescenceThicknessMapUv);
    array.push(parameters.sheenColorMapUv);
    array.push(parameters.sheenRoughnessMapUv);
    array.push(parameters.specularMapUv);
    array.push(parameters.specularColorMapUv);
    array.push(parameters.specularIntensityMapUv);
    array.push(parameters.transmissionMapUv);
    array.push(parameters.thicknessMapUv);
    array.push(parameters.combine);
    array.push(parameters.fogExp2);
    array.push(parameters.sizeAttenuation);
    array.push(parameters.morphTargetsCount);
    array.push(parameters.morphAttributeCount);
    array.push(parameters.numDirLights);
    array.push(parameters.numPointLights);
    array.push(parameters.numSpotLights);
    array.push(parameters.numSpotLightMaps);
    array.push(parameters.numHemiLights);
    array.push(parameters.numRectAreaLights);
    array.push(parameters.numDirLightShadows);
    array.push(parameters.numPointLightShadows);
    array.push(parameters.numSpotLightShadows);
    array.push(parameters.numSpotLightShadowsWithMaps);
    array.push(parameters.numLightProbes);
    array.push(parameters.shadowMapType);
    array.push(parameters.toneMapping);
    array.push(parameters.numClippingPlanes);
    array.push(parameters.numClipIntersection);
    array.push(parameters.depthPacking);
  }
  function getProgramCacheKeyBooleans(array, parameters) {
    _programLayers.disableAll();
    if (parameters.supportsVertexTextures)
      _programLayers.enable(0);
    if (parameters.instancing)
      _programLayers.enable(1);
    if (parameters.instancingColor)
      _programLayers.enable(2);
    if (parameters.instancingMorph)
      _programLayers.enable(3);
    if (parameters.matcap)
      _programLayers.enable(4);
    if (parameters.envMap)
      _programLayers.enable(5);
    if (parameters.normalMapObjectSpace)
      _programLayers.enable(6);
    if (parameters.normalMapTangentSpace)
      _programLayers.enable(7);
    if (parameters.clearcoat)
      _programLayers.enable(8);
    if (parameters.iridescence)
      _programLayers.enable(9);
    if (parameters.alphaTest)
      _programLayers.enable(10);
    if (parameters.vertexColors)
      _programLayers.enable(11);
    if (parameters.vertexAlphas)
      _programLayers.enable(12);
    if (parameters.vertexUv1s)
      _programLayers.enable(13);
    if (parameters.vertexUv2s)
      _programLayers.enable(14);
    if (parameters.vertexUv3s)
      _programLayers.enable(15);
    if (parameters.vertexTangents)
      _programLayers.enable(16);
    if (parameters.anisotropy)
      _programLayers.enable(17);
    if (parameters.alphaHash)
      _programLayers.enable(18);
    if (parameters.batching)
      _programLayers.enable(19);
    if (parameters.dispersion)
      _programLayers.enable(20);
    if (parameters.batchingColor)
      _programLayers.enable(21);
    array.push(_programLayers.mask);
    _programLayers.disableAll();
    if (parameters.fog)
      _programLayers.enable(0);
    if (parameters.useFog)
      _programLayers.enable(1);
    if (parameters.flatShading)
      _programLayers.enable(2);
    if (parameters.logarithmicDepthBuffer)
      _programLayers.enable(3);
    if (parameters.reverseDepthBuffer)
      _programLayers.enable(4);
    if (parameters.skinning)
      _programLayers.enable(5);
    if (parameters.morphTargets)
      _programLayers.enable(6);
    if (parameters.morphNormals)
      _programLayers.enable(7);
    if (parameters.morphColors)
      _programLayers.enable(8);
    if (parameters.premultipliedAlpha)
      _programLayers.enable(9);
    if (parameters.shadowMapEnabled)
      _programLayers.enable(10);
    if (parameters.doubleSided)
      _programLayers.enable(11);
    if (parameters.flipSided)
      _programLayers.enable(12);
    if (parameters.useDepthPacking)
      _programLayers.enable(13);
    if (parameters.dithering)
      _programLayers.enable(14);
    if (parameters.transmission)
      _programLayers.enable(15);
    if (parameters.sheen)
      _programLayers.enable(16);
    if (parameters.opaque)
      _programLayers.enable(17);
    if (parameters.pointsUvs)
      _programLayers.enable(18);
    if (parameters.decodeVideoTexture)
      _programLayers.enable(19);
    if (parameters.decodeVideoTextureEmissive)
      _programLayers.enable(20);
    if (parameters.alphaToCoverage)
      _programLayers.enable(21);
    array.push(_programLayers.mask);
  }
  function getUniforms(material) {
    const shaderID = shaderIDs[material.type];
    let uniforms;
    if (shaderID) {
      const shader = ShaderLib[shaderID];
      uniforms = UniformsUtils.clone(shader.uniforms);
    } else {
      uniforms = material.uniforms;
    }
    return uniforms;
  }
  function acquireProgram(parameters, cacheKey) {
    let program;
    for (let p2 = 0, pl = programs.length; p2 < pl; p2++) {
      const preexistingProgram = programs[p2];
      if (preexistingProgram.cacheKey === cacheKey) {
        program = preexistingProgram;
        ++program.usedTimes;
        break;
      }
    }
    if (program === void 0) {
      program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
      programs.push(program);
    }
    return program;
  }
  function releaseProgram(program) {
    if (--program.usedTimes === 0) {
      const i2 = programs.indexOf(program);
      programs[i2] = programs[programs.length - 1];
      programs.pop();
      program.destroy();
    }
  }
  function releaseShaderCache(material) {
    _customShaders.remove(material);
  }
  function dispose2() {
    _customShaders.dispose();
  }
  return {
    getParameters,
    getProgramCacheKey,
    getUniforms,
    acquireProgram,
    releaseProgram,
    releaseShaderCache,
    // Exposed for resource monitoring & error feedback via renderer.info:
    programs,
    dispose: dispose2
  };
}
function WebGLProperties() {
  let properties = /* @__PURE__ */ new WeakMap();
  function has(object) {
    return properties.has(object);
  }
  function get(object) {
    let map = properties.get(object);
    if (map === void 0) {
      map = {};
      properties.set(object, map);
    }
    return map;
  }
  function remove(object) {
    properties.delete(object);
  }
  function update(object, key, value) {
    properties.get(object)[key] = value;
  }
  function dispose2() {
    properties = /* @__PURE__ */ new WeakMap();
  }
  return {
    has,
    get,
    remove,
    update,
    dispose: dispose2
  };
}
function painterSortStable(a3, b2) {
  if (a3.groupOrder !== b2.groupOrder) {
    return a3.groupOrder - b2.groupOrder;
  } else if (a3.renderOrder !== b2.renderOrder) {
    return a3.renderOrder - b2.renderOrder;
  } else if (a3.material.id !== b2.material.id) {
    return a3.material.id - b2.material.id;
  } else if (a3.z !== b2.z) {
    return a3.z - b2.z;
  } else {
    return a3.id - b2.id;
  }
}
function reversePainterSortStable(a3, b2) {
  if (a3.groupOrder !== b2.groupOrder) {
    return a3.groupOrder - b2.groupOrder;
  } else if (a3.renderOrder !== b2.renderOrder) {
    return a3.renderOrder - b2.renderOrder;
  } else if (a3.z !== b2.z) {
    return b2.z - a3.z;
  } else {
    return a3.id - b2.id;
  }
}
function WebGLRenderList() {
  const renderItems = [];
  let renderItemsIndex = 0;
  const opaque = [];
  const transmissive = [];
  const transparent = [];
  function init() {
    renderItemsIndex = 0;
    opaque.length = 0;
    transmissive.length = 0;
    transparent.length = 0;
  }
  function getNextRenderItem(object, geometry, material, groupOrder, z2, group) {
    let renderItem = renderItems[renderItemsIndex];
    if (renderItem === void 0) {
      renderItem = {
        id: object.id,
        object,
        geometry,
        material,
        groupOrder,
        renderOrder: object.renderOrder,
        z: z2,
        group
      };
      renderItems[renderItemsIndex] = renderItem;
    } else {
      renderItem.id = object.id;
      renderItem.object = object;
      renderItem.geometry = geometry;
      renderItem.material = material;
      renderItem.groupOrder = groupOrder;
      renderItem.renderOrder = object.renderOrder;
      renderItem.z = z2;
      renderItem.group = group;
    }
    renderItemsIndex++;
    return renderItem;
  }
  function push(object, geometry, material, groupOrder, z2, group) {
    const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group);
    if (material.transmission > 0) {
      transmissive.push(renderItem);
    } else if (material.transparent === true) {
      transparent.push(renderItem);
    } else {
      opaque.push(renderItem);
    }
  }
  function unshift(object, geometry, material, groupOrder, z2, group) {
    const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group);
    if (material.transmission > 0) {
      transmissive.unshift(renderItem);
    } else if (material.transparent === true) {
      transparent.unshift(renderItem);
    } else {
      opaque.unshift(renderItem);
    }
  }
  function sort(customOpaqueSort, customTransparentSort) {
    if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
    if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
    if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  }
  function finish() {
    for (let i2 = renderItemsIndex, il = renderItems.length; i2 < il; i2++) {
      const renderItem = renderItems[i2];
      if (renderItem.id === null) break;
      renderItem.id = null;
      renderItem.object = null;
      renderItem.geometry = null;
      renderItem.material = null;
      renderItem.group = null;
    }
  }
  return {
    opaque,
    transmissive,
    transparent,
    init,
    push,
    unshift,
    finish,
    sort
  };
}
function WebGLRenderLists() {
  let lists = /* @__PURE__ */ new WeakMap();
  function get(scene, renderCallDepth) {
    const listArray = lists.get(scene);
    let list;
    if (listArray === void 0) {
      list = new WebGLRenderList();
      lists.set(scene, [list]);
    } else {
      if (renderCallDepth >= listArray.length) {
        list = new WebGLRenderList();
        listArray.push(list);
      } else {
        list = listArray[renderCallDepth];
      }
    }
    return list;
  }
  function dispose2() {
    lists = /* @__PURE__ */ new WeakMap();
  }
  return {
    get,
    dispose: dispose2
  };
}
function UniformsCache() {
  const lights = {};
  return {
    get: function(light) {
      if (lights[light.id] !== void 0) {
        return lights[light.id];
      }
      let uniforms;
      switch (light.type) {
        case "DirectionalLight":
          uniforms = {
            direction: new Vector3(),
            color: new Color()
          };
          break;
        case "SpotLight":
          uniforms = {
            position: new Vector3(),
            direction: new Vector3(),
            color: new Color(),
            distance: 0,
            coneCos: 0,
            penumbraCos: 0,
            decay: 0
          };
          break;
        case "PointLight":
          uniforms = {
            position: new Vector3(),
            color: new Color(),
            distance: 0,
            decay: 0
          };
          break;
        case "HemisphereLight":
          uniforms = {
            direction: new Vector3(),
            skyColor: new Color(),
            groundColor: new Color()
          };
          break;
        case "RectAreaLight":
          uniforms = {
            color: new Color(),
            position: new Vector3(),
            halfWidth: new Vector3(),
            halfHeight: new Vector3()
          };
          break;
      }
      lights[light.id] = uniforms;
      return uniforms;
    }
  };
}
function ShadowUniformsCache() {
  const lights = {};
  return {
    get: function(light) {
      if (lights[light.id] !== void 0) {
        return lights[light.id];
      }
      let uniforms;
      switch (light.type) {
        case "DirectionalLight":
          uniforms = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new Vector2()
          };
          break;
        case "SpotLight":
          uniforms = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new Vector2()
          };
          break;
        case "PointLight":
          uniforms = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new Vector2(),
            shadowCameraNear: 1,
            shadowCameraFar: 1e3
          };
          break;
      }
      lights[light.id] = uniforms;
      return uniforms;
    }
  };
}
let nextVersion = 0;
function shadowCastingAndTexturingLightsFirst(lightA, lightB) {
  return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0);
}
function WebGLLights(extensions) {
  const cache = new UniformsCache();
  const shadowCache = ShadowUniformsCache();
  const state = {
    version: 0,
    hash: {
      directionalLength: -1,
      pointLength: -1,
      spotLength: -1,
      rectAreaLength: -1,
      hemiLength: -1,
      numDirectionalShadows: -1,
      numPointShadows: -1,
      numSpotShadows: -1,
      numSpotMaps: -1,
      numLightProbes: -1
    },
    ambient: [0, 0, 0],
    probe: [],
    directional: [],
    directionalShadow: [],
    directionalShadowMap: [],
    directionalShadowMatrix: [],
    spot: [],
    spotLightMap: [],
    spotShadow: [],
    spotShadowMap: [],
    spotLightMatrix: [],
    rectArea: [],
    rectAreaLTC1: null,
    rectAreaLTC2: null,
    point: [],
    pointShadow: [],
    pointShadowMap: [],
    pointShadowMatrix: [],
    hemi: [],
    numSpotLightShadowsWithMaps: 0,
    numLightProbes: 0
  };
  for (let i2 = 0; i2 < 9; i2++) state.probe.push(new Vector3());
  const vector3 = new Vector3();
  const matrix4 = new Matrix4();
  const matrix42 = new Matrix4();
  function setup(lights) {
    let r2 = 0, g2 = 0, b2 = 0;
    for (let i2 = 0; i2 < 9; i2++) state.probe[i2].set(0, 0, 0);
    let directionalLength = 0;
    let pointLength = 0;
    let spotLength = 0;
    let rectAreaLength = 0;
    let hemiLength = 0;
    let numDirectionalShadows = 0;
    let numPointShadows = 0;
    let numSpotShadows = 0;
    let numSpotMaps = 0;
    let numSpotShadowsWithMaps = 0;
    let numLightProbes = 0;
    lights.sort(shadowCastingAndTexturingLightsFirst);
    for (let i2 = 0, l2 = lights.length; i2 < l2; i2++) {
      const light = lights[i2];
      const color = light.color;
      const intensity = light.intensity;
      const distance = light.distance;
      const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
      if (light.isAmbientLight) {
        r2 += color.r * intensity;
        g2 += color.g * intensity;
        b2 += color.b * intensity;
      } else if (light.isLightProbe) {
        for (let j2 = 0; j2 < 9; j2++) {
          state.probe[j2].addScaledVector(light.sh.coefficients[j2], intensity);
        }
        numLightProbes++;
      } else if (light.isDirectionalLight) {
        const uniforms = cache.get(light);
        uniforms.color.copy(light.color).multiplyScalar(light.intensity);
        if (light.castShadow) {
          const shadow = light.shadow;
          const shadowUniforms = shadowCache.get(light);
          shadowUniforms.shadowIntensity = shadow.intensity;
          shadowUniforms.shadowBias = shadow.bias;
          shadowUniforms.shadowNormalBias = shadow.normalBias;
          shadowUniforms.shadowRadius = shadow.radius;
          shadowUniforms.shadowMapSize = shadow.mapSize;
          state.directionalShadow[directionalLength] = shadowUniforms;
          state.directionalShadowMap[directionalLength] = shadowMap;
          state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
          numDirectionalShadows++;
        }
        state.directional[directionalLength] = uniforms;
        directionalLength++;
      } else if (light.isSpotLight) {
        const uniforms = cache.get(light);
        uniforms.position.setFromMatrixPosition(light.matrixWorld);
        uniforms.color.copy(color).multiplyScalar(intensity);
        uniforms.distance = distance;
        uniforms.coneCos = Math.cos(light.angle);
        uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
        uniforms.decay = light.decay;
        state.spot[spotLength] = uniforms;
        const shadow = light.shadow;
        if (light.map) {
          state.spotLightMap[numSpotMaps] = light.map;
          numSpotMaps++;
          shadow.updateMatrices(light);
          if (light.castShadow) numSpotShadowsWithMaps++;
        }
        state.spotLightMatrix[spotLength] = shadow.matrix;
        if (light.castShadow) {
          const shadowUniforms = shadowCache.get(light);
          shadowUniforms.shadowIntensity = shadow.intensity;
          shadowUniforms.shadowBias = shadow.bias;
          shadowUniforms.shadowNormalBias = shadow.normalBias;
          shadowUniforms.shadowRadius = shadow.radius;
          shadowUniforms.shadowMapSize = shadow.mapSize;
          state.spotShadow[spotLength] = shadowUniforms;
          state.spotShadowMap[spotLength] = shadowMap;
          numSpotShadows++;
        }
        spotLength++;
      } else if (light.isRectAreaLight) {
        const uniforms = cache.get(light);
        uniforms.color.copy(color).multiplyScalar(intensity);
        uniforms.halfWidth.set(light.width * 0.5, 0, 0);
        uniforms.halfHeight.set(0, light.height * 0.5, 0);
        state.rectArea[rectAreaLength] = uniforms;
        rectAreaLength++;
      } else if (light.isPointLight) {
        const uniforms = cache.get(light);
        uniforms.color.copy(light.color).multiplyScalar(light.intensity);
        uniforms.distance = light.distance;
        uniforms.decay = light.decay;
        if (light.castShadow) {
          const shadow = light.shadow;
          const shadowUniforms = shadowCache.get(light);
          shadowUniforms.shadowIntensity = shadow.intensity;
          shadowUniforms.shadowBias = shadow.bias;
          shadowUniforms.shadowNormalBias = shadow.normalBias;
          shadowUniforms.shadowRadius = shadow.radius;
          shadowUniforms.shadowMapSize = shadow.mapSize;
          shadowUniforms.shadowCameraNear = shadow.camera.near;
          shadowUniforms.shadowCameraFar = shadow.camera.far;
          state.pointShadow[pointLength] = shadowUniforms;
          state.pointShadowMap[pointLength] = shadowMap;
          state.pointShadowMatrix[pointLength] = light.shadow.matrix;
          numPointShadows++;
        }
        state.point[pointLength] = uniforms;
        pointLength++;
      } else if (light.isHemisphereLight) {
        const uniforms = cache.get(light);
        uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
        uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
        state.hemi[hemiLength] = uniforms;
        hemiLength++;
      }
    }
    if (rectAreaLength > 0) {
      if (extensions.has("OES_texture_float_linear") === true) {
        state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
        state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
      } else {
        state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
        state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
      }
    }
    state.ambient[0] = r2;
    state.ambient[1] = g2;
    state.ambient[2] = b2;
    const hash = state.hash;
    if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) {
      state.directional.length = directionalLength;
      state.spot.length = spotLength;
      state.rectArea.length = rectAreaLength;
      state.point.length = pointLength;
      state.hemi.length = hemiLength;
      state.directionalShadow.length = numDirectionalShadows;
      state.directionalShadowMap.length = numDirectionalShadows;
      state.pointShadow.length = numPointShadows;
      state.pointShadowMap.length = numPointShadows;
      state.spotShadow.length = numSpotShadows;
      state.spotShadowMap.length = numSpotShadows;
      state.directionalShadowMatrix.length = numDirectionalShadows;
      state.pointShadowMatrix.length = numPointShadows;
      state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
      state.spotLightMap.length = numSpotMaps;
      state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
      state.numLightProbes = numLightProbes;
      hash.directionalLength = directionalLength;
      hash.pointLength = pointLength;
      hash.spotLength = spotLength;
      hash.rectAreaLength = rectAreaLength;
      hash.hemiLength = hemiLength;
      hash.numDirectionalShadows = numDirectionalShadows;
      hash.numPointShadows = numPointShadows;
      hash.numSpotShadows = numSpotShadows;
      hash.numSpotMaps = numSpotMaps;
      hash.numLightProbes = numLightProbes;
      state.version = nextVersion++;
    }
  }
  function setupView(lights, camera) {
    let directionalLength = 0;
    let pointLength = 0;
    let spotLength = 0;
    let rectAreaLength = 0;
    let hemiLength = 0;
    const viewMatrix = camera.matrixWorldInverse;
    for (let i2 = 0, l2 = lights.length; i2 < l2; i2++) {
      const light = lights[i2];
      if (light.isDirectionalLight) {
        const uniforms = state.directional[directionalLength];
        uniforms.direction.setFromMatrixPosition(light.matrixWorld);
        vector3.setFromMatrixPosition(light.target.matrixWorld);
        uniforms.direction.sub(vector3);
        uniforms.direction.transformDirection(viewMatrix);
        directionalLength++;
      } else if (light.isSpotLight) {
        const uniforms = state.spot[spotLength];
        uniforms.position.setFromMatrixPosition(light.matrixWorld);
        uniforms.position.applyMatrix4(viewMatrix);
        uniforms.direction.setFromMatrixPosition(light.matrixWorld);
        vector3.setFromMatrixPosition(light.target.matrixWorld);
        uniforms.direction.sub(vector3);
        uniforms.direction.transformDirection(viewMatrix);
        spotLength++;
      } else if (light.isRectAreaLight) {
        const uniforms = state.rectArea[rectAreaLength];
        uniforms.position.setFromMatrixPosition(light.matrixWorld);
        uniforms.position.applyMatrix4(viewMatrix);
        matrix42.identity();
        matrix4.copy(light.matrixWorld);
        matrix4.premultiply(viewMatrix);
        matrix42.extractRotation(matrix4);
        uniforms.halfWidth.set(light.width * 0.5, 0, 0);
        uniforms.halfHeight.set(0, light.height * 0.5, 0);
        uniforms.halfWidth.applyMatrix4(matrix42);
        uniforms.halfHeight.applyMatrix4(matrix42);
        rectAreaLength++;
      } else if (light.isPointLight) {
        const uniforms = state.point[pointLength];
        uniforms.position.setFromMatrixPosition(light.matrixWorld);
        uniforms.position.applyMatrix4(viewMatrix);
        pointLength++;
      } else if (light.isHemisphereLight) {
        const uniforms = state.hemi[hemiLength];
        uniforms.direction.setFromMatrixPosition(light.matrixWorld);
        uniforms.direction.transformDirection(viewMatrix);
        hemiLength++;
      }
    }
  }
  return {
    setup,
    setupView,
    state
  };
}
function WebGLRenderState(extensions) {
  const lights = new WebGLLights(extensions);
  const lightsArray = [];
  const shadowsArray = [];
  function init(camera) {
    state.camera = camera;
    lightsArray.length = 0;
    shadowsArray.length = 0;
  }
  function pushLight(light) {
    lightsArray.push(light);
  }
  function pushShadow(shadowLight) {
    shadowsArray.push(shadowLight);
  }
  function setupLights() {
    lights.setup(lightsArray);
  }
  function setupLightsView(camera) {
    lights.setupView(lightsArray, camera);
  }
  const state = {
    lightsArray,
    shadowsArray,
    camera: null,
    lights,
    transmissionRenderTarget: {}
  };
  return {
    init,
    state,
    setupLights,
    setupLightsView,
    pushLight,
    pushShadow
  };
}
function WebGLRenderStates(extensions) {
  let renderStates = /* @__PURE__ */ new WeakMap();
  function get(scene, renderCallDepth = 0) {
    const renderStateArray = renderStates.get(scene);
    let renderState;
    if (renderStateArray === void 0) {
      renderState = new WebGLRenderState(extensions);
      renderStates.set(scene, [renderState]);
    } else {
      if (renderCallDepth >= renderStateArray.length) {
        renderState = new WebGLRenderState(extensions);
        renderStateArray.push(renderState);
      } else {
        renderState = renderStateArray[renderCallDepth];
      }
    }
    return renderState;
  }
  function dispose2() {
    renderStates = /* @__PURE__ */ new WeakMap();
  }
  return {
    get,
    dispose: dispose2
  };
}
const vertex = "void main() {\n	gl_Position = vec4( position, 1.0 );\n}";
const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n	const float samples = float( VSM_SAMPLES );\n	float mean = 0.0;\n	float squared_mean = 0.0;\n	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n	for ( float i = 0.0; i < samples; i ++ ) {\n		float uvOffset = uvStart + i * uvStride;\n		#ifdef HORIZONTAL_PASS\n			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n			mean += distribution.x;\n			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n		#else\n			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n			mean += depth;\n			squared_mean += depth * depth;\n		#endif\n	}\n	mean = mean / samples;\n	squared_mean = squared_mean / samples;\n	float std_dev = sqrt( squared_mean - mean * mean );\n	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
function WebGLShadowMap(renderer, objects, capabilities) {
  let _frustum2 = new Frustum();
  const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport2 = new Vector4(), _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial(), _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize;
  const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide };
  const shadowMaterialVertical = new ShaderMaterial({
    defines: {
      VSM_SAMPLES: 8
    },
    uniforms: {
      shadow_pass: { value: null },
      resolution: { value: new Vector2() },
      radius: { value: 4 }
    },
    vertexShader: vertex,
    fragmentShader: fragment
  });
  const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  const fullScreenTri = new BufferGeometry();
  fullScreenTri.setAttribute(
    "position",
    new BufferAttribute(
      new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]),
      3
    )
  );
  const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  const scope = this;
  this.enabled = false;
  this.autoUpdate = true;
  this.needsUpdate = false;
  this.type = PCFShadowMap;
  let _previousType = this.type;
  this.render = function(lights, scene, camera) {
    if (scope.enabled === false) return;
    if (scope.autoUpdate === false && scope.needsUpdate === false) return;
    if (lights.length === 0) return;
    const currentRenderTarget = renderer.getRenderTarget();
    const activeCubeFace = renderer.getActiveCubeFace();
    const activeMipmapLevel = renderer.getActiveMipmapLevel();
    const _state = renderer.state;
    _state.setBlending(NoBlending);
    _state.buffers.color.setClear(1, 1, 1, 1);
    _state.buffers.depth.setTest(true);
    _state.setScissorTest(false);
    const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap;
    const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap;
    for (let i2 = 0, il = lights.length; i2 < il; i2++) {
      const light = lights[i2];
      const shadow = light.shadow;
      if (shadow === void 0) {
        console.warn("THREE.WebGLShadowMap:", light, "has no shadow.");
        continue;
      }
      if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
      _shadowMapSize.copy(shadow.mapSize);
      const shadowFrameExtents = shadow.getFrameExtents();
      _shadowMapSize.multiply(shadowFrameExtents);
      _viewportSize.copy(shadow.mapSize);
      if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
        if (_shadowMapSize.x > _maxTextureSize) {
          _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
          _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
          shadow.mapSize.x = _viewportSize.x;
        }
        if (_shadowMapSize.y > _maxTextureSize) {
          _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
          _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
          shadow.mapSize.y = _viewportSize.y;
        }
      }
      if (shadow.map === null || toVSM === true || fromVSM === true) {
        const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
        if (shadow.map !== null) {
          shadow.map.dispose();
        }
        shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
        shadow.map.texture.name = light.name + ".shadowMap";
        shadow.camera.updateProjectionMatrix();
      }
      renderer.setRenderTarget(shadow.map);
      renderer.clear();
      const viewportCount = shadow.getViewportCount();
      for (let vp = 0; vp < viewportCount; vp++) {
        const viewport = shadow.getViewport(vp);
        _viewport2.set(
          _viewportSize.x * viewport.x,
          _viewportSize.y * viewport.y,
          _viewportSize.x * viewport.z,
          _viewportSize.y * viewport.w
        );
        _state.viewport(_viewport2);
        shadow.updateMatrices(light, vp);
        _frustum2 = shadow.getFrustum();
        renderObject(scene, camera, shadow.camera, light, this.type);
      }
      if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
        VSMPass(shadow, camera);
      }
      shadow.needsUpdate = false;
    }
    _previousType = this.type;
    scope.needsUpdate = false;
    renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  };
  function VSMPass(shadow, camera) {
    const geometry = objects.update(fullScreenMesh);
    if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
      shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
      shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
      shadowMaterialVertical.needsUpdate = true;
      shadowMaterialHorizontal.needsUpdate = true;
    }
    if (shadow.mapPass === null) {
      shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
    }
    shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
    shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
    shadowMaterialVertical.uniforms.radius.value = shadow.radius;
    renderer.setRenderTarget(shadow.mapPass);
    renderer.clear();
    renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null);
    shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
    shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
    shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
    renderer.setRenderTarget(shadow.map);
    renderer.clear();
    renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  }
  function getDepthMaterial(object, material, light, type) {
    let result = null;
    const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
    if (customMaterial !== void 0) {
      result = customMaterial;
    } else {
      result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
      if (renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) {
        const keyA = result.uuid, keyB = material.uuid;
        let materialsForVariant = _materialCache[keyA];
        if (materialsForVariant === void 0) {
          materialsForVariant = {};
          _materialCache[keyA] = materialsForVariant;
        }
        let cachedMaterial = materialsForVariant[keyB];
        if (cachedMaterial === void 0) {
          cachedMaterial = result.clone();
          materialsForVariant[keyB] = cachedMaterial;
          material.addEventListener("dispose", onMaterialDispose);
        }
        result = cachedMaterial;
      }
    }
    result.visible = material.visible;
    result.wireframe = material.wireframe;
    if (type === VSMShadowMap) {
      result.side = material.shadowSide !== null ? material.shadowSide : material.side;
    } else {
      result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
    }
    result.alphaMap = material.alphaMap;
    result.alphaTest = material.alphaTest;
    result.map = material.map;
    result.clipShadows = material.clipShadows;
    result.clippingPlanes = material.clippingPlanes;
    result.clipIntersection = material.clipIntersection;
    result.displacementMap = material.displacementMap;
    result.displacementScale = material.displacementScale;
    result.displacementBias = material.displacementBias;
    result.wireframeLinewidth = material.wireframeLinewidth;
    result.linewidth = material.linewidth;
    if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
      const materialProperties = renderer.properties.get(result);
      materialProperties.light = light;
    }
    return result;
  }
  function renderObject(object, camera, shadowCamera, light, type) {
    if (object.visible === false) return;
    const visible = object.layers.test(camera.layers);
    if (visible && (object.isMesh || object.isLine || object.isPoints)) {
      if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) {
        object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
        const geometry = objects.update(object);
        const material = object.material;
        if (Array.isArray(material)) {
          const groups = geometry.groups;
          for (let k2 = 0, kl = groups.length; k2 < kl; k2++) {
            const group = groups[k2];
            const groupMaterial = material[group.materialIndex];
            if (groupMaterial && groupMaterial.visible) {
              const depthMaterial = getDepthMaterial(object, groupMaterial, light, type);
              object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group);
              renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
              object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group);
            }
          }
        } else if (material.visible) {
          const depthMaterial = getDepthMaterial(object, material, light, type);
          object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null);
          renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
          object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null);
        }
      }
    }
    const children = object.children;
    for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
      renderObject(children[i2], camera, shadowCamera, light, type);
    }
  }
  function onMaterialDispose(event) {
    const material = event.target;
    material.removeEventListener("dispose", onMaterialDispose);
    for (const id in _materialCache) {
      const cache = _materialCache[id];
      const uuid = event.target.uuid;
      if (uuid in cache) {
        const shadowMaterial = cache[uuid];
        shadowMaterial.dispose();
        delete cache[uuid];
      }
    }
  }
}
const reversedFuncs = {
  [NeverDepth]: AlwaysDepth,
  [LessDepth]: GreaterDepth,
  [EqualDepth]: NotEqualDepth,
  [LessEqualDepth]: GreaterEqualDepth,
  [AlwaysDepth]: NeverDepth,
  [GreaterDepth]: LessDepth,
  [NotEqualDepth]: EqualDepth,
  [GreaterEqualDepth]: LessEqualDepth
};
function WebGLState(gl, extensions) {
  function ColorBuffer() {
    let locked = false;
    const color = new Vector4();
    let currentColorMask = null;
    const currentColorClear = new Vector4(0, 0, 0, 0);
    return {
      setMask: function(colorMask) {
        if (currentColorMask !== colorMask && !locked) {
          gl.colorMask(colorMask, colorMask, colorMask, colorMask);
          currentColorMask = colorMask;
        }
      },
      setLocked: function(lock) {
        locked = lock;
      },
      setClear: function(r2, g2, b2, a3, premultipliedAlpha) {
        if (premultipliedAlpha === true) {
          r2 *= a3;
          g2 *= a3;
          b2 *= a3;
        }
        color.set(r2, g2, b2, a3);
        if (currentColorClear.equals(color) === false) {
          gl.clearColor(r2, g2, b2, a3);
          currentColorClear.copy(color);
        }
      },
      reset: function() {
        locked = false;
        currentColorMask = null;
        currentColorClear.set(-1, 0, 0, 0);
      }
    };
  }
  function DepthBuffer() {
    let locked = false;
    let reversed = false;
    let currentDepthMask = null;
    let currentDepthFunc = null;
    let currentDepthClear = null;
    return {
      setReversed: function(value) {
        if (reversed !== value) {
          const ext = extensions.get("EXT_clip_control");
          if (reversed) {
            ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT);
          } else {
            ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT);
          }
          const oldDepth = currentDepthClear;
          currentDepthClear = null;
          this.setClear(oldDepth);
        }
        reversed = value;
      },
      getReversed: function() {
        return reversed;
      },
      setTest: function(depthTest) {
        if (depthTest) {
          enable(gl.DEPTH_TEST);
        } else {
          disable(gl.DEPTH_TEST);
        }
      },
      setMask: function(depthMask) {
        if (currentDepthMask !== depthMask && !locked) {
          gl.depthMask(depthMask);
          currentDepthMask = depthMask;
        }
      },
      setFunc: function(depthFunc) {
        if (reversed) depthFunc = reversedFuncs[depthFunc];
        if (currentDepthFunc !== depthFunc) {
          switch (depthFunc) {
            case NeverDepth:
              gl.depthFunc(gl.NEVER);
              break;
            case AlwaysDepth:
              gl.depthFunc(gl.ALWAYS);
              break;
            case LessDepth:
              gl.depthFunc(gl.LESS);
              break;
            case LessEqualDepth:
              gl.depthFunc(gl.LEQUAL);
              break;
            case EqualDepth:
              gl.depthFunc(gl.EQUAL);
              break;
            case GreaterEqualDepth:
              gl.depthFunc(gl.GEQUAL);
              break;
            case GreaterDepth:
              gl.depthFunc(gl.GREATER);
              break;
            case NotEqualDepth:
              gl.depthFunc(gl.NOTEQUAL);
              break;
            default:
              gl.depthFunc(gl.LEQUAL);
          }
          currentDepthFunc = depthFunc;
        }
      },
      setLocked: function(lock) {
        locked = lock;
      },
      setClear: function(depth) {
        if (currentDepthClear !== depth) {
          if (reversed) {
            depth = 1 - depth;
          }
          gl.clearDepth(depth);
          currentDepthClear = depth;
        }
      },
      reset: function() {
        locked = false;
        currentDepthMask = null;
        currentDepthFunc = null;
        currentDepthClear = null;
        reversed = false;
      }
    };
  }
  function StencilBuffer() {
    let locked = false;
    let currentStencilMask = null;
    let currentStencilFunc = null;
    let currentStencilRef = null;
    let currentStencilFuncMask = null;
    let currentStencilFail = null;
    let currentStencilZFail = null;
    let currentStencilZPass = null;
    let currentStencilClear = null;
    return {
      setTest: function(stencilTest) {
        if (!locked) {
          if (stencilTest) {
            enable(gl.STENCIL_TEST);
          } else {
            disable(gl.STENCIL_TEST);
          }
        }
      },
      setMask: function(stencilMask) {
        if (currentStencilMask !== stencilMask && !locked) {
          gl.stencilMask(stencilMask);
          currentStencilMask = stencilMask;
        }
      },
      setFunc: function(stencilFunc, stencilRef, stencilMask) {
        if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
          gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
          currentStencilFunc = stencilFunc;
          currentStencilRef = stencilRef;
          currentStencilFuncMask = stencilMask;
        }
      },
      setOp: function(stencilFail, stencilZFail, stencilZPass) {
        if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
          gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
          currentStencilFail = stencilFail;
          currentStencilZFail = stencilZFail;
          currentStencilZPass = stencilZPass;
        }
      },
      setLocked: function(lock) {
        locked = lock;
      },
      setClear: function(stencil) {
        if (currentStencilClear !== stencil) {
          gl.clearStencil(stencil);
          currentStencilClear = stencil;
        }
      },
      reset: function() {
        locked = false;
        currentStencilMask = null;
        currentStencilFunc = null;
        currentStencilRef = null;
        currentStencilFuncMask = null;
        currentStencilFail = null;
        currentStencilZFail = null;
        currentStencilZPass = null;
        currentStencilClear = null;
      }
    };
  }
  const colorBuffer = new ColorBuffer();
  const depthBuffer = new DepthBuffer();
  const stencilBuffer = new StencilBuffer();
  const uboBindings = /* @__PURE__ */ new WeakMap();
  const uboProgramMap = /* @__PURE__ */ new WeakMap();
  let enabledCapabilities = {};
  let currentBoundFramebuffers = {};
  let currentDrawbuffers = /* @__PURE__ */ new WeakMap();
  let defaultDrawbuffers = [];
  let currentProgram = null;
  let currentBlendingEnabled = false;
  let currentBlending = null;
  let currentBlendEquation = null;
  let currentBlendSrc = null;
  let currentBlendDst = null;
  let currentBlendEquationAlpha = null;
  let currentBlendSrcAlpha = null;
  let currentBlendDstAlpha = null;
  let currentBlendColor = new Color(0, 0, 0);
  let currentBlendAlpha = 0;
  let currentPremultipledAlpha = false;
  let currentFlipSided = null;
  let currentCullFace = null;
  let currentLineWidth = null;
  let currentPolygonOffsetFactor = null;
  let currentPolygonOffsetUnits = null;
  const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  let lineWidthAvailable = false;
  let version2 = 0;
  const glVersion = gl.getParameter(gl.VERSION);
  if (glVersion.indexOf("WebGL") !== -1) {
    version2 = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
    lineWidthAvailable = version2 >= 1;
  } else if (glVersion.indexOf("OpenGL ES") !== -1) {
    version2 = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
    lineWidthAvailable = version2 >= 2;
  }
  let currentTextureSlot = null;
  let currentBoundTextures = {};
  const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  const viewportParam = gl.getParameter(gl.VIEWPORT);
  const currentScissor = new Vector4().fromArray(scissorParam);
  const currentViewport = new Vector4().fromArray(viewportParam);
  function createTexture(type, target, count, dimensions) {
    const data = new Uint8Array(4);
    const texture = gl.createTexture();
    gl.bindTexture(type, texture);
    gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    for (let i2 = 0; i2 < count; i2++) {
      if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) {
        gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
      } else {
        gl.texImage2D(target + i2, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
      }
    }
    return texture;
  }
  const emptyTextures = {};
  emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6);
  emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1);
  emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1);
  colorBuffer.setClear(0, 0, 0, 1);
  depthBuffer.setClear(1);
  stencilBuffer.setClear(0);
  enable(gl.DEPTH_TEST);
  depthBuffer.setFunc(LessEqualDepth);
  setFlipSided(false);
  setCullFace(CullFaceBack);
  enable(gl.CULL_FACE);
  setBlending(NoBlending);
  function enable(id) {
    if (enabledCapabilities[id] !== true) {
      gl.enable(id);
      enabledCapabilities[id] = true;
    }
  }
  function disable(id) {
    if (enabledCapabilities[id] !== false) {
      gl.disable(id);
      enabledCapabilities[id] = false;
    }
  }
  function bindFramebuffer(target, framebuffer) {
    if (currentBoundFramebuffers[target] !== framebuffer) {
      gl.bindFramebuffer(target, framebuffer);
      currentBoundFramebuffers[target] = framebuffer;
      if (target === gl.DRAW_FRAMEBUFFER) {
        currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
      }
      if (target === gl.FRAMEBUFFER) {
        currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
      }
      return true;
    }
    return false;
  }
  function drawBuffers(renderTarget, framebuffer) {
    let drawBuffers2 = defaultDrawbuffers;
    let needsUpdate = false;
    if (renderTarget) {
      drawBuffers2 = currentDrawbuffers.get(framebuffer);
      if (drawBuffers2 === void 0) {
        drawBuffers2 = [];
        currentDrawbuffers.set(framebuffer, drawBuffers2);
      }
      const textures = renderTarget.textures;
      if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) {
        for (let i2 = 0, il = textures.length; i2 < il; i2++) {
          drawBuffers2[i2] = gl.COLOR_ATTACHMENT0 + i2;
        }
        drawBuffers2.length = textures.length;
        needsUpdate = true;
      }
    } else {
      if (drawBuffers2[0] !== gl.BACK) {
        drawBuffers2[0] = gl.BACK;
        needsUpdate = true;
      }
    }
    if (needsUpdate) {
      gl.drawBuffers(drawBuffers2);
    }
  }
  function useProgram(program) {
    if (currentProgram !== program) {
      gl.useProgram(program);
      currentProgram = program;
      return true;
    }
    return false;
  }
  const equationToGL = {
    [AddEquation]: gl.FUNC_ADD,
    [SubtractEquation]: gl.FUNC_SUBTRACT,
    [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  };
  equationToGL[MinEquation] = gl.MIN;
  equationToGL[MaxEquation] = gl.MAX;
  const factorToGL = {
    [ZeroFactor]: gl.ZERO,
    [OneFactor]: gl.ONE,
    [SrcColorFactor]: gl.SRC_COLOR,
    [SrcAlphaFactor]: gl.SRC_ALPHA,
    [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
    [DstColorFactor]: gl.DST_COLOR,
    [DstAlphaFactor]: gl.DST_ALPHA,
    [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
    [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
    [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
    [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA,
    [ConstantColorFactor]: gl.CONSTANT_COLOR,
    [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR,
    [ConstantAlphaFactor]: gl.CONSTANT_ALPHA,
    [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA
  };
  function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) {
    if (blending === NoBlending) {
      if (currentBlendingEnabled === true) {
        disable(gl.BLEND);
        currentBlendingEnabled = false;
      }
      return;
    }
    if (currentBlendingEnabled === false) {
      enable(gl.BLEND);
      currentBlendingEnabled = true;
    }
    if (blending !== CustomBlending) {
      if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
        if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
          gl.blendEquation(gl.FUNC_ADD);
          currentBlendEquation = AddEquation;
          currentBlendEquationAlpha = AddEquation;
        }
        if (premultipliedAlpha) {
          switch (blending) {
            case NormalBlending:
              gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
              break;
            case AdditiveBlending:
              gl.blendFunc(gl.ONE, gl.ONE);
              break;
            case SubtractiveBlending:
              gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
              break;
            case MultiplyBlending:
              gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", blending);
              break;
          }
        } else {
          switch (blending) {
            case NormalBlending:
              gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
              break;
            case AdditiveBlending:
              gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
              break;
            case SubtractiveBlending:
              gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
              break;
            case MultiplyBlending:
              gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", blending);
              break;
          }
        }
        currentBlendSrc = null;
        currentBlendDst = null;
        currentBlendSrcAlpha = null;
        currentBlendDstAlpha = null;
        currentBlendColor.set(0, 0, 0);
        currentBlendAlpha = 0;
        currentBlending = blending;
        currentPremultipledAlpha = premultipliedAlpha;
      }
      return;
    }
    blendEquationAlpha = blendEquationAlpha || blendEquation;
    blendSrcAlpha = blendSrcAlpha || blendSrc;
    blendDstAlpha = blendDstAlpha || blendDst;
    if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
      gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
      currentBlendEquation = blendEquation;
      currentBlendEquationAlpha = blendEquationAlpha;
    }
    if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
      gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
      currentBlendSrc = blendSrc;
      currentBlendDst = blendDst;
      currentBlendSrcAlpha = blendSrcAlpha;
      currentBlendDstAlpha = blendDstAlpha;
    }
    if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) {
      gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha);
      currentBlendColor.copy(blendColor);
      currentBlendAlpha = blendAlpha;
    }
    currentBlending = blending;
    currentPremultipledAlpha = false;
  }
  function setMaterial(material, frontFaceCW) {
    material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
    let flipSided = material.side === BackSide;
    if (frontFaceCW) flipSided = !flipSided;
    setFlipSided(flipSided);
    material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha);
    depthBuffer.setFunc(material.depthFunc);
    depthBuffer.setTest(material.depthTest);
    depthBuffer.setMask(material.depthWrite);
    colorBuffer.setMask(material.colorWrite);
    const stencilWrite = material.stencilWrite;
    stencilBuffer.setTest(stencilWrite);
    if (stencilWrite) {
      stencilBuffer.setMask(material.stencilWriteMask);
      stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
      stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
    }
    setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
    material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  }
  function setFlipSided(flipSided) {
    if (currentFlipSided !== flipSided) {
      if (flipSided) {
        gl.frontFace(gl.CW);
      } else {
        gl.frontFace(gl.CCW);
      }
      currentFlipSided = flipSided;
    }
  }
  function setCullFace(cullFace) {
    if (cullFace !== CullFaceNone) {
      enable(gl.CULL_FACE);
      if (cullFace !== currentCullFace) {
        if (cullFace === CullFaceBack) {
          gl.cullFace(gl.BACK);
        } else if (cullFace === CullFaceFront) {
          gl.cullFace(gl.FRONT);
        } else {
          gl.cullFace(gl.FRONT_AND_BACK);
        }
      }
    } else {
      disable(gl.CULL_FACE);
    }
    currentCullFace = cullFace;
  }
  function setLineWidth(width) {
    if (width !== currentLineWidth) {
      if (lineWidthAvailable) gl.lineWidth(width);
      currentLineWidth = width;
    }
  }
  function setPolygonOffset(polygonOffset, factor, units) {
    if (polygonOffset) {
      enable(gl.POLYGON_OFFSET_FILL);
      if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
        gl.polygonOffset(factor, units);
        currentPolygonOffsetFactor = factor;
        currentPolygonOffsetUnits = units;
      }
    } else {
      disable(gl.POLYGON_OFFSET_FILL);
    }
  }
  function setScissorTest(scissorTest) {
    if (scissorTest) {
      enable(gl.SCISSOR_TEST);
    } else {
      disable(gl.SCISSOR_TEST);
    }
  }
  function activeTexture(webglSlot) {
    if (webglSlot === void 0) webglSlot = gl.TEXTURE0 + maxTextures - 1;
    if (currentTextureSlot !== webglSlot) {
      gl.activeTexture(webglSlot);
      currentTextureSlot = webglSlot;
    }
  }
  function bindTexture(webglType, webglTexture, webglSlot) {
    if (webglSlot === void 0) {
      if (currentTextureSlot === null) {
        webglSlot = gl.TEXTURE0 + maxTextures - 1;
      } else {
        webglSlot = currentTextureSlot;
      }
    }
    let boundTexture = currentBoundTextures[webglSlot];
    if (boundTexture === void 0) {
      boundTexture = { type: void 0, texture: void 0 };
      currentBoundTextures[webglSlot] = boundTexture;
    }
    if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
      if (currentTextureSlot !== webglSlot) {
        gl.activeTexture(webglSlot);
        currentTextureSlot = webglSlot;
      }
      gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
      boundTexture.type = webglType;
      boundTexture.texture = webglTexture;
    }
  }
  function unbindTexture() {
    const boundTexture = currentBoundTextures[currentTextureSlot];
    if (boundTexture !== void 0 && boundTexture.type !== void 0) {
      gl.bindTexture(boundTexture.type, null);
      boundTexture.type = void 0;
      boundTexture.texture = void 0;
    }
  }
  function compressedTexImage2D() {
    try {
      gl.compressedTexImage2D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function compressedTexImage3D() {
    try {
      gl.compressedTexImage3D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texSubImage2D() {
    try {
      gl.texSubImage2D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texSubImage3D() {
    try {
      gl.texSubImage3D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function compressedTexSubImage2D() {
    try {
      gl.compressedTexSubImage2D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function compressedTexSubImage3D() {
    try {
      gl.compressedTexSubImage3D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texStorage2D() {
    try {
      gl.texStorage2D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texStorage3D() {
    try {
      gl.texStorage3D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texImage2D() {
    try {
      gl.texImage2D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function texImage3D() {
    try {
      gl.texImage3D.apply(gl, arguments);
    } catch (error2) {
      console.error("THREE.WebGLState:", error2);
    }
  }
  function scissor(scissor2) {
    if (currentScissor.equals(scissor2) === false) {
      gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w);
      currentScissor.copy(scissor2);
    }
  }
  function viewport(viewport2) {
    if (currentViewport.equals(viewport2) === false) {
      gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w);
      currentViewport.copy(viewport2);
    }
  }
  function updateUBOMapping(uniformsGroup, program) {
    let mapping = uboProgramMap.get(program);
    if (mapping === void 0) {
      mapping = /* @__PURE__ */ new WeakMap();
      uboProgramMap.set(program, mapping);
    }
    let blockIndex = mapping.get(uniformsGroup);
    if (blockIndex === void 0) {
      blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
      mapping.set(uniformsGroup, blockIndex);
    }
  }
  function uniformBlockBinding(uniformsGroup, program) {
    const mapping = uboProgramMap.get(program);
    const blockIndex = mapping.get(uniformsGroup);
    if (uboBindings.get(program) !== blockIndex) {
      gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
      uboBindings.set(program, blockIndex);
    }
  }
  function reset() {
    gl.disable(gl.BLEND);
    gl.disable(gl.CULL_FACE);
    gl.disable(gl.DEPTH_TEST);
    gl.disable(gl.POLYGON_OFFSET_FILL);
    gl.disable(gl.SCISSOR_TEST);
    gl.disable(gl.STENCIL_TEST);
    gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
    gl.blendEquation(gl.FUNC_ADD);
    gl.blendFunc(gl.ONE, gl.ZERO);
    gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
    gl.blendColor(0, 0, 0, 0);
    gl.colorMask(true, true, true, true);
    gl.clearColor(0, 0, 0, 0);
    gl.depthMask(true);
    gl.depthFunc(gl.LESS);
    depthBuffer.setReversed(false);
    gl.clearDepth(1);
    gl.stencilMask(4294967295);
    gl.stencilFunc(gl.ALWAYS, 0, 4294967295);
    gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
    gl.clearStencil(0);
    gl.cullFace(gl.BACK);
    gl.frontFace(gl.CCW);
    gl.polygonOffset(0, 0);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
    gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
    gl.useProgram(null);
    gl.lineWidth(1);
    gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    enabledCapabilities = {};
    currentTextureSlot = null;
    currentBoundTextures = {};
    currentBoundFramebuffers = {};
    currentDrawbuffers = /* @__PURE__ */ new WeakMap();
    defaultDrawbuffers = [];
    currentProgram = null;
    currentBlendingEnabled = false;
    currentBlending = null;
    currentBlendEquation = null;
    currentBlendSrc = null;
    currentBlendDst = null;
    currentBlendEquationAlpha = null;
    currentBlendSrcAlpha = null;
    currentBlendDstAlpha = null;
    currentBlendColor = new Color(0, 0, 0);
    currentBlendAlpha = 0;
    currentPremultipledAlpha = false;
    currentFlipSided = null;
    currentCullFace = null;
    currentLineWidth = null;
    currentPolygonOffsetFactor = null;
    currentPolygonOffsetUnits = null;
    currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
    currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
    colorBuffer.reset();
    depthBuffer.reset();
    stencilBuffer.reset();
  }
  return {
    buffers: {
      color: colorBuffer,
      depth: depthBuffer,
      stencil: stencilBuffer
    },
    enable,
    disable,
    bindFramebuffer,
    drawBuffers,
    useProgram,
    setBlending,
    setMaterial,
    setFlipSided,
    setCullFace,
    setLineWidth,
    setPolygonOffset,
    setScissorTest,
    activeTexture,
    bindTexture,
    unbindTexture,
    compressedTexImage2D,
    compressedTexImage3D,
    texImage2D,
    texImage3D,
    updateUBOMapping,
    uniformBlockBinding,
    texStorage2D,
    texStorage3D,
    texSubImage2D,
    texSubImage3D,
    compressedTexSubImage2D,
    compressedTexSubImage3D,
    scissor,
    viewport,
    reset
  };
}
function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null;
  const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent);
  const _imageDimensions = new Vector2();
  const _videoTextures = /* @__PURE__ */ new WeakMap();
  let _canvas2;
  const _sources = /* @__PURE__ */ new WeakMap();
  let useOffscreenCanvas = false;
  try {
    useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  } catch (err) {
  }
  function createCanvas(width, height) {
    return useOffscreenCanvas ? (
      // eslint-disable-next-line compat/compat
      new OffscreenCanvas(width, height)
    ) : createElementNS("canvas");
  }
  function resizeImage(image, needsNewCanvas, maxSize) {
    let scale = 1;
    const dimensions = getDimensions(image);
    if (dimensions.width > maxSize || dimensions.height > maxSize) {
      scale = maxSize / Math.max(dimensions.width, dimensions.height);
    }
    if (scale < 1) {
      if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) {
        const width = Math.floor(scale * dimensions.width);
        const height = Math.floor(scale * dimensions.height);
        if (_canvas2 === void 0) _canvas2 = createCanvas(width, height);
        const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas2;
        canvas.width = width;
        canvas.height = height;
        const context2 = canvas.getContext("2d");
        context2.drawImage(image, 0, 0, width, height);
        console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width + "x" + height + ").");
        return canvas;
      } else {
        if ("data" in image) {
          console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ").");
        }
        return image;
      }
    }
    return image;
  }
  function textureNeedsGenerateMipmaps(texture) {
    return texture.generateMipmaps;
  }
  function generateMipmap(target) {
    _gl.generateMipmap(target);
  }
  function getTargetType(texture) {
    if (texture.isWebGLCubeRenderTarget) return _gl.TEXTURE_CUBE_MAP;
    if (texture.isWebGL3DRenderTarget) return _gl.TEXTURE_3D;
    if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) return _gl.TEXTURE_2D_ARRAY;
    return _gl.TEXTURE_2D;
  }
  function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) {
    if (internalFormatName !== null) {
      if (_gl[internalFormatName] !== void 0) return _gl[internalFormatName];
      console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'");
    }
    let internalFormat = glFormat;
    if (glFormat === _gl.RED) {
      if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
      if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
    }
    if (glFormat === _gl.RED_INTEGER) {
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8UI;
      if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.R16UI;
      if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.R32UI;
      if (glType === _gl.BYTE) internalFormat = _gl.R8I;
      if (glType === _gl.SHORT) internalFormat = _gl.R16I;
      if (glType === _gl.INT) internalFormat = _gl.R32I;
    }
    if (glFormat === _gl.RG) {
      if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
      if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
    }
    if (glFormat === _gl.RG_INTEGER) {
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8UI;
      if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RG16UI;
      if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RG32UI;
      if (glType === _gl.BYTE) internalFormat = _gl.RG8I;
      if (glType === _gl.SHORT) internalFormat = _gl.RG16I;
      if (glType === _gl.INT) internalFormat = _gl.RG32I;
    }
    if (glFormat === _gl.RGB_INTEGER) {
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8UI;
      if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGB16UI;
      if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGB32UI;
      if (glType === _gl.BYTE) internalFormat = _gl.RGB8I;
      if (glType === _gl.SHORT) internalFormat = _gl.RGB16I;
      if (glType === _gl.INT) internalFormat = _gl.RGB32I;
    }
    if (glFormat === _gl.RGBA_INTEGER) {
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8UI;
      if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGBA16UI;
      if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGBA32UI;
      if (glType === _gl.BYTE) internalFormat = _gl.RGBA8I;
      if (glType === _gl.SHORT) internalFormat = _gl.RGBA16I;
      if (glType === _gl.INT) internalFormat = _gl.RGBA32I;
    }
    if (glFormat === _gl.RGB) {
      if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) internalFormat = _gl.RGB9_E5;
    }
    if (glFormat === _gl.RGBA) {
      const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace);
      if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
      if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
      if (glType === _gl.UNSIGNED_BYTE) internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
      if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
      if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
    }
    if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
      extensions.get("EXT_color_buffer_float");
    }
    return internalFormat;
  }
  function getInternalDepthFormat(useStencil, depthType) {
    let glInternalFormat;
    if (useStencil) {
      if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) {
        glInternalFormat = _gl.DEPTH24_STENCIL8;
      } else if (depthType === FloatType) {
        glInternalFormat = _gl.DEPTH32F_STENCIL8;
      } else if (depthType === UnsignedShortType) {
        glInternalFormat = _gl.DEPTH24_STENCIL8;
        console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.");
      }
    } else {
      if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) {
        glInternalFormat = _gl.DEPTH_COMPONENT24;
      } else if (depthType === FloatType) {
        glInternalFormat = _gl.DEPTH_COMPONENT32F;
      } else if (depthType === UnsignedShortType) {
        glInternalFormat = _gl.DEPTH_COMPONENT16;
      }
    }
    return glInternalFormat;
  }
  function getMipLevels(texture, image) {
    if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
      return Math.log2(Math.max(image.width, image.height)) + 1;
    } else if (texture.mipmaps !== void 0 && texture.mipmaps.length > 0) {
      return texture.mipmaps.length;
    } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
      return image.mipmaps.length;
    } else {
      return 1;
    }
  }
  function onTextureDispose(event) {
    const texture = event.target;
    texture.removeEventListener("dispose", onTextureDispose);
    deallocateTexture(texture);
    if (texture.isVideoTexture) {
      _videoTextures.delete(texture);
    }
  }
  function onRenderTargetDispose(event) {
    const renderTarget = event.target;
    renderTarget.removeEventListener("dispose", onRenderTargetDispose);
    deallocateRenderTarget(renderTarget);
  }
  function deallocateTexture(texture) {
    const textureProperties = properties.get(texture);
    if (textureProperties.__webglInit === void 0) return;
    const source = texture.source;
    const webglTextures = _sources.get(source);
    if (webglTextures) {
      const webglTexture = webglTextures[textureProperties.__cacheKey];
      webglTexture.usedTimes--;
      if (webglTexture.usedTimes === 0) {
        deleteTexture(texture);
      }
      if (Object.keys(webglTextures).length === 0) {
        _sources.delete(source);
      }
    }
    properties.remove(texture);
  }
  function deleteTexture(texture) {
    const textureProperties = properties.get(texture);
    _gl.deleteTexture(textureProperties.__webglTexture);
    const source = texture.source;
    const webglTextures = _sources.get(source);
    delete webglTextures[textureProperties.__cacheKey];
    info.memory.textures--;
  }
  function deallocateRenderTarget(renderTarget) {
    const renderTargetProperties = properties.get(renderTarget);
    if (renderTarget.depthTexture) {
      renderTarget.depthTexture.dispose();
      properties.remove(renderTarget.depthTexture);
    }
    if (renderTarget.isWebGLCubeRenderTarget) {
      for (let i2 = 0; i2 < 6; i2++) {
        if (Array.isArray(renderTargetProperties.__webglFramebuffer[i2])) {
          for (let level = 0; level < renderTargetProperties.__webglFramebuffer[i2].length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i2][level]);
        } else {
          _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i2]);
        }
        if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i2]);
      }
    } else {
      if (Array.isArray(renderTargetProperties.__webglFramebuffer)) {
        for (let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]);
      } else {
        _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
      }
      if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
      if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
      if (renderTargetProperties.__webglColorRenderbuffer) {
        for (let i2 = 0; i2 < renderTargetProperties.__webglColorRenderbuffer.length; i2++) {
          if (renderTargetProperties.__webglColorRenderbuffer[i2]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i2]);
        }
      }
      if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
    }
    const textures = renderTarget.textures;
    for (let i2 = 0, il = textures.length; i2 < il; i2++) {
      const attachmentProperties = properties.get(textures[i2]);
      if (attachmentProperties.__webglTexture) {
        _gl.deleteTexture(attachmentProperties.__webglTexture);
        info.memory.textures--;
      }
      properties.remove(textures[i2]);
    }
    properties.remove(renderTarget);
  }
  let textureUnits = 0;
  function resetTextureUnits() {
    textureUnits = 0;
  }
  function allocateTextureUnit() {
    const textureUnit = textureUnits;
    if (textureUnit >= capabilities.maxTextures) {
      console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures);
    }
    textureUnits += 1;
    return textureUnit;
  }
  function getTextureCacheKey(texture) {
    const array = [];
    array.push(texture.wrapS);
    array.push(texture.wrapT);
    array.push(texture.wrapR || 0);
    array.push(texture.magFilter);
    array.push(texture.minFilter);
    array.push(texture.anisotropy);
    array.push(texture.internalFormat);
    array.push(texture.format);
    array.push(texture.type);
    array.push(texture.generateMipmaps);
    array.push(texture.premultiplyAlpha);
    array.push(texture.flipY);
    array.push(texture.unpackAlignment);
    array.push(texture.colorSpace);
    return array.join();
  }
  function setTexture2D(texture, slot) {
    const textureProperties = properties.get(texture);
    if (texture.isVideoTexture) updateVideoTexture(texture);
    if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
      const image = texture.image;
      if (image === null) {
        console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");
      } else if (image.complete === false) {
        console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");
      } else {
        uploadTexture(textureProperties, texture, slot);
        return;
      }
    }
    state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  }
  function setTexture2DArray(texture, slot) {
    const textureProperties = properties.get(texture);
    if (texture.version > 0 && textureProperties.__version !== texture.version) {
      uploadTexture(textureProperties, texture, slot);
      return;
    }
    state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  }
  function setTexture3D(texture, slot) {
    const textureProperties = properties.get(texture);
    if (texture.version > 0 && textureProperties.__version !== texture.version) {
      uploadTexture(textureProperties, texture, slot);
      return;
    }
    state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  }
  function setTextureCube(texture, slot) {
    const textureProperties = properties.get(texture);
    if (texture.version > 0 && textureProperties.__version !== texture.version) {
      uploadCubeTexture(textureProperties, texture, slot);
      return;
    }
    state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  }
  const wrappingToGL = {
    [RepeatWrapping]: _gl.REPEAT,
    [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
    [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  };
  const filterToGL = {
    [NearestFilter]: _gl.NEAREST,
    [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
    [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
    [LinearFilter]: _gl.LINEAR,
    [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
    [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  };
  const compareToGL = {
    [NeverCompare]: _gl.NEVER,
    [AlwaysCompare]: _gl.ALWAYS,
    [LessCompare]: _gl.LESS,
    [LessEqualCompare]: _gl.LEQUAL,
    [EqualCompare]: _gl.EQUAL,
    [GreaterEqualCompare]: _gl.GEQUAL,
    [GreaterCompare]: _gl.GREATER,
    [NotEqualCompare]: _gl.NOTEQUAL
  };
  function setTextureParameters(textureType, texture) {
    if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) {
      console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");
    }
    _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
    _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
    if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
      _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
    }
    _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
    _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
    if (texture.compareFunction) {
      _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE);
      _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]);
    }
    if (extensions.has("EXT_texture_filter_anisotropic") === true) {
      if (texture.magFilter === NearestFilter) return;
      if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) return;
      if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) return;
      if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
        const extension = extensions.get("EXT_texture_filter_anisotropic");
        _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
        properties.get(texture).__currentAnisotropy = texture.anisotropy;
      }
    }
  }
  function initTexture(textureProperties, texture) {
    let forceUpload = false;
    if (textureProperties.__webglInit === void 0) {
      textureProperties.__webglInit = true;
      texture.addEventListener("dispose", onTextureDispose);
    }
    const source = texture.source;
    let webglTextures = _sources.get(source);
    if (webglTextures === void 0) {
      webglTextures = {};
      _sources.set(source, webglTextures);
    }
    const textureCacheKey = getTextureCacheKey(texture);
    if (textureCacheKey !== textureProperties.__cacheKey) {
      if (webglTextures[textureCacheKey] === void 0) {
        webglTextures[textureCacheKey] = {
          texture: _gl.createTexture(),
          usedTimes: 0
        };
        info.memory.textures++;
        forceUpload = true;
      }
      webglTextures[textureCacheKey].usedTimes++;
      const webglTexture = webglTextures[textureProperties.__cacheKey];
      if (webglTexture !== void 0) {
        webglTextures[textureProperties.__cacheKey].usedTimes--;
        if (webglTexture.usedTimes === 0) {
          deleteTexture(texture);
        }
      }
      textureProperties.__cacheKey = textureCacheKey;
      textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
    }
    return forceUpload;
  }
  function uploadTexture(textureProperties, texture, slot) {
    let textureType = _gl.TEXTURE_2D;
    if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
    if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
    const forceUpload = initTexture(textureProperties, texture);
    const source = texture.source;
    state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
    const sourceProperties = properties.get(source);
    if (source.version !== sourceProperties.__version || forceUpload === true) {
      state.activeTexture(_gl.TEXTURE0 + slot);
      const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace);
      const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace);
      const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
      _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
      _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
      _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
      _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion);
      let image = resizeImage(texture.image, false, capabilities.maxTextureSize);
      image = verifyColorSpace(texture, image);
      const glFormat = utils.convert(texture.format, texture.colorSpace);
      const glType = utils.convert(texture.type);
      let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture);
      setTextureParameters(textureType, texture);
      let mipmap;
      const mipmaps = texture.mipmaps;
      const useTexStorage = texture.isVideoTexture !== true;
      const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true;
      const dataReady = source.dataReady;
      const levels = getMipLevels(texture, image);
      if (texture.isDepthTexture) {
        glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type);
        if (allocateMemory) {
          if (useTexStorage) {
            state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
          } else {
            state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
          }
        }
      } else if (texture.isDataTexture) {
        if (mipmaps.length > 0) {
          if (useTexStorage && allocateMemory) {
            state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
          }
          for (let i2 = 0, il = mipmaps.length; i2 < il; i2++) {
            mipmap = mipmaps[i2];
            if (useTexStorage) {
              if (dataReady) {
                state.texSubImage2D(_gl.TEXTURE_2D, i2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
              }
            } else {
              state.texImage2D(_gl.TEXTURE_2D, i2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
            }
          }
          texture.generateMipmaps = false;
        } else {
          if (useTexStorage) {
            if (allocateMemory) {
              state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
            }
            if (dataReady) {
              state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
            }
          } else {
            state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
          }
        }
      } else if (texture.isCompressedTexture) {
        if (texture.isCompressedArrayTexture) {
          if (useTexStorage && allocateMemory) {
            state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth);
          }
          for (let i2 = 0, il = mipmaps.length; i2 < il; i2++) {
            mipmap = mipmaps[i2];
            if (texture.format !== RGBAFormat) {
              if (glFormat !== null) {
                if (useTexStorage) {
                  if (dataReady) {
                    if (texture.layerUpdates.size > 0) {
                      const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type);
                      for (const layerIndex of texture.layerUpdates) {
                        const layerData = mipmap.data.subarray(
                          layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
                          (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
                        );
                        state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i2, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData);
                      }
                      texture.clearLayerUpdates();
                    } else {
                      state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i2, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data);
                    }
                  }
                } else {
                  state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i2, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0);
                }
              } else {
                console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
              }
            } else {
              if (useTexStorage) {
                if (dataReady) {
                  state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i2, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data);
                }
              } else {
                state.texImage3D(_gl.TEXTURE_2D_ARRAY, i2, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data);
              }
            }
          }
        } else {
          if (useTexStorage && allocateMemory) {
            state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
          }
          for (let i2 = 0, il = mipmaps.length; i2 < il; i2++) {
            mipmap = mipmaps[i2];
            if (texture.format !== RGBAFormat) {
              if (glFormat !== null) {
                if (useTexStorage) {
                  if (dataReady) {
                    state.compressedTexSubImage2D(_gl.TEXTURE_2D, i2, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
                  }
                } else {
                  state.compressedTexImage2D(_gl.TEXTURE_2D, i2, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
                }
              } else {
                console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
              }
            } else {
              if (useTexStorage) {
                if (dataReady) {
                  state.texSubImage2D(_gl.TEXTURE_2D, i2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
                }
              } else {
                state.texImage2D(_gl.TEXTURE_2D, i2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
              }
            }
          }
        }
      } else if (texture.isDataArrayTexture) {
        if (useTexStorage) {
          if (allocateMemory) {
            state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
          }
          if (dataReady) {
            if (texture.layerUpdates.size > 0) {
              const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type);
              for (const layerIndex of texture.layerUpdates) {
                const layerData = image.data.subarray(
                  layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
                  (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT
                );
                state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData);
              }
              texture.clearLayerUpdates();
            } else {
              state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
            }
          }
        } else {
          state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
        }
      } else if (texture.isData3DTexture) {
        if (useTexStorage) {
          if (allocateMemory) {
            state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
          }
          if (dataReady) {
            state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
          }
        } else {
          state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
        }
      } else if (texture.isFramebufferTexture) {
        if (allocateMemory) {
          if (useTexStorage) {
            state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
          } else {
            let width = image.width, height = image.height;
            for (let i2 = 0; i2 < levels; i2++) {
              state.texImage2D(_gl.TEXTURE_2D, i2, glInternalFormat, width, height, 0, glFormat, glType, null);
              width >>= 1;
              height >>= 1;
            }
          }
        }
      } else {
        if (mipmaps.length > 0) {
          if (useTexStorage && allocateMemory) {
            const dimensions = getDimensions(mipmaps[0]);
            state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height);
          }
          for (let i2 = 0, il = mipmaps.length; i2 < il; i2++) {
            mipmap = mipmaps[i2];
            if (useTexStorage) {
              if (dataReady) {
                state.texSubImage2D(_gl.TEXTURE_2D, i2, 0, 0, glFormat, glType, mipmap);
              }
            } else {
              state.texImage2D(_gl.TEXTURE_2D, i2, glInternalFormat, glFormat, glType, mipmap);
            }
          }
          texture.generateMipmaps = false;
        } else {
          if (useTexStorage) {
            if (allocateMemory) {
              const dimensions = getDimensions(image);
              state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height);
            }
            if (dataReady) {
              state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
            }
          } else {
            state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
          }
        }
      }
      if (textureNeedsGenerateMipmaps(texture)) {
        generateMipmap(textureType);
      }
      sourceProperties.__version = source.version;
      if (texture.onUpdate) texture.onUpdate(texture);
    }
    textureProperties.__version = texture.version;
  }
  function uploadCubeTexture(textureProperties, texture, slot) {
    if (texture.image.length !== 6) return;
    const forceUpload = initTexture(textureProperties, texture);
    const source = texture.source;
    state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
    const sourceProperties = properties.get(source);
    if (source.version !== sourceProperties.__version || forceUpload === true) {
      state.activeTexture(_gl.TEXTURE0 + slot);
      const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace);
      const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace);
      const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
      _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
      _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
      _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
      _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion);
      const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
      const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
      const cubeImage = [];
      for (let i2 = 0; i2 < 6; i2++) {
        if (!isCompressed && !isDataTexture) {
          cubeImage[i2] = resizeImage(texture.image[i2], true, capabilities.maxCubemapSize);
        } else {
          cubeImage[i2] = isDataTexture ? texture.image[i2].image : texture.image[i2];
        }
        cubeImage[i2] = verifyColorSpace(texture, cubeImage[i2]);
      }
      const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace);
      const useTexStorage = texture.isVideoTexture !== true;
      const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true;
      const dataReady = source.dataReady;
      let levels = getMipLevels(texture, image);
      setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture);
      let mipmaps;
      if (isCompressed) {
        if (useTexStorage && allocateMemory) {
          state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
        }
        for (let i2 = 0; i2 < 6; i2++) {
          mipmaps = cubeImage[i2].mipmaps;
          for (let j2 = 0; j2 < mipmaps.length; j2++) {
            const mipmap = mipmaps[j2];
            if (texture.format !== RGBAFormat) {
              if (glFormat !== null) {
                if (useTexStorage) {
                  if (dataReady) {
                    state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
                  }
                } else {
                  state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
                }
              } else {
                console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");
              }
            } else {
              if (useTexStorage) {
                if (dataReady) {
                  state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
                }
              } else {
                state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
              }
            }
          }
        }
      } else {
        mipmaps = texture.mipmaps;
        if (useTexStorage && allocateMemory) {
          if (mipmaps.length > 0) levels++;
          const dimensions = getDimensions(cubeImage[0]);
          state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height);
        }
        for (let i2 = 0; i2 < 6; i2++) {
          if (isDataTexture) {
            if (useTexStorage) {
              if (dataReady) {
                state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, 0, 0, cubeImage[i2].width, cubeImage[i2].height, glFormat, glType, cubeImage[i2].data);
              }
            } else {
              state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, glInternalFormat, cubeImage[i2].width, cubeImage[i2].height, 0, glFormat, glType, cubeImage[i2].data);
            }
            for (let j2 = 0; j2 < mipmaps.length; j2++) {
              const mipmap = mipmaps[j2];
              const mipmapImage = mipmap.image[i2].image;
              if (useTexStorage) {
                if (dataReady) {
                  state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2 + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
                }
              } else {
                state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2 + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
              }
            }
          } else {
            if (useTexStorage) {
              if (dataReady) {
                state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, 0, 0, glFormat, glType, cubeImage[i2]);
              }
            } else {
              state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, glInternalFormat, glFormat, glType, cubeImage[i2]);
            }
            for (let j2 = 0; j2 < mipmaps.length; j2++) {
              const mipmap = mipmaps[j2];
              if (useTexStorage) {
                if (dataReady) {
                  state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2 + 1, 0, 0, glFormat, glType, mipmap.image[i2]);
                }
              } else {
                state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, j2 + 1, glInternalFormat, glFormat, glType, mipmap.image[i2]);
              }
            }
          }
        }
      }
      if (textureNeedsGenerateMipmaps(texture)) {
        generateMipmap(_gl.TEXTURE_CUBE_MAP);
      }
      sourceProperties.__version = source.version;
      if (texture.onUpdate) texture.onUpdate(texture);
    }
    textureProperties.__version = texture.version;
  }
  function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) {
    const glFormat = utils.convert(texture.format, texture.colorSpace);
    const glType = utils.convert(texture.type);
    const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace);
    const renderTargetProperties = properties.get(renderTarget);
    const textureProperties = properties.get(texture);
    textureProperties.__renderTarget = renderTarget;
    if (!renderTargetProperties.__hasExternalTextures) {
      const width = Math.max(1, renderTarget.width >> level);
      const height = Math.max(1, renderTarget.height >> level);
      if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
        state.texImage3D(textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null);
      } else {
        state.texImage2D(textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null);
      }
    }
    state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
    if (useMultisampledRTT(renderTarget)) {
      multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget));
    } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) {
      _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level);
    }
    state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  }
  function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
    _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
    if (renderTarget.depthBuffer) {
      const depthTexture = renderTarget.depthTexture;
      const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
      const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType);
      const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
      const samples = getRenderTargetSamples(renderTarget);
      const isUseMultisampledRTT = useMultisampledRTT(renderTarget);
      if (isUseMultisampledRTT) {
        multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
      } else if (isMultisample) {
        _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
      } else {
        _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
      }
      _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer);
    } else {
      const textures = renderTarget.textures;
      for (let i2 = 0; i2 < textures.length; i2++) {
        const texture = textures[i2];
        const glFormat = utils.convert(texture.format, texture.colorSpace);
        const glType = utils.convert(texture.type);
        const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace);
        const samples = getRenderTargetSamples(renderTarget);
        if (isMultisample && useMultisampledRTT(renderTarget) === false) {
          _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
        } else if (useMultisampledRTT(renderTarget)) {
          multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
        } else {
          _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
        }
      }
    }
    _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  }
  function setupDepthTexture(framebuffer, renderTarget) {
    const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
    if (isCube) throw new Error("Depth Texture with cube render targets is not supported");
    state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
    if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
      throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");
    }
    const textureProperties = properties.get(renderTarget.depthTexture);
    textureProperties.__renderTarget = renderTarget;
    if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
      renderTarget.depthTexture.image.width = renderTarget.width;
      renderTarget.depthTexture.image.height = renderTarget.height;
      renderTarget.depthTexture.needsUpdate = true;
    }
    setTexture2D(renderTarget.depthTexture, 0);
    const webglDepthTexture = textureProperties.__webglTexture;
    const samples = getRenderTargetSamples(renderTarget);
    if (renderTarget.depthTexture.format === DepthFormat) {
      if (useMultisampledRTT(renderTarget)) {
        multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
      } else {
        _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
      }
    } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
      if (useMultisampledRTT(renderTarget)) {
        multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
      } else {
        _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
      }
    } else {
      throw new Error("Unknown depthTexture format");
    }
  }
  function setupDepthRenderbuffer(renderTarget) {
    const renderTargetProperties = properties.get(renderTarget);
    const isCube = renderTarget.isWebGLCubeRenderTarget === true;
    if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) {
      const depthTexture = renderTarget.depthTexture;
      if (renderTargetProperties.__depthDisposeCallback) {
        renderTargetProperties.__depthDisposeCallback();
      }
      if (depthTexture) {
        const disposeEvent = () => {
          delete renderTargetProperties.__boundDepthTexture;
          delete renderTargetProperties.__depthDisposeCallback;
          depthTexture.removeEventListener("dispose", disposeEvent);
        };
        depthTexture.addEventListener("dispose", disposeEvent);
        renderTargetProperties.__depthDisposeCallback = disposeEvent;
      }
      renderTargetProperties.__boundDepthTexture = depthTexture;
    }
    if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
      if (isCube) throw new Error("target.depthTexture not supported in Cube render targets");
      setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
    } else {
      if (isCube) {
        renderTargetProperties.__webglDepthbuffer = [];
        for (let i2 = 0; i2 < 6; i2++) {
          state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i2]);
          if (renderTargetProperties.__webglDepthbuffer[i2] === void 0) {
            renderTargetProperties.__webglDepthbuffer[i2] = _gl.createRenderbuffer();
            setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i2], renderTarget, false);
          } else {
            const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
            const renderbuffer = renderTargetProperties.__webglDepthbuffer[i2];
            _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
            _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer);
          }
        }
      } else {
        state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
        if (renderTargetProperties.__webglDepthbuffer === void 0) {
          renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
          setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
        } else {
          const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
          const renderbuffer = renderTargetProperties.__webglDepthbuffer;
          _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
          _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer);
        }
      }
    }
    state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  }
  function rebindTextures(renderTarget, colorTexture, depthTexture) {
    const renderTargetProperties = properties.get(renderTarget);
    if (colorTexture !== void 0) {
      setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0);
    }
    if (depthTexture !== void 0) {
      setupDepthRenderbuffer(renderTarget);
    }
  }
  function setupRenderTarget(renderTarget) {
    const texture = renderTarget.texture;
    const renderTargetProperties = properties.get(renderTarget);
    const textureProperties = properties.get(texture);
    renderTarget.addEventListener("dispose", onRenderTargetDispose);
    const textures = renderTarget.textures;
    const isCube = renderTarget.isWebGLCubeRenderTarget === true;
    const isMultipleRenderTargets = textures.length > 1;
    if (!isMultipleRenderTargets) {
      if (textureProperties.__webglTexture === void 0) {
        textureProperties.__webglTexture = _gl.createTexture();
      }
      textureProperties.__version = texture.version;
      info.memory.textures++;
    }
    if (isCube) {
      renderTargetProperties.__webglFramebuffer = [];
      for (let i2 = 0; i2 < 6; i2++) {
        if (texture.mipmaps && texture.mipmaps.length > 0) {
          renderTargetProperties.__webglFramebuffer[i2] = [];
          for (let level = 0; level < texture.mipmaps.length; level++) {
            renderTargetProperties.__webglFramebuffer[i2][level] = _gl.createFramebuffer();
          }
        } else {
          renderTargetProperties.__webglFramebuffer[i2] = _gl.createFramebuffer();
        }
      }
    } else {
      if (texture.mipmaps && texture.mipmaps.length > 0) {
        renderTargetProperties.__webglFramebuffer = [];
        for (let level = 0; level < texture.mipmaps.length; level++) {
          renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer();
        }
      } else {
        renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
      }
      if (isMultipleRenderTargets) {
        for (let i2 = 0, il = textures.length; i2 < il; i2++) {
          const attachmentProperties = properties.get(textures[i2]);
          if (attachmentProperties.__webglTexture === void 0) {
            attachmentProperties.__webglTexture = _gl.createTexture();
            info.memory.textures++;
          }
        }
      }
      if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
        renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
        renderTargetProperties.__webglColorRenderbuffer = [];
        state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
        for (let i2 = 0; i2 < textures.length; i2++) {
          const texture2 = textures[i2];
          renderTargetProperties.__webglColorRenderbuffer[i2] = _gl.createRenderbuffer();
          _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i2]);
          const glFormat = utils.convert(texture2.format, texture2.colorSpace);
          const glType = utils.convert(texture2.type);
          const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true);
          const samples = getRenderTargetSamples(renderTarget);
          _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
          _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i2, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i2]);
        }
        _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
        if (renderTarget.depthBuffer) {
          renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
          setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
        }
        state.bindFramebuffer(_gl.FRAMEBUFFER, null);
      }
    }
    if (isCube) {
      state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
      setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture);
      for (let i2 = 0; i2 < 6; i2++) {
        if (texture.mipmaps && texture.mipmaps.length > 0) {
          for (let level = 0; level < texture.mipmaps.length; level++) {
            setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i2][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, level);
          }
        } else {
          setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i2], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0);
        }
      }
      if (textureNeedsGenerateMipmaps(texture)) {
        generateMipmap(_gl.TEXTURE_CUBE_MAP);
      }
      state.unbindTexture();
    } else if (isMultipleRenderTargets) {
      for (let i2 = 0, il = textures.length; i2 < il; i2++) {
        const attachment = textures[i2];
        const attachmentProperties = properties.get(attachment);
        state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
        setTextureParameters(_gl.TEXTURE_2D, attachment);
        setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i2, _gl.TEXTURE_2D, 0);
        if (textureNeedsGenerateMipmaps(attachment)) {
          generateMipmap(_gl.TEXTURE_2D);
        }
      }
      state.unbindTexture();
    } else {
      let glTextureType = _gl.TEXTURE_2D;
      if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
        glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
      }
      state.bindTexture(glTextureType, textureProperties.__webglTexture);
      setTextureParameters(glTextureType, texture);
      if (texture.mipmaps && texture.mipmaps.length > 0) {
        for (let level = 0; level < texture.mipmaps.length; level++) {
          setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level);
        }
      } else {
        setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0);
      }
      if (textureNeedsGenerateMipmaps(texture)) {
        generateMipmap(glTextureType);
      }
      state.unbindTexture();
    }
    if (renderTarget.depthBuffer) {
      setupDepthRenderbuffer(renderTarget);
    }
  }
  function updateRenderTargetMipmap(renderTarget) {
    const textures = renderTarget.textures;
    for (let i2 = 0, il = textures.length; i2 < il; i2++) {
      const texture = textures[i2];
      if (textureNeedsGenerateMipmaps(texture)) {
        const targetType = getTargetType(renderTarget);
        const webglTexture = properties.get(texture).__webglTexture;
        state.bindTexture(targetType, webglTexture);
        generateMipmap(targetType);
        state.unbindTexture();
      }
    }
  }
  const invalidationArrayRead = [];
  const invalidationArrayDraw = [];
  function updateMultisampleRenderTarget(renderTarget) {
    if (renderTarget.samples > 0) {
      if (useMultisampledRTT(renderTarget) === false) {
        const textures = renderTarget.textures;
        const width = renderTarget.width;
        const height = renderTarget.height;
        let mask = _gl.COLOR_BUFFER_BIT;
        const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
        const renderTargetProperties = properties.get(renderTarget);
        const isMultipleRenderTargets = textures.length > 1;
        if (isMultipleRenderTargets) {
          for (let i2 = 0; i2 < textures.length; i2++) {
            state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
            _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i2, _gl.RENDERBUFFER, null);
            state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
            _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i2, _gl.TEXTURE_2D, null, 0);
          }
        }
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
        for (let i2 = 0; i2 < textures.length; i2++) {
          if (renderTarget.resolveDepthBuffer) {
            if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
            if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
          }
          if (isMultipleRenderTargets) {
            _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i2]);
            const webglTexture = properties.get(textures[i2]).__webglTexture;
            _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
          }
          _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
          if (supportsInvalidateFramebuffer === true) {
            invalidationArrayRead.length = 0;
            invalidationArrayDraw.length = 0;
            invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i2);
            if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) {
              invalidationArrayRead.push(depthStyle);
              invalidationArrayDraw.push(depthStyle);
              _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw);
            }
            _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead);
          }
        }
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null);
        if (isMultipleRenderTargets) {
          for (let i2 = 0; i2 < textures.length; i2++) {
            state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
            _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i2, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i2]);
            const webglTexture = properties.get(textures[i2]).__webglTexture;
            state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
            _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i2, _gl.TEXTURE_2D, webglTexture, 0);
          }
        }
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
      } else {
        if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) {
          const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
          _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
        }
      }
    }
  }
  function getRenderTargetSamples(renderTarget) {
    return Math.min(capabilities.maxSamples, renderTarget.samples);
  }
  function useMultisampledRTT(renderTarget) {
    const renderTargetProperties = properties.get(renderTarget);
    return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false;
  }
  function updateVideoTexture(texture) {
    const frame = info.render.frame;
    if (_videoTextures.get(texture) !== frame) {
      _videoTextures.set(texture, frame);
      texture.update();
    }
  }
  function verifyColorSpace(texture, image) {
    const colorSpace = texture.colorSpace;
    const format = texture.format;
    const type = texture.type;
    if (texture.isCompressedTexture === true || texture.isVideoTexture === true) return image;
    if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) {
      if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) {
        if (format !== RGBAFormat || type !== UnsignedByteType) {
          console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.");
        }
      } else {
        console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace);
      }
    }
    return image;
  }
  function getDimensions(image) {
    if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) {
      _imageDimensions.width = image.naturalWidth || image.width;
      _imageDimensions.height = image.naturalHeight || image.height;
    } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) {
      _imageDimensions.width = image.displayWidth;
      _imageDimensions.height = image.displayHeight;
    } else {
      _imageDimensions.width = image.width;
      _imageDimensions.height = image.height;
    }
    return _imageDimensions;
  }
  this.allocateTextureUnit = allocateTextureUnit;
  this.resetTextureUnits = resetTextureUnits;
  this.setTexture2D = setTexture2D;
  this.setTexture2DArray = setTexture2DArray;
  this.setTexture3D = setTexture3D;
  this.setTextureCube = setTextureCube;
  this.rebindTextures = rebindTextures;
  this.setupRenderTarget = setupRenderTarget;
  this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  this.setupFrameBufferTexture = setupFrameBufferTexture;
  this.useMultisampledRTT = useMultisampledRTT;
}
function WebGLUtils(gl, extensions) {
  function convert(p2, colorSpace = NoColorSpace) {
    let extension;
    const transfer = ColorManagement.getTransfer(colorSpace);
    if (p2 === UnsignedByteType) return gl.UNSIGNED_BYTE;
    if (p2 === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
    if (p2 === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
    if (p2 === UnsignedInt5999Type) return gl.UNSIGNED_INT_5_9_9_9_REV;
    if (p2 === ByteType) return gl.BYTE;
    if (p2 === ShortType) return gl.SHORT;
    if (p2 === UnsignedShortType) return gl.UNSIGNED_SHORT;
    if (p2 === IntType) return gl.INT;
    if (p2 === UnsignedIntType) return gl.UNSIGNED_INT;
    if (p2 === FloatType) return gl.FLOAT;
    if (p2 === HalfFloatType) return gl.HALF_FLOAT;
    if (p2 === AlphaFormat) return gl.ALPHA;
    if (p2 === RGBFormat) return gl.RGB;
    if (p2 === RGBAFormat) return gl.RGBA;
    if (p2 === LuminanceFormat) return gl.LUMINANCE;
    if (p2 === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
    if (p2 === DepthFormat) return gl.DEPTH_COMPONENT;
    if (p2 === DepthStencilFormat) return gl.DEPTH_STENCIL;
    if (p2 === RedFormat) return gl.RED;
    if (p2 === RedIntegerFormat) return gl.RED_INTEGER;
    if (p2 === RGFormat) return gl.RG;
    if (p2 === RGIntegerFormat) return gl.RG_INTEGER;
    if (p2 === RGBAIntegerFormat) return gl.RGBA_INTEGER;
    if (p2 === RGB_S3TC_DXT1_Format || p2 === RGBA_S3TC_DXT1_Format || p2 === RGBA_S3TC_DXT3_Format || p2 === RGBA_S3TC_DXT5_Format) {
      if (transfer === SRGBTransfer) {
        extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb");
        if (extension !== null) {
          if (p2 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          if (p2 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          if (p2 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          if (p2 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
        } else {
          return null;
        }
      } else {
        extension = extensions.get("WEBGL_compressed_texture_s3tc");
        if (extension !== null) {
          if (p2 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
          if (p2 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          if (p2 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          if (p2 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
        } else {
          return null;
        }
      }
    }
    if (p2 === RGB_PVRTC_4BPPV1_Format || p2 === RGB_PVRTC_2BPPV1_Format || p2 === RGBA_PVRTC_4BPPV1_Format || p2 === RGBA_PVRTC_2BPPV1_Format) {
      extension = extensions.get("WEBGL_compressed_texture_pvrtc");
      if (extension !== null) {
        if (p2 === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
        if (p2 === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
        if (p2 === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
        if (p2 === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
      } else {
        return null;
      }
    }
    if (p2 === RGB_ETC1_Format || p2 === RGB_ETC2_Format || p2 === RGBA_ETC2_EAC_Format) {
      extension = extensions.get("WEBGL_compressed_texture_etc");
      if (extension !== null) {
        if (p2 === RGB_ETC1_Format || p2 === RGB_ETC2_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
        if (p2 === RGBA_ETC2_EAC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
      } else {
        return null;
      }
    }
    if (p2 === RGBA_ASTC_4x4_Format || p2 === RGBA_ASTC_5x4_Format || p2 === RGBA_ASTC_5x5_Format || p2 === RGBA_ASTC_6x5_Format || p2 === RGBA_ASTC_6x6_Format || p2 === RGBA_ASTC_8x5_Format || p2 === RGBA_ASTC_8x6_Format || p2 === RGBA_ASTC_8x8_Format || p2 === RGBA_ASTC_10x5_Format || p2 === RGBA_ASTC_10x6_Format || p2 === RGBA_ASTC_10x8_Format || p2 === RGBA_ASTC_10x10_Format || p2 === RGBA_ASTC_12x10_Format || p2 === RGBA_ASTC_12x12_Format) {
      extension = extensions.get("WEBGL_compressed_texture_astc");
      if (extension !== null) {
        if (p2 === RGBA_ASTC_4x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
        if (p2 === RGBA_ASTC_5x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
        if (p2 === RGBA_ASTC_5x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
        if (p2 === RGBA_ASTC_6x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
        if (p2 === RGBA_ASTC_6x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
        if (p2 === RGBA_ASTC_8x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
        if (p2 === RGBA_ASTC_8x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
        if (p2 === RGBA_ASTC_8x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
        if (p2 === RGBA_ASTC_10x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
        if (p2 === RGBA_ASTC_10x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
        if (p2 === RGBA_ASTC_10x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
        if (p2 === RGBA_ASTC_10x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
        if (p2 === RGBA_ASTC_12x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
        if (p2 === RGBA_ASTC_12x12_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
      } else {
        return null;
      }
    }
    if (p2 === RGBA_BPTC_Format || p2 === RGB_BPTC_SIGNED_Format || p2 === RGB_BPTC_UNSIGNED_Format) {
      extension = extensions.get("EXT_texture_compression_bptc");
      if (extension !== null) {
        if (p2 === RGBA_BPTC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
        if (p2 === RGB_BPTC_SIGNED_Format) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
        if (p2 === RGB_BPTC_UNSIGNED_Format) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
      } else {
        return null;
      }
    }
    if (p2 === RED_RGTC1_Format || p2 === SIGNED_RED_RGTC1_Format || p2 === RED_GREEN_RGTC2_Format || p2 === SIGNED_RED_GREEN_RGTC2_Format) {
      extension = extensions.get("EXT_texture_compression_rgtc");
      if (extension !== null) {
        if (p2 === RGBA_BPTC_Format) return extension.COMPRESSED_RED_RGTC1_EXT;
        if (p2 === SIGNED_RED_RGTC1_Format) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
        if (p2 === RED_GREEN_RGTC2_Format) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
        if (p2 === SIGNED_RED_GREEN_RGTC2_Format) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
      } else {
        return null;
      }
    }
    if (p2 === UnsignedInt248Type) return gl.UNSIGNED_INT_24_8;
    return gl[p2] !== void 0 ? gl[p2] : null;
  }
  return { convert };
}
const _moveEvent = { type: "move" };
class WebXRController {
  constructor() {
    this._targetRay = null;
    this._grip = null;
    this._hand = null;
  }
  getHandSpace() {
    if (this._hand === null) {
      this._hand = new Group();
      this._hand.matrixAutoUpdate = false;
      this._hand.visible = false;
      this._hand.joints = {};
      this._hand.inputState = { pinching: false };
    }
    return this._hand;
  }
  getTargetRaySpace() {
    if (this._targetRay === null) {
      this._targetRay = new Group();
      this._targetRay.matrixAutoUpdate = false;
      this._targetRay.visible = false;
      this._targetRay.hasLinearVelocity = false;
      this._targetRay.linearVelocity = new Vector3();
      this._targetRay.hasAngularVelocity = false;
      this._targetRay.angularVelocity = new Vector3();
    }
    return this._targetRay;
  }
  getGripSpace() {
    if (this._grip === null) {
      this._grip = new Group();
      this._grip.matrixAutoUpdate = false;
      this._grip.visible = false;
      this._grip.hasLinearVelocity = false;
      this._grip.linearVelocity = new Vector3();
      this._grip.hasAngularVelocity = false;
      this._grip.angularVelocity = new Vector3();
    }
    return this._grip;
  }
  dispatchEvent(event) {
    if (this._targetRay !== null) {
      this._targetRay.dispatchEvent(event);
    }
    if (this._grip !== null) {
      this._grip.dispatchEvent(event);
    }
    if (this._hand !== null) {
      this._hand.dispatchEvent(event);
    }
    return this;
  }
  connect(inputSource) {
    if (inputSource && inputSource.hand) {
      const hand = this._hand;
      if (hand) {
        for (const inputjoint of inputSource.hand.values()) {
          this._getHandJoint(hand, inputjoint);
        }
      }
    }
    this.dispatchEvent({ type: "connected", data: inputSource });
    return this;
  }
  disconnect(inputSource) {
    this.dispatchEvent({ type: "disconnected", data: inputSource });
    if (this._targetRay !== null) {
      this._targetRay.visible = false;
    }
    if (this._grip !== null) {
      this._grip.visible = false;
    }
    if (this._hand !== null) {
      this._hand.visible = false;
    }
    return this;
  }
  update(inputSource, frame, referenceSpace) {
    let inputPose = null;
    let gripPose = null;
    let handPose = null;
    const targetRay = this._targetRay;
    const grip = this._grip;
    const hand = this._hand;
    if (inputSource && frame.session.visibilityState !== "visible-blurred") {
      if (hand && inputSource.hand) {
        handPose = true;
        for (const inputjoint of inputSource.hand.values()) {
          const jointPose = frame.getJointPose(inputjoint, referenceSpace);
          const joint = this._getHandJoint(hand, inputjoint);
          if (jointPose !== null) {
            joint.matrix.fromArray(jointPose.transform.matrix);
            joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
            joint.matrixWorldNeedsUpdate = true;
            joint.jointRadius = jointPose.radius;
          }
          joint.visible = jointPose !== null;
        }
        const indexTip = hand.joints["index-finger-tip"];
        const thumbTip = hand.joints["thumb-tip"];
        const distance = indexTip.position.distanceTo(thumbTip.position);
        const distanceToPinch = 0.02;
        const threshold = 5e-3;
        if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
          hand.inputState.pinching = false;
          this.dispatchEvent({
            type: "pinchend",
            handedness: inputSource.handedness,
            target: this
          });
        } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
          hand.inputState.pinching = true;
          this.dispatchEvent({
            type: "pinchstart",
            handedness: inputSource.handedness,
            target: this
          });
        }
      } else {
        if (grip !== null && inputSource.gripSpace) {
          gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
          if (gripPose !== null) {
            grip.matrix.fromArray(gripPose.transform.matrix);
            grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
            grip.matrixWorldNeedsUpdate = true;
            if (gripPose.linearVelocity) {
              grip.hasLinearVelocity = true;
              grip.linearVelocity.copy(gripPose.linearVelocity);
            } else {
              grip.hasLinearVelocity = false;
            }
            if (gripPose.angularVelocity) {
              grip.hasAngularVelocity = true;
              grip.angularVelocity.copy(gripPose.angularVelocity);
            } else {
              grip.hasAngularVelocity = false;
            }
          }
        }
      }
      if (targetRay !== null) {
        inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
        if (inputPose === null && gripPose !== null) {
          inputPose = gripPose;
        }
        if (inputPose !== null) {
          targetRay.matrix.fromArray(inputPose.transform.matrix);
          targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
          targetRay.matrixWorldNeedsUpdate = true;
          if (inputPose.linearVelocity) {
            targetRay.hasLinearVelocity = true;
            targetRay.linearVelocity.copy(inputPose.linearVelocity);
          } else {
            targetRay.hasLinearVelocity = false;
          }
          if (inputPose.angularVelocity) {
            targetRay.hasAngularVelocity = true;
            targetRay.angularVelocity.copy(inputPose.angularVelocity);
          } else {
            targetRay.hasAngularVelocity = false;
          }
          this.dispatchEvent(_moveEvent);
        }
      }
    }
    if (targetRay !== null) {
      targetRay.visible = inputPose !== null;
    }
    if (grip !== null) {
      grip.visible = gripPose !== null;
    }
    if (hand !== null) {
      hand.visible = handPose !== null;
    }
    return this;
  }
  // private method
  _getHandJoint(hand, inputjoint) {
    if (hand.joints[inputjoint.jointName] === void 0) {
      const joint = new Group();
      joint.matrixAutoUpdate = false;
      joint.visible = false;
      hand.joints[inputjoint.jointName] = joint;
      hand.add(joint);
    }
    return hand.joints[inputjoint.jointName];
  }
}
const _occlusion_vertex = `
void main() {

	gl_Position = vec4( position, 1.0 );

}`;
const _occlusion_fragment = `
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;
class WebXRDepthSensing {
  constructor() {
    this.texture = null;
    this.mesh = null;
    this.depthNear = 0;
    this.depthFar = 0;
  }
  init(renderer, depthData, renderState) {
    if (this.texture === null) {
      const texture = new Texture();
      const texProps = renderer.properties.get(texture);
      texProps.__webglTexture = depthData.texture;
      if (depthData.depthNear != renderState.depthNear || depthData.depthFar != renderState.depthFar) {
        this.depthNear = depthData.depthNear;
        this.depthFar = depthData.depthFar;
      }
      this.texture = texture;
    }
  }
  getMesh(cameraXR) {
    if (this.texture !== null) {
      if (this.mesh === null) {
        const viewport = cameraXR.cameras[0].viewport;
        const material = new ShaderMaterial({
          vertexShader: _occlusion_vertex,
          fragmentShader: _occlusion_fragment,
          uniforms: {
            depthColor: { value: this.texture },
            depthWidth: { value: viewport.z },
            depthHeight: { value: viewport.w }
          }
        });
        this.mesh = new Mesh(new PlaneGeometry(20, 20), material);
      }
    }
    return this.mesh;
  }
  reset() {
    this.texture = null;
    this.mesh = null;
  }
  getDepthTexture() {
    return this.texture;
  }
}
class WebXRManager extends EventDispatcher$1 {
  constructor(renderer, gl) {
    super();
    const scope = this;
    let session = null;
    let framebufferScaleFactor = 1;
    let referenceSpace = null;
    let referenceSpaceType = "local-floor";
    let foveation = 1;
    let customReferenceSpace = null;
    let pose = null;
    let glBinding = null;
    let glProjLayer = null;
    let glBaseLayer = null;
    let xrFrame = null;
    const depthSensing = new WebXRDepthSensing();
    const attributes = gl.getContextAttributes();
    let initialRenderTarget = null;
    let newRenderTarget = null;
    const controllers = [];
    const controllerInputSources = [];
    const currentSize = new Vector2();
    let currentPixelRatio = null;
    const cameraL = new PerspectiveCamera();
    cameraL.viewport = new Vector4();
    const cameraR = new PerspectiveCamera();
    cameraR.viewport = new Vector4();
    const cameras = [cameraL, cameraR];
    const cameraXR = new ArrayCamera();
    let _currentDepthNear = null;
    let _currentDepthFar = null;
    this.cameraAutoUpdate = true;
    this.enabled = false;
    this.isPresenting = false;
    this.getController = function(index) {
      let controller = controllers[index];
      if (controller === void 0) {
        controller = new WebXRController();
        controllers[index] = controller;
      }
      return controller.getTargetRaySpace();
    };
    this.getControllerGrip = function(index) {
      let controller = controllers[index];
      if (controller === void 0) {
        controller = new WebXRController();
        controllers[index] = controller;
      }
      return controller.getGripSpace();
    };
    this.getHand = function(index) {
      let controller = controllers[index];
      if (controller === void 0) {
        controller = new WebXRController();
        controllers[index] = controller;
      }
      return controller.getHandSpace();
    };
    function onSessionEvent(event) {
      const controllerIndex = controllerInputSources.indexOf(event.inputSource);
      if (controllerIndex === -1) {
        return;
      }
      const controller = controllers[controllerIndex];
      if (controller !== void 0) {
        controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace);
        controller.dispatchEvent({ type: event.type, data: event.inputSource });
      }
    }
    function onSessionEnd() {
      session.removeEventListener("select", onSessionEvent);
      session.removeEventListener("selectstart", onSessionEvent);
      session.removeEventListener("selectend", onSessionEvent);
      session.removeEventListener("squeeze", onSessionEvent);
      session.removeEventListener("squeezestart", onSessionEvent);
      session.removeEventListener("squeezeend", onSessionEvent);
      session.removeEventListener("end", onSessionEnd);
      session.removeEventListener("inputsourceschange", onInputSourcesChange);
      for (let i2 = 0; i2 < controllers.length; i2++) {
        const inputSource = controllerInputSources[i2];
        if (inputSource === null) continue;
        controllerInputSources[i2] = null;
        controllers[i2].disconnect(inputSource);
      }
      _currentDepthNear = null;
      _currentDepthFar = null;
      depthSensing.reset();
      renderer.setRenderTarget(initialRenderTarget);
      glBaseLayer = null;
      glProjLayer = null;
      glBinding = null;
      session = null;
      newRenderTarget = null;
      animation.stop();
      scope.isPresenting = false;
      renderer.setPixelRatio(currentPixelRatio);
      renderer.setSize(currentSize.width, currentSize.height, false);
      scope.dispatchEvent({ type: "sessionend" });
    }
    this.setFramebufferScaleFactor = function(value) {
      framebufferScaleFactor = value;
      if (scope.isPresenting === true) {
        console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.");
      }
    };
    this.setReferenceSpaceType = function(value) {
      referenceSpaceType = value;
      if (scope.isPresenting === true) {
        console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.");
      }
    };
    this.getReferenceSpace = function() {
      return customReferenceSpace || referenceSpace;
    };
    this.setReferenceSpace = function(space) {
      customReferenceSpace = space;
    };
    this.getBaseLayer = function() {
      return glProjLayer !== null ? glProjLayer : glBaseLayer;
    };
    this.getBinding = function() {
      return glBinding;
    };
    this.getFrame = function() {
      return xrFrame;
    };
    this.getSession = function() {
      return session;
    };
    this.setSession = async function(value) {
      session = value;
      if (session !== null) {
        initialRenderTarget = renderer.getRenderTarget();
        session.addEventListener("select", onSessionEvent);
        session.addEventListener("selectstart", onSessionEvent);
        session.addEventListener("selectend", onSessionEvent);
        session.addEventListener("squeeze", onSessionEvent);
        session.addEventListener("squeezestart", onSessionEvent);
        session.addEventListener("squeezeend", onSessionEvent);
        session.addEventListener("end", onSessionEnd);
        session.addEventListener("inputsourceschange", onInputSourcesChange);
        if (attributes.xrCompatible !== true) {
          await gl.makeXRCompatible();
        }
        currentPixelRatio = renderer.getPixelRatio();
        renderer.getSize(currentSize);
        if (session.renderState.layers === void 0) {
          const layerInit = {
            antialias: attributes.antialias,
            alpha: true,
            depth: attributes.depth,
            stencil: attributes.stencil,
            framebufferScaleFactor
          };
          glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
          session.updateRenderState({ baseLayer: glBaseLayer });
          renderer.setPixelRatio(1);
          renderer.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false);
          newRenderTarget = new WebGLRenderTarget(
            glBaseLayer.framebufferWidth,
            glBaseLayer.framebufferHeight,
            {
              format: RGBAFormat,
              type: UnsignedByteType,
              colorSpace: renderer.outputColorSpace,
              stencilBuffer: attributes.stencil
            }
          );
        } else {
          let depthFormat = null;
          let depthType = null;
          let glDepthFormat = null;
          if (attributes.depth) {
            glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
            depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
            depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
          }
          const projectionlayerInit = {
            colorFormat: gl.RGBA8,
            depthFormat: glDepthFormat,
            scaleFactor: framebufferScaleFactor
          };
          glBinding = new XRWebGLBinding(session, gl);
          glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
          session.updateRenderState({ layers: [glProjLayer] });
          renderer.setPixelRatio(1);
          renderer.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false);
          newRenderTarget = new WebGLRenderTarget(
            glProjLayer.textureWidth,
            glProjLayer.textureHeight,
            {
              format: RGBAFormat,
              type: UnsignedByteType,
              depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, void 0, void 0, void 0, void 0, void 0, void 0, depthFormat),
              stencilBuffer: attributes.stencil,
              colorSpace: renderer.outputColorSpace,
              samples: attributes.antialias ? 4 : 0,
              resolveDepthBuffer: glProjLayer.ignoreDepthValues === false
            }
          );
        }
        newRenderTarget.isXRRenderTarget = true;
        this.setFoveation(foveation);
        customReferenceSpace = null;
        referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
        animation.setContext(session);
        animation.start();
        scope.isPresenting = true;
        scope.dispatchEvent({ type: "sessionstart" });
      }
    };
    this.getEnvironmentBlendMode = function() {
      if (session !== null) {
        return session.environmentBlendMode;
      }
    };
    this.getDepthTexture = function() {
      return depthSensing.getDepthTexture();
    };
    function onInputSourcesChange(event) {
      for (let i2 = 0; i2 < event.removed.length; i2++) {
        const inputSource = event.removed[i2];
        const index = controllerInputSources.indexOf(inputSource);
        if (index >= 0) {
          controllerInputSources[index] = null;
          controllers[index].disconnect(inputSource);
        }
      }
      for (let i2 = 0; i2 < event.added.length; i2++) {
        const inputSource = event.added[i2];
        let controllerIndex = controllerInputSources.indexOf(inputSource);
        if (controllerIndex === -1) {
          for (let i3 = 0; i3 < controllers.length; i3++) {
            if (i3 >= controllerInputSources.length) {
              controllerInputSources.push(inputSource);
              controllerIndex = i3;
              break;
            } else if (controllerInputSources[i3] === null) {
              controllerInputSources[i3] = inputSource;
              controllerIndex = i3;
              break;
            }
          }
          if (controllerIndex === -1) break;
        }
        const controller = controllers[controllerIndex];
        if (controller) {
          controller.connect(inputSource);
        }
      }
    }
    const cameraLPos = new Vector3();
    const cameraRPos = new Vector3();
    function setProjectionFromUnion(camera, cameraL2, cameraR2) {
      cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld);
      cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld);
      const ipd = cameraLPos.distanceTo(cameraRPos);
      const projL = cameraL2.projectionMatrix.elements;
      const projR = cameraR2.projectionMatrix.elements;
      const near = projL[14] / (projL[10] - 1);
      const far = projL[14] / (projL[10] + 1);
      const topFov = (projL[9] + 1) / projL[5];
      const bottomFov = (projL[9] - 1) / projL[5];
      const leftFov = (projL[8] - 1) / projL[0];
      const rightFov = (projR[8] + 1) / projR[0];
      const left = near * leftFov;
      const right = near * rightFov;
      const zOffset = ipd / (-leftFov + rightFov);
      const xOffset = zOffset * -leftFov;
      cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
      camera.translateX(xOffset);
      camera.translateZ(zOffset);
      camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
      camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
      if (projL[10] === -1) {
        camera.projectionMatrix.copy(cameraL2.projectionMatrix);
        camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse);
      } else {
        const near2 = near + zOffset;
        const far2 = far + zOffset;
        const left2 = left - xOffset;
        const right2 = right + (ipd - xOffset);
        const top2 = topFov * far / far2 * near2;
        const bottom2 = bottomFov * far / far2 * near2;
        camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
        camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
      }
    }
    function updateCamera2(camera, parent) {
      if (parent === null) {
        camera.matrixWorld.copy(camera.matrix);
      } else {
        camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
      }
      camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
    }
    this.updateCamera = function(camera) {
      if (session === null) return;
      let depthNear = camera.near;
      let depthFar = camera.far;
      if (depthSensing.texture !== null) {
        if (depthSensing.depthNear > 0) depthNear = depthSensing.depthNear;
        if (depthSensing.depthFar > 0) depthFar = depthSensing.depthFar;
      }
      cameraXR.near = cameraR.near = cameraL.near = depthNear;
      cameraXR.far = cameraR.far = cameraL.far = depthFar;
      if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) {
        session.updateRenderState({
          depthNear: cameraXR.near,
          depthFar: cameraXR.far
        });
        _currentDepthNear = cameraXR.near;
        _currentDepthFar = cameraXR.far;
      }
      cameraL.layers.mask = camera.layers.mask | 2;
      cameraR.layers.mask = camera.layers.mask | 4;
      cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
      const parent = camera.parent;
      const cameras2 = cameraXR.cameras;
      updateCamera2(cameraXR, parent);
      for (let i2 = 0; i2 < cameras2.length; i2++) {
        updateCamera2(cameras2[i2], parent);
      }
      if (cameras2.length === 2) {
        setProjectionFromUnion(cameraXR, cameraL, cameraR);
      } else {
        cameraXR.projectionMatrix.copy(cameraL.projectionMatrix);
      }
      updateUserCamera(camera, cameraXR, parent);
    };
    function updateUserCamera(camera, cameraXR2, parent) {
      if (parent === null) {
        camera.matrix.copy(cameraXR2.matrixWorld);
      } else {
        camera.matrix.copy(parent.matrixWorld);
        camera.matrix.invert();
        camera.matrix.multiply(cameraXR2.matrixWorld);
      }
      camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
      camera.updateMatrixWorld(true);
      camera.projectionMatrix.copy(cameraXR2.projectionMatrix);
      camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse);
      if (camera.isPerspectiveCamera) {
        camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]);
        camera.zoom = 1;
      }
    }
    this.getCamera = function() {
      return cameraXR;
    };
    this.getFoveation = function() {
      if (glProjLayer === null && glBaseLayer === null) {
        return void 0;
      }
      return foveation;
    };
    this.setFoveation = function(value) {
      foveation = value;
      if (glProjLayer !== null) {
        glProjLayer.fixedFoveation = value;
      }
      if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== void 0) {
        glBaseLayer.fixedFoveation = value;
      }
    };
    this.hasDepthSensing = function() {
      return depthSensing.texture !== null;
    };
    this.getDepthSensingMesh = function() {
      return depthSensing.getMesh(cameraXR);
    };
    let onAnimationFrameCallback = null;
    function onAnimationFrame(time, frame) {
      pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
      xrFrame = frame;
      if (pose !== null) {
        const views = pose.views;
        if (glBaseLayer !== null) {
          renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
          renderer.setRenderTarget(newRenderTarget);
        }
        let cameraXRNeedsUpdate = false;
        if (views.length !== cameraXR.cameras.length) {
          cameraXR.cameras.length = 0;
          cameraXRNeedsUpdate = true;
        }
        for (let i2 = 0; i2 < views.length; i2++) {
          const view = views[i2];
          let viewport = null;
          if (glBaseLayer !== null) {
            viewport = glBaseLayer.getViewport(view);
          } else {
            const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
            viewport = glSubImage.viewport;
            if (i2 === 0) {
              renderer.setRenderTargetTextures(
                newRenderTarget,
                glSubImage.colorTexture,
                glProjLayer.ignoreDepthValues ? void 0 : glSubImage.depthStencilTexture
              );
              renderer.setRenderTarget(newRenderTarget);
            }
          }
          let camera = cameras[i2];
          if (camera === void 0) {
            camera = new PerspectiveCamera();
            camera.layers.enable(i2);
            camera.viewport = new Vector4();
            cameras[i2] = camera;
          }
          camera.matrix.fromArray(view.transform.matrix);
          camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
          camera.projectionMatrix.fromArray(view.projectionMatrix);
          camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
          camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
          if (i2 === 0) {
            cameraXR.matrix.copy(camera.matrix);
            cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale);
          }
          if (cameraXRNeedsUpdate === true) {
            cameraXR.cameras.push(camera);
          }
        }
        const enabledFeatures = session.enabledFeatures;
        if (enabledFeatures && enabledFeatures.includes("depth-sensing")) {
          const depthData = glBinding.getDepthInformation(views[0]);
          if (depthData && depthData.isValid && depthData.texture) {
            depthSensing.init(renderer, depthData, session.renderState);
          }
        }
      }
      for (let i2 = 0; i2 < controllers.length; i2++) {
        const inputSource = controllerInputSources[i2];
        const controller = controllers[i2];
        if (inputSource !== null && controller !== void 0) {
          controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
        }
      }
      if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
      if (frame.detectedPlanes) {
        scope.dispatchEvent({ type: "planesdetected", data: frame });
      }
      xrFrame = null;
    }
    const animation = new WebGLAnimation();
    animation.setAnimationLoop(onAnimationFrame);
    this.setAnimationLoop = function(callback) {
      onAnimationFrameCallback = callback;
    };
    this.dispose = function() {
    };
  }
}
const _e1 = /* @__PURE__ */ new Euler();
const _m1 = /* @__PURE__ */ new Matrix4();
function WebGLMaterials(renderer, properties) {
  function refreshTransformUniform(map, uniform) {
    if (map.matrixAutoUpdate === true) {
      map.updateMatrix();
    }
    uniform.value.copy(map.matrix);
  }
  function refreshFogUniforms(uniforms, fog) {
    fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer));
    if (fog.isFog) {
      uniforms.fogNear.value = fog.near;
      uniforms.fogFar.value = fog.far;
    } else if (fog.isFogExp2) {
      uniforms.fogDensity.value = fog.density;
    }
  }
  function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
    if (material.isMeshBasicMaterial) {
      refreshUniformsCommon(uniforms, material);
    } else if (material.isMeshLambertMaterial) {
      refreshUniformsCommon(uniforms, material);
    } else if (material.isMeshToonMaterial) {
      refreshUniformsCommon(uniforms, material);
      refreshUniformsToon(uniforms, material);
    } else if (material.isMeshPhongMaterial) {
      refreshUniformsCommon(uniforms, material);
      refreshUniformsPhong(uniforms, material);
    } else if (material.isMeshStandardMaterial) {
      refreshUniformsCommon(uniforms, material);
      refreshUniformsStandard(uniforms, material);
      if (material.isMeshPhysicalMaterial) {
        refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
      }
    } else if (material.isMeshMatcapMaterial) {
      refreshUniformsCommon(uniforms, material);
      refreshUniformsMatcap(uniforms, material);
    } else if (material.isMeshDepthMaterial) {
      refreshUniformsCommon(uniforms, material);
    } else if (material.isMeshDistanceMaterial) {
      refreshUniformsCommon(uniforms, material);
      refreshUniformsDistance(uniforms, material);
    } else if (material.isMeshNormalMaterial) {
      refreshUniformsCommon(uniforms, material);
    } else if (material.isLineBasicMaterial) {
      refreshUniformsLine(uniforms, material);
      if (material.isLineDashedMaterial) {
        refreshUniformsDash(uniforms, material);
      }
    } else if (material.isPointsMaterial) {
      refreshUniformsPoints(uniforms, material, pixelRatio, height);
    } else if (material.isSpriteMaterial) {
      refreshUniformsSprites(uniforms, material);
    } else if (material.isShadowMaterial) {
      uniforms.color.value.copy(material.color);
      uniforms.opacity.value = material.opacity;
    } else if (material.isShaderMaterial) {
      material.uniformsNeedUpdate = false;
    }
  }
  function refreshUniformsCommon(uniforms, material) {
    uniforms.opacity.value = material.opacity;
    if (material.color) {
      uniforms.diffuse.value.copy(material.color);
    }
    if (material.emissive) {
      uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
    }
    if (material.map) {
      uniforms.map.value = material.map;
      refreshTransformUniform(material.map, uniforms.mapTransform);
    }
    if (material.alphaMap) {
      uniforms.alphaMap.value = material.alphaMap;
      refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform);
    }
    if (material.bumpMap) {
      uniforms.bumpMap.value = material.bumpMap;
      refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform);
      uniforms.bumpScale.value = material.bumpScale;
      if (material.side === BackSide) {
        uniforms.bumpScale.value *= -1;
      }
    }
    if (material.normalMap) {
      uniforms.normalMap.value = material.normalMap;
      refreshTransformUniform(material.normalMap, uniforms.normalMapTransform);
      uniforms.normalScale.value.copy(material.normalScale);
      if (material.side === BackSide) {
        uniforms.normalScale.value.negate();
      }
    }
    if (material.displacementMap) {
      uniforms.displacementMap.value = material.displacementMap;
      refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform);
      uniforms.displacementScale.value = material.displacementScale;
      uniforms.displacementBias.value = material.displacementBias;
    }
    if (material.emissiveMap) {
      uniforms.emissiveMap.value = material.emissiveMap;
      refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform);
    }
    if (material.specularMap) {
      uniforms.specularMap.value = material.specularMap;
      refreshTransformUniform(material.specularMap, uniforms.specularMapTransform);
    }
    if (material.alphaTest > 0) {
      uniforms.alphaTest.value = material.alphaTest;
    }
    const materialProperties = properties.get(material);
    const envMap = materialProperties.envMap;
    const envMapRotation = materialProperties.envMapRotation;
    if (envMap) {
      uniforms.envMap.value = envMap;
      _e1.copy(envMapRotation);
      _e1.x *= -1;
      _e1.y *= -1;
      _e1.z *= -1;
      if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) {
        _e1.y *= -1;
        _e1.z *= -1;
      }
      uniforms.envMapRotation.value.setFromMatrix4(_m1.makeRotationFromEuler(_e1));
      uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
      uniforms.reflectivity.value = material.reflectivity;
      uniforms.ior.value = material.ior;
      uniforms.refractionRatio.value = material.refractionRatio;
    }
    if (material.lightMap) {
      uniforms.lightMap.value = material.lightMap;
      uniforms.lightMapIntensity.value = material.lightMapIntensity;
      refreshTransformUniform(material.lightMap, uniforms.lightMapTransform);
    }
    if (material.aoMap) {
      uniforms.aoMap.value = material.aoMap;
      uniforms.aoMapIntensity.value = material.aoMapIntensity;
      refreshTransformUniform(material.aoMap, uniforms.aoMapTransform);
    }
  }
  function refreshUniformsLine(uniforms, material) {
    uniforms.diffuse.value.copy(material.color);
    uniforms.opacity.value = material.opacity;
    if (material.map) {
      uniforms.map.value = material.map;
      refreshTransformUniform(material.map, uniforms.mapTransform);
    }
  }
  function refreshUniformsDash(uniforms, material) {
    uniforms.dashSize.value = material.dashSize;
    uniforms.totalSize.value = material.dashSize + material.gapSize;
    uniforms.scale.value = material.scale;
  }
  function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
    uniforms.diffuse.value.copy(material.color);
    uniforms.opacity.value = material.opacity;
    uniforms.size.value = material.size * pixelRatio;
    uniforms.scale.value = height * 0.5;
    if (material.map) {
      uniforms.map.value = material.map;
      refreshTransformUniform(material.map, uniforms.uvTransform);
    }
    if (material.alphaMap) {
      uniforms.alphaMap.value = material.alphaMap;
      refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform);
    }
    if (material.alphaTest > 0) {
      uniforms.alphaTest.value = material.alphaTest;
    }
  }
  function refreshUniformsSprites(uniforms, material) {
    uniforms.diffuse.value.copy(material.color);
    uniforms.opacity.value = material.opacity;
    uniforms.rotation.value = material.rotation;
    if (material.map) {
      uniforms.map.value = material.map;
      refreshTransformUniform(material.map, uniforms.mapTransform);
    }
    if (material.alphaMap) {
      uniforms.alphaMap.value = material.alphaMap;
      refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform);
    }
    if (material.alphaTest > 0) {
      uniforms.alphaTest.value = material.alphaTest;
    }
  }
  function refreshUniformsPhong(uniforms, material) {
    uniforms.specular.value.copy(material.specular);
    uniforms.shininess.value = Math.max(material.shininess, 1e-4);
  }
  function refreshUniformsToon(uniforms, material) {
    if (material.gradientMap) {
      uniforms.gradientMap.value = material.gradientMap;
    }
  }
  function refreshUniformsStandard(uniforms, material) {
    uniforms.metalness.value = material.metalness;
    if (material.metalnessMap) {
      uniforms.metalnessMap.value = material.metalnessMap;
      refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform);
    }
    uniforms.roughness.value = material.roughness;
    if (material.roughnessMap) {
      uniforms.roughnessMap.value = material.roughnessMap;
      refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform);
    }
    if (material.envMap) {
      uniforms.envMapIntensity.value = material.envMapIntensity;
    }
  }
  function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
    uniforms.ior.value = material.ior;
    if (material.sheen > 0) {
      uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
      uniforms.sheenRoughness.value = material.sheenRoughness;
      if (material.sheenColorMap) {
        uniforms.sheenColorMap.value = material.sheenColorMap;
        refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform);
      }
      if (material.sheenRoughnessMap) {
        uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
        refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform);
      }
    }
    if (material.clearcoat > 0) {
      uniforms.clearcoat.value = material.clearcoat;
      uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
      if (material.clearcoatMap) {
        uniforms.clearcoatMap.value = material.clearcoatMap;
        refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform);
      }
      if (material.clearcoatRoughnessMap) {
        uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
        refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform);
      }
      if (material.clearcoatNormalMap) {
        uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
        refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform);
        uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
        if (material.side === BackSide) {
          uniforms.clearcoatNormalScale.value.negate();
        }
      }
    }
    if (material.dispersion > 0) {
      uniforms.dispersion.value = material.dispersion;
    }
    if (material.iridescence > 0) {
      uniforms.iridescence.value = material.iridescence;
      uniforms.iridescenceIOR.value = material.iridescenceIOR;
      uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
      uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
      if (material.iridescenceMap) {
        uniforms.iridescenceMap.value = material.iridescenceMap;
        refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform);
      }
      if (material.iridescenceThicknessMap) {
        uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
        refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform);
      }
    }
    if (material.transmission > 0) {
      uniforms.transmission.value = material.transmission;
      uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
      uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
      if (material.transmissionMap) {
        uniforms.transmissionMap.value = material.transmissionMap;
        refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform);
      }
      uniforms.thickness.value = material.thickness;
      if (material.thicknessMap) {
        uniforms.thicknessMap.value = material.thicknessMap;
        refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform);
      }
      uniforms.attenuationDistance.value = material.attenuationDistance;
      uniforms.attenuationColor.value.copy(material.attenuationColor);
    }
    if (material.anisotropy > 0) {
      uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation));
      if (material.anisotropyMap) {
        uniforms.anisotropyMap.value = material.anisotropyMap;
        refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform);
      }
    }
    uniforms.specularIntensity.value = material.specularIntensity;
    uniforms.specularColor.value.copy(material.specularColor);
    if (material.specularColorMap) {
      uniforms.specularColorMap.value = material.specularColorMap;
      refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform);
    }
    if (material.specularIntensityMap) {
      uniforms.specularIntensityMap.value = material.specularIntensityMap;
      refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform);
    }
  }
  function refreshUniformsMatcap(uniforms, material) {
    if (material.matcap) {
      uniforms.matcap.value = material.matcap;
    }
  }
  function refreshUniformsDistance(uniforms, material) {
    const light = properties.get(material).light;
    uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld);
    uniforms.nearDistance.value = light.shadow.camera.near;
    uniforms.farDistance.value = light.shadow.camera.far;
  }
  return {
    refreshFogUniforms,
    refreshMaterialUniforms
  };
}
function WebGLUniformsGroups(gl, info, capabilities, state) {
  let buffers = {};
  let updateList = {};
  let allocatedBindingPoints = [];
  const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS);
  function bind(uniformsGroup, program) {
    const webglProgram = program.program;
    state.uniformBlockBinding(uniformsGroup, webglProgram);
  }
  function update(uniformsGroup, program) {
    let buffer = buffers[uniformsGroup.id];
    if (buffer === void 0) {
      prepareUniformsGroup(uniformsGroup);
      buffer = createBuffer(uniformsGroup);
      buffers[uniformsGroup.id] = buffer;
      uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose);
    }
    const webglProgram = program.program;
    state.updateUBOMapping(uniformsGroup, webglProgram);
    const frame = info.render.frame;
    if (updateList[uniformsGroup.id] !== frame) {
      updateBufferData(uniformsGroup);
      updateList[uniformsGroup.id] = frame;
    }
  }
  function createBuffer(uniformsGroup) {
    const bindingPointIndex = allocateBindingPointIndex();
    uniformsGroup.__bindingPointIndex = bindingPointIndex;
    const buffer = gl.createBuffer();
    const size = uniformsGroup.__size;
    const usage = uniformsGroup.usage;
    gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
    gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
    gl.bindBuffer(gl.UNIFORM_BUFFER, null);
    gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
    return buffer;
  }
  function allocateBindingPointIndex() {
    for (let i2 = 0; i2 < maxBindingPoints; i2++) {
      if (allocatedBindingPoints.indexOf(i2) === -1) {
        allocatedBindingPoints.push(i2);
        return i2;
      }
    }
    console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.");
    return 0;
  }
  function updateBufferData(uniformsGroup) {
    const buffer = buffers[uniformsGroup.id];
    const uniforms = uniformsGroup.uniforms;
    const cache = uniformsGroup.__cache;
    gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
    for (let i2 = 0, il = uniforms.length; i2 < il; i2++) {
      const uniformArray = Array.isArray(uniforms[i2]) ? uniforms[i2] : [uniforms[i2]];
      for (let j2 = 0, jl = uniformArray.length; j2 < jl; j2++) {
        const uniform = uniformArray[j2];
        if (hasUniformChanged(uniform, i2, j2, cache) === true) {
          const offset = uniform.__offset;
          const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value];
          let arrayOffset = 0;
          for (let k2 = 0; k2 < values.length; k2++) {
            const value = values[k2];
            const info2 = getUniformSize(value);
            if (typeof value === "number" || typeof value === "boolean") {
              uniform.__data[0] = value;
              gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data);
            } else if (value.isMatrix3) {
              uniform.__data[0] = value.elements[0];
              uniform.__data[1] = value.elements[1];
              uniform.__data[2] = value.elements[2];
              uniform.__data[3] = 0;
              uniform.__data[4] = value.elements[3];
              uniform.__data[5] = value.elements[4];
              uniform.__data[6] = value.elements[5];
              uniform.__data[7] = 0;
              uniform.__data[8] = value.elements[6];
              uniform.__data[9] = value.elements[7];
              uniform.__data[10] = value.elements[8];
              uniform.__data[11] = 0;
            } else {
              value.toArray(uniform.__data, arrayOffset);
              arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT;
            }
          }
          gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
        }
      }
    }
    gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  }
  function hasUniformChanged(uniform, index, indexArray, cache) {
    const value = uniform.value;
    const indexString = index + "_" + indexArray;
    if (cache[indexString] === void 0) {
      if (typeof value === "number" || typeof value === "boolean") {
        cache[indexString] = value;
      } else {
        cache[indexString] = value.clone();
      }
      return true;
    } else {
      const cachedObject = cache[indexString];
      if (typeof value === "number" || typeof value === "boolean") {
        if (cachedObject !== value) {
          cache[indexString] = value;
          return true;
        }
      } else {
        if (cachedObject.equals(value) === false) {
          cachedObject.copy(value);
          return true;
        }
      }
    }
    return false;
  }
  function prepareUniformsGroup(uniformsGroup) {
    const uniforms = uniformsGroup.uniforms;
    let offset = 0;
    const chunkSize = 16;
    for (let i2 = 0, l2 = uniforms.length; i2 < l2; i2++) {
      const uniformArray = Array.isArray(uniforms[i2]) ? uniforms[i2] : [uniforms[i2]];
      for (let j2 = 0, jl = uniformArray.length; j2 < jl; j2++) {
        const uniform = uniformArray[j2];
        const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value];
        for (let k2 = 0, kl = values.length; k2 < kl; k2++) {
          const value = values[k2];
          const info2 = getUniformSize(value);
          const chunkOffset2 = offset % chunkSize;
          const chunkPadding = chunkOffset2 % info2.boundary;
          const chunkStart = chunkOffset2 + chunkPadding;
          offset += chunkPadding;
          if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) {
            offset += chunkSize - chunkStart;
          }
          uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT);
          uniform.__offset = offset;
          offset += info2.storage;
        }
      }
    }
    const chunkOffset = offset % chunkSize;
    if (chunkOffset > 0) offset += chunkSize - chunkOffset;
    uniformsGroup.__size = offset;
    uniformsGroup.__cache = {};
    return this;
  }
  function getUniformSize(value) {
    const info2 = {
      boundary: 0,
      // bytes
      storage: 0
      // bytes
    };
    if (typeof value === "number" || typeof value === "boolean") {
      info2.boundary = 4;
      info2.storage = 4;
    } else if (value.isVector2) {
      info2.boundary = 8;
      info2.storage = 8;
    } else if (value.isVector3 || value.isColor) {
      info2.boundary = 16;
      info2.storage = 12;
    } else if (value.isVector4) {
      info2.boundary = 16;
      info2.storage = 16;
    } else if (value.isMatrix3) {
      info2.boundary = 48;
      info2.storage = 48;
    } else if (value.isMatrix4) {
      info2.boundary = 64;
      info2.storage = 64;
    } else if (value.isTexture) {
      console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.");
    } else {
      console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value);
    }
    return info2;
  }
  function onUniformsGroupsDispose(event) {
    const uniformsGroup = event.target;
    uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose);
    const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
    allocatedBindingPoints.splice(index, 1);
    gl.deleteBuffer(buffers[uniformsGroup.id]);
    delete buffers[uniformsGroup.id];
    delete updateList[uniformsGroup.id];
  }
  function dispose2() {
    for (const id in buffers) {
      gl.deleteBuffer(buffers[id]);
    }
    allocatedBindingPoints = [];
    buffers = {};
    updateList = {};
  }
  return {
    bind,
    update,
    dispose: dispose2
  };
}
class WebGLRenderer {
  constructor(parameters = {}) {
    const {
      canvas = createCanvasElement(),
      context: context2 = null,
      depth = true,
      stencil = false,
      alpha = false,
      antialias = false,
      premultipliedAlpha = true,
      preserveDrawingBuffer = false,
      powerPreference = "default",
      failIfMajorPerformanceCaveat = false,
      reverseDepthBuffer = false
    } = parameters;
    this.isWebGLRenderer = true;
    let _alpha;
    if (context2 !== null) {
      if (typeof WebGLRenderingContext !== "undefined" && context2 instanceof WebGLRenderingContext) {
        throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");
      }
      _alpha = context2.getContextAttributes().alpha;
    } else {
      _alpha = alpha;
    }
    const uintClearColor = new Uint32Array(4);
    const intClearColor = new Int32Array(4);
    let currentRenderList = null;
    let currentRenderState = null;
    const renderListStack = [];
    const renderStateStack = [];
    this.domElement = canvas;
    this.debug = {
      /**
       * Enables error checking and reporting when shader programs are being compiled
       * @type {boolean}
       */
      checkShaderErrors: true,
      /**
       * Callback for custom error reporting.
       * @type {?Function}
       */
      onShaderError: null
    };
    this.autoClear = true;
    this.autoClearColor = true;
    this.autoClearDepth = true;
    this.autoClearStencil = true;
    this.sortObjects = true;
    this.clippingPlanes = [];
    this.localClippingEnabled = false;
    this._outputColorSpace = SRGBColorSpace;
    this.toneMapping = NoToneMapping;
    this.toneMappingExposure = 1;
    const _this = this;
    let _isContextLost = false;
    let _currentActiveCubeFace = 0;
    let _currentActiveMipmapLevel = 0;
    let _currentRenderTarget = null;
    let _currentMaterialId = -1;
    let _currentCamera = null;
    const _currentViewport = new Vector4();
    const _currentScissor = new Vector4();
    let _currentScissorTest = null;
    const _currentClearColor = new Color(0);
    let _currentClearAlpha = 0;
    let _width = canvas.width;
    let _height = canvas.height;
    let _pixelRatio = 1;
    let _opaqueSort = null;
    let _transparentSort = null;
    const _viewport2 = new Vector4(0, 0, _width, _height);
    const _scissor = new Vector4(0, 0, _width, _height);
    let _scissorTest = false;
    const _frustum2 = new Frustum();
    let _clippingEnabled = false;
    let _localClippingEnabled = false;
    const _currentProjectionMatrix = new Matrix4();
    const _projScreenMatrix2 = new Matrix4();
    const _vector32 = new Vector3();
    const _vector4 = new Vector4();
    const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
    let _renderBackground = false;
    function getTargetPixelRatio() {
      return _currentRenderTarget === null ? _pixelRatio : 1;
    }
    let _gl = context2;
    function getContext(contextName, contextAttributes) {
      return canvas.getContext(contextName, contextAttributes);
    }
    try {
      const contextAttributes = {
        alpha: true,
        depth,
        stencil,
        antialias,
        premultipliedAlpha,
        preserveDrawingBuffer,
        powerPreference,
        failIfMajorPerformanceCaveat
      };
      if ("setAttribute" in canvas) canvas.setAttribute("data-engine", `three.js r${REVISION}`);
      canvas.addEventListener("webglcontextlost", onContextLost, false);
      canvas.addEventListener("webglcontextrestored", onContextRestore, false);
      canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false);
      if (_gl === null) {
        const contextName = "webgl2";
        _gl = getContext(contextName, contextAttributes);
        if (_gl === null) {
          if (getContext(contextName)) {
            throw new Error("Error creating WebGL context with your selected attributes.");
          } else {
            throw new Error("Error creating WebGL context.");
          }
        }
      }
    } catch (error2) {
      console.error("THREE.WebGLRenderer: " + error2.message);
      throw error2;
    }
    let extensions, capabilities, state, info;
    let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
    let programCache, materials, renderLists, renderStates, clipping, shadowMap;
    let background, morphtargets, bufferRenderer, indexedBufferRenderer;
    let utils, bindingStates, uniformsGroups;
    function initGLContext() {
      extensions = new WebGLExtensions(_gl);
      extensions.init();
      utils = new WebGLUtils(_gl, extensions);
      capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils);
      state = new WebGLState(_gl, extensions);
      if (capabilities.reverseDepthBuffer && reverseDepthBuffer) {
        state.buffers.depth.setReversed(true);
      }
      info = new WebGLInfo(_gl);
      properties = new WebGLProperties();
      textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
      cubemaps = new WebGLCubeMaps(_this);
      cubeuvmaps = new WebGLCubeUVMaps(_this);
      attributes = new WebGLAttributes(_gl);
      bindingStates = new WebGLBindingStates(_gl, attributes);
      geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
      objects = new WebGLObjects(_gl, geometries, attributes, info);
      morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
      clipping = new WebGLClipping(properties);
      programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
      materials = new WebGLMaterials(_this, properties);
      renderLists = new WebGLRenderLists();
      renderStates = new WebGLRenderStates(extensions);
      background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha);
      shadowMap = new WebGLShadowMap(_this, objects, capabilities);
      uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
      bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info);
      indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info);
      info.programs = programCache.programs;
      _this.capabilities = capabilities;
      _this.extensions = extensions;
      _this.properties = properties;
      _this.renderLists = renderLists;
      _this.shadowMap = shadowMap;
      _this.state = state;
      _this.info = info;
    }
    initGLContext();
    const xr = new WebXRManager(_this, _gl);
    this.xr = xr;
    this.getContext = function() {
      return _gl;
    };
    this.getContextAttributes = function() {
      return _gl.getContextAttributes();
    };
    this.forceContextLoss = function() {
      const extension = extensions.get("WEBGL_lose_context");
      if (extension) extension.loseContext();
    };
    this.forceContextRestore = function() {
      const extension = extensions.get("WEBGL_lose_context");
      if (extension) extension.restoreContext();
    };
    this.getPixelRatio = function() {
      return _pixelRatio;
    };
    this.setPixelRatio = function(value) {
      if (value === void 0) return;
      _pixelRatio = value;
      this.setSize(_width, _height, false);
    };
    this.getSize = function(target) {
      return target.set(_width, _height);
    };
    this.setSize = function(width, height, updateStyle = true) {
      if (xr.isPresenting) {
        console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");
        return;
      }
      _width = width;
      _height = height;
      canvas.width = Math.floor(width * _pixelRatio);
      canvas.height = Math.floor(height * _pixelRatio);
      if (updateStyle === true) {
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
      }
      this.setViewport(0, 0, width, height);
    };
    this.getDrawingBufferSize = function(target) {
      return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
    };
    this.setDrawingBufferSize = function(width, height, pixelRatio) {
      _width = width;
      _height = height;
      _pixelRatio = pixelRatio;
      canvas.width = Math.floor(width * pixelRatio);
      canvas.height = Math.floor(height * pixelRatio);
      this.setViewport(0, 0, width, height);
    };
    this.getCurrentViewport = function(target) {
      return target.copy(_currentViewport);
    };
    this.getViewport = function(target) {
      return target.copy(_viewport2);
    };
    this.setViewport = function(x, y2, width, height) {
      if (x.isVector4) {
        _viewport2.set(x.x, x.y, x.z, x.w);
      } else {
        _viewport2.set(x, y2, width, height);
      }
      state.viewport(_currentViewport.copy(_viewport2).multiplyScalar(_pixelRatio).round());
    };
    this.getScissor = function(target) {
      return target.copy(_scissor);
    };
    this.setScissor = function(x, y2, width, height) {
      if (x.isVector4) {
        _scissor.set(x.x, x.y, x.z, x.w);
      } else {
        _scissor.set(x, y2, width, height);
      }
      state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round());
    };
    this.getScissorTest = function() {
      return _scissorTest;
    };
    this.setScissorTest = function(boolean) {
      state.setScissorTest(_scissorTest = boolean);
    };
    this.setOpaqueSort = function(method) {
      _opaqueSort = method;
    };
    this.setTransparentSort = function(method) {
      _transparentSort = method;
    };
    this.getClearColor = function(target) {
      return target.copy(background.getClearColor());
    };
    this.setClearColor = function() {
      background.setClearColor.apply(background, arguments);
    };
    this.getClearAlpha = function() {
      return background.getClearAlpha();
    };
    this.setClearAlpha = function() {
      background.setClearAlpha.apply(background, arguments);
    };
    this.clear = function(color = true, depth2 = true, stencil2 = true) {
      let bits2 = 0;
      if (color) {
        let isIntegerFormat = false;
        if (_currentRenderTarget !== null) {
          const targetFormat = _currentRenderTarget.texture.format;
          isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat;
        }
        if (isIntegerFormat) {
          const targetType = _currentRenderTarget.texture.type;
          const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type;
          const clearColor = background.getClearColor();
          const a3 = background.getClearAlpha();
          const r2 = clearColor.r;
          const g2 = clearColor.g;
          const b2 = clearColor.b;
          if (isUnsignedType) {
            uintClearColor[0] = r2;
            uintClearColor[1] = g2;
            uintClearColor[2] = b2;
            uintClearColor[3] = a3;
            _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor);
          } else {
            intClearColor[0] = r2;
            intClearColor[1] = g2;
            intClearColor[2] = b2;
            intClearColor[3] = a3;
            _gl.clearBufferiv(_gl.COLOR, 0, intClearColor);
          }
        } else {
          bits2 |= _gl.COLOR_BUFFER_BIT;
        }
      }
      if (depth2) {
        bits2 |= _gl.DEPTH_BUFFER_BIT;
      }
      if (stencil2) {
        bits2 |= _gl.STENCIL_BUFFER_BIT;
        this.state.buffers.stencil.setMask(4294967295);
      }
      _gl.clear(bits2);
    };
    this.clearColor = function() {
      this.clear(true, false, false);
    };
    this.clearDepth = function() {
      this.clear(false, true, false);
    };
    this.clearStencil = function() {
      this.clear(false, false, true);
    };
    this.dispose = function() {
      canvas.removeEventListener("webglcontextlost", onContextLost, false);
      canvas.removeEventListener("webglcontextrestored", onContextRestore, false);
      canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false);
      background.dispose();
      renderLists.dispose();
      renderStates.dispose();
      properties.dispose();
      cubemaps.dispose();
      cubeuvmaps.dispose();
      objects.dispose();
      bindingStates.dispose();
      uniformsGroups.dispose();
      programCache.dispose();
      xr.dispose();
      xr.removeEventListener("sessionstart", onXRSessionStart);
      xr.removeEventListener("sessionend", onXRSessionEnd);
      animation.stop();
    };
    function onContextLost(event) {
      event.preventDefault();
      console.log("THREE.WebGLRenderer: Context Lost.");
      _isContextLost = true;
    }
    function onContextRestore() {
      console.log("THREE.WebGLRenderer: Context Restored.");
      _isContextLost = false;
      const infoAutoReset = info.autoReset;
      const shadowMapEnabled = shadowMap.enabled;
      const shadowMapAutoUpdate = shadowMap.autoUpdate;
      const shadowMapNeedsUpdate = shadowMap.needsUpdate;
      const shadowMapType = shadowMap.type;
      initGLContext();
      info.autoReset = infoAutoReset;
      shadowMap.enabled = shadowMapEnabled;
      shadowMap.autoUpdate = shadowMapAutoUpdate;
      shadowMap.needsUpdate = shadowMapNeedsUpdate;
      shadowMap.type = shadowMapType;
    }
    function onContextCreationError(event) {
      console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage);
    }
    function onMaterialDispose(event) {
      const material = event.target;
      material.removeEventListener("dispose", onMaterialDispose);
      deallocateMaterial(material);
    }
    function deallocateMaterial(material) {
      releaseMaterialProgramReferences(material);
      properties.remove(material);
    }
    function releaseMaterialProgramReferences(material) {
      const programs = properties.get(material).programs;
      if (programs !== void 0) {
        programs.forEach(function(program) {
          programCache.releaseProgram(program);
        });
        if (material.isShaderMaterial) {
          programCache.releaseShaderCache(material);
        }
      }
    }
    this.renderBufferDirect = function(camera, scene, geometry, material, object, group) {
      if (scene === null) scene = _emptyScene;
      const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
      const program = setProgram(camera, scene, geometry, material, object);
      state.setMaterial(material, frontFaceCW);
      let index = geometry.index;
      let rangeFactor = 1;
      if (material.wireframe === true) {
        index = geometries.getWireframeAttribute(geometry);
        if (index === void 0) return;
        rangeFactor = 2;
      }
      const drawRange = geometry.drawRange;
      const position = geometry.attributes.position;
      let drawStart = drawRange.start * rangeFactor;
      let drawEnd = (drawRange.start + drawRange.count) * rangeFactor;
      if (group !== null) {
        drawStart = Math.max(drawStart, group.start * rangeFactor);
        drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor);
      }
      if (index !== null) {
        drawStart = Math.max(drawStart, 0);
        drawEnd = Math.min(drawEnd, index.count);
      } else if (position !== void 0 && position !== null) {
        drawStart = Math.max(drawStart, 0);
        drawEnd = Math.min(drawEnd, position.count);
      }
      const drawCount = drawEnd - drawStart;
      if (drawCount < 0 || drawCount === Infinity) return;
      bindingStates.setup(object, material, program, geometry, index);
      let attribute;
      let renderer = bufferRenderer;
      if (index !== null) {
        attribute = attributes.get(index);
        renderer = indexedBufferRenderer;
        renderer.setIndex(attribute);
      }
      if (object.isMesh) {
        if (material.wireframe === true) {
          state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
          renderer.setMode(_gl.LINES);
        } else {
          renderer.setMode(_gl.TRIANGLES);
        }
      } else if (object.isLine) {
        let lineWidth = material.linewidth;
        if (lineWidth === void 0) lineWidth = 1;
        state.setLineWidth(lineWidth * getTargetPixelRatio());
        if (object.isLineSegments) {
          renderer.setMode(_gl.LINES);
        } else if (object.isLineLoop) {
          renderer.setMode(_gl.LINE_LOOP);
        } else {
          renderer.setMode(_gl.LINE_STRIP);
        }
      } else if (object.isPoints) {
        renderer.setMode(_gl.POINTS);
      } else if (object.isSprite) {
        renderer.setMode(_gl.TRIANGLES);
      }
      if (object.isBatchedMesh) {
        if (object._multiDrawInstances !== null) {
          renderer.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances);
        } else {
          if (!extensions.get("WEBGL_multi_draw")) {
            const starts = object._multiDrawStarts;
            const counts = object._multiDrawCounts;
            const drawCount2 = object._multiDrawCount;
            const bytesPerElement = index ? attributes.get(index).bytesPerElement : 1;
            const uniforms = properties.get(material).currentProgram.getUniforms();
            for (let i2 = 0; i2 < drawCount2; i2++) {
              uniforms.setValue(_gl, "_gl_DrawID", i2);
              renderer.render(starts[i2] / bytesPerElement, counts[i2]);
            }
          } else {
            renderer.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount);
          }
        }
      } else if (object.isInstancedMesh) {
        renderer.renderInstances(drawStart, drawCount, object.count);
      } else if (geometry.isInstancedBufferGeometry) {
        const maxInstanceCount = geometry._maxInstanceCount !== void 0 ? geometry._maxInstanceCount : Infinity;
        const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount);
        renderer.renderInstances(drawStart, drawCount, instanceCount);
      } else {
        renderer.render(drawStart, drawCount);
      }
    };
    function prepareMaterial(material, scene, object) {
      if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) {
        material.side = BackSide;
        material.needsUpdate = true;
        getProgram(material, scene, object);
        material.side = FrontSide;
        material.needsUpdate = true;
        getProgram(material, scene, object);
        material.side = DoubleSide;
      } else {
        getProgram(material, scene, object);
      }
    }
    this.compile = function(scene, camera, targetScene = null) {
      if (targetScene === null) targetScene = scene;
      currentRenderState = renderStates.get(targetScene);
      currentRenderState.init(camera);
      renderStateStack.push(currentRenderState);
      targetScene.traverseVisible(function(object) {
        if (object.isLight && object.layers.test(camera.layers)) {
          currentRenderState.pushLight(object);
          if (object.castShadow) {
            currentRenderState.pushShadow(object);
          }
        }
      });
      if (scene !== targetScene) {
        scene.traverseVisible(function(object) {
          if (object.isLight && object.layers.test(camera.layers)) {
            currentRenderState.pushLight(object);
            if (object.castShadow) {
              currentRenderState.pushShadow(object);
            }
          }
        });
      }
      currentRenderState.setupLights();
      const materials2 = /* @__PURE__ */ new Set();
      scene.traverse(function(object) {
        if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) {
          return;
        }
        const material = object.material;
        if (material) {
          if (Array.isArray(material)) {
            for (let i2 = 0; i2 < material.length; i2++) {
              const material2 = material[i2];
              prepareMaterial(material2, targetScene, object);
              materials2.add(material2);
            }
          } else {
            prepareMaterial(material, targetScene, object);
            materials2.add(material);
          }
        }
      });
      renderStateStack.pop();
      currentRenderState = null;
      return materials2;
    };
    this.compileAsync = function(scene, camera, targetScene = null) {
      const materials2 = this.compile(scene, camera, targetScene);
      return new Promise((resolve2) => {
        function checkMaterialsReady() {
          materials2.forEach(function(material) {
            const materialProperties = properties.get(material);
            const program = materialProperties.currentProgram;
            if (program.isReady()) {
              materials2.delete(material);
            }
          });
          if (materials2.size === 0) {
            resolve2(scene);
            return;
          }
          setTimeout(checkMaterialsReady, 10);
        }
        if (extensions.get("KHR_parallel_shader_compile") !== null) {
          checkMaterialsReady();
        } else {
          setTimeout(checkMaterialsReady, 10);
        }
      });
    };
    let onAnimationFrameCallback = null;
    function onAnimationFrame(time) {
      if (onAnimationFrameCallback) onAnimationFrameCallback(time);
    }
    function onXRSessionStart() {
      animation.stop();
    }
    function onXRSessionEnd() {
      animation.start();
    }
    const animation = new WebGLAnimation();
    animation.setAnimationLoop(onAnimationFrame);
    if (typeof self !== "undefined") animation.setContext(self);
    this.setAnimationLoop = function(callback) {
      onAnimationFrameCallback = callback;
      xr.setAnimationLoop(callback);
      callback === null ? animation.stop() : animation.start();
    };
    xr.addEventListener("sessionstart", onXRSessionStart);
    xr.addEventListener("sessionend", onXRSessionEnd);
    this.render = function(scene, camera) {
      if (camera !== void 0 && camera.isCamera !== true) {
        console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");
        return;
      }
      if (_isContextLost === true) return;
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      if (xr.enabled === true && xr.isPresenting === true) {
        if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
        camera = xr.getCamera();
      }
      if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
      currentRenderState = renderStates.get(scene, renderStateStack.length);
      currentRenderState.init(camera);
      renderStateStack.push(currentRenderState);
      _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
      _frustum2.setFromProjectionMatrix(_projScreenMatrix2);
      _localClippingEnabled = this.localClippingEnabled;
      _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled);
      currentRenderList = renderLists.get(scene, renderListStack.length);
      currentRenderList.init();
      renderListStack.push(currentRenderList);
      if (xr.enabled === true && xr.isPresenting === true) {
        const depthSensingMesh = _this.xr.getDepthSensingMesh();
        if (depthSensingMesh !== null) {
          projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects);
        }
      }
      projectObject(scene, camera, 0, _this.sortObjects);
      currentRenderList.finish();
      if (_this.sortObjects === true) {
        currentRenderList.sort(_opaqueSort, _transparentSort);
      }
      _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
      if (_renderBackground) {
        background.addToRenderList(currentRenderList, scene);
      }
      this.info.render.frame++;
      if (_clippingEnabled === true) clipping.beginShadows();
      const shadowsArray = currentRenderState.state.shadowsArray;
      shadowMap.render(shadowsArray, scene, camera);
      if (_clippingEnabled === true) clipping.endShadows();
      if (this.info.autoReset === true) this.info.reset();
      const opaqueObjects = currentRenderList.opaque;
      const transmissiveObjects = currentRenderList.transmissive;
      currentRenderState.setupLights();
      if (camera.isArrayCamera) {
        const cameras = camera.cameras;
        if (transmissiveObjects.length > 0) {
          for (let i2 = 0, l2 = cameras.length; i2 < l2; i2++) {
            const camera2 = cameras[i2];
            renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2);
          }
        }
        if (_renderBackground) background.render(scene);
        for (let i2 = 0, l2 = cameras.length; i2 < l2; i2++) {
          const camera2 = cameras[i2];
          renderScene(currentRenderList, scene, camera2, camera2.viewport);
        }
      } else {
        if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera);
        if (_renderBackground) background.render(scene);
        renderScene(currentRenderList, scene, camera);
      }
      if (_currentRenderTarget !== null) {
        textures.updateMultisampleRenderTarget(_currentRenderTarget);
        textures.updateRenderTargetMipmap(_currentRenderTarget);
      }
      if (scene.isScene === true) scene.onAfterRender(_this, scene, camera);
      bindingStates.resetDefaultState();
      _currentMaterialId = -1;
      _currentCamera = null;
      renderStateStack.pop();
      if (renderStateStack.length > 0) {
        currentRenderState = renderStateStack[renderStateStack.length - 1];
        if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera);
      } else {
        currentRenderState = null;
      }
      renderListStack.pop();
      if (renderListStack.length > 0) {
        currentRenderList = renderListStack[renderListStack.length - 1];
      } else {
        currentRenderList = null;
      }
    };
    function projectObject(object, camera, groupOrder, sortObjects) {
      if (object.visible === false) return;
      const visible = object.layers.test(camera.layers);
      if (visible) {
        if (object.isGroup) {
          groupOrder = object.renderOrder;
        } else if (object.isLOD) {
          if (object.autoUpdate === true) object.update(camera);
        } else if (object.isLight) {
          currentRenderState.pushLight(object);
          if (object.castShadow) {
            currentRenderState.pushShadow(object);
          }
        } else if (object.isSprite) {
          if (!object.frustumCulled || _frustum2.intersectsSprite(object)) {
            if (sortObjects) {
              _vector4.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2);
            }
            const geometry = objects.update(object);
            const material = object.material;
            if (material.visible) {
              currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null);
            }
          }
        } else if (object.isMesh || object.isLine || object.isPoints) {
          if (!object.frustumCulled || _frustum2.intersectsObject(object)) {
            const geometry = objects.update(object);
            const material = object.material;
            if (sortObjects) {
              if (object.boundingSphere !== void 0) {
                if (object.boundingSphere === null) object.computeBoundingSphere();
                _vector4.copy(object.boundingSphere.center);
              } else {
                if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
                _vector4.copy(geometry.boundingSphere.center);
              }
              _vector4.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2);
            }
            if (Array.isArray(material)) {
              const groups = geometry.groups;
              for (let i2 = 0, l2 = groups.length; i2 < l2; i2++) {
                const group = groups[i2];
                const groupMaterial = material[group.materialIndex];
                if (groupMaterial && groupMaterial.visible) {
                  currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector4.z, group);
                }
              }
            } else if (material.visible) {
              currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null);
            }
          }
        }
      }
      const children = object.children;
      for (let i2 = 0, l2 = children.length; i2 < l2; i2++) {
        projectObject(children[i2], camera, groupOrder, sortObjects);
      }
    }
    function renderScene(currentRenderList2, scene, camera, viewport) {
      const opaqueObjects = currentRenderList2.opaque;
      const transmissiveObjects = currentRenderList2.transmissive;
      const transparentObjects = currentRenderList2.transparent;
      currentRenderState.setupLightsView(camera);
      if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, camera);
      if (viewport) state.viewport(_currentViewport.copy(viewport));
      if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
      if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
      if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
      state.buffers.depth.setTest(true);
      state.buffers.depth.setMask(true);
      state.buffers.color.setMask(true);
      state.setPolygonOffset(false);
    }
    function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) {
      const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
      if (overrideMaterial !== null) {
        return;
      }
      if (currentRenderState.state.transmissionRenderTarget[camera.id] === void 0) {
        currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, {
          generateMipmaps: true,
          type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType : UnsignedByteType,
          minFilter: LinearMipmapLinearFilter,
          samples: 4,
          stencilBuffer: stencil,
          resolveDepthBuffer: false,
          resolveStencilBuffer: false,
          colorSpace: ColorManagement.workingColorSpace
        });
      }
      const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id];
      const activeViewport = camera.viewport || _currentViewport;
      transmissionRenderTarget.setSize(activeViewport.z, activeViewport.w);
      const currentRenderTarget = _this.getRenderTarget();
      _this.setRenderTarget(transmissionRenderTarget);
      _this.getClearColor(_currentClearColor);
      _currentClearAlpha = _this.getClearAlpha();
      if (_currentClearAlpha < 1) _this.setClearColor(16777215, 0.5);
      _this.clear();
      if (_renderBackground) background.render(scene);
      const currentToneMapping = _this.toneMapping;
      _this.toneMapping = NoToneMapping;
      const currentCameraViewport = camera.viewport;
      if (camera.viewport !== void 0) camera.viewport = void 0;
      currentRenderState.setupLightsView(camera);
      if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, camera);
      renderObjects(opaqueObjects, scene, camera);
      textures.updateMultisampleRenderTarget(transmissionRenderTarget);
      textures.updateRenderTargetMipmap(transmissionRenderTarget);
      if (extensions.has("WEBGL_multisampled_render_to_texture") === false) {
        let renderTargetNeedsUpdate = false;
        for (let i2 = 0, l2 = transmissiveObjects.length; i2 < l2; i2++) {
          const renderItem = transmissiveObjects[i2];
          const object = renderItem.object;
          const geometry = renderItem.geometry;
          const material = renderItem.material;
          const group = renderItem.group;
          if (material.side === DoubleSide && object.layers.test(camera.layers)) {
            const currentSide = material.side;
            material.side = BackSide;
            material.needsUpdate = true;
            renderObject(object, scene, camera, geometry, material, group);
            material.side = currentSide;
            material.needsUpdate = true;
            renderTargetNeedsUpdate = true;
          }
        }
        if (renderTargetNeedsUpdate === true) {
          textures.updateMultisampleRenderTarget(transmissionRenderTarget);
          textures.updateRenderTargetMipmap(transmissionRenderTarget);
        }
      }
      _this.setRenderTarget(currentRenderTarget);
      _this.setClearColor(_currentClearColor, _currentClearAlpha);
      if (currentCameraViewport !== void 0) camera.viewport = currentCameraViewport;
      _this.toneMapping = currentToneMapping;
    }
    function renderObjects(renderList, scene, camera) {
      const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
      for (let i2 = 0, l2 = renderList.length; i2 < l2; i2++) {
        const renderItem = renderList[i2];
        const object = renderItem.object;
        const geometry = renderItem.geometry;
        const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
        const group = renderItem.group;
        if (object.layers.test(camera.layers)) {
          renderObject(object, scene, camera, geometry, material, group);
        }
      }
    }
    function renderObject(object, scene, camera, geometry, material, group) {
      object.onBeforeRender(_this, scene, camera, geometry, material, group);
      object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
      object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
      material.onBeforeRender(_this, scene, camera, geometry, object, group);
      if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) {
        material.side = BackSide;
        material.needsUpdate = true;
        _this.renderBufferDirect(camera, scene, geometry, material, object, group);
        material.side = FrontSide;
        material.needsUpdate = true;
        _this.renderBufferDirect(camera, scene, geometry, material, object, group);
        material.side = DoubleSide;
      } else {
        _this.renderBufferDirect(camera, scene, geometry, material, object, group);
      }
      object.onAfterRender(_this, scene, camera, geometry, material, group);
    }
    function getProgram(material, scene, object) {
      if (scene.isScene !== true) scene = _emptyScene;
      const materialProperties = properties.get(material);
      const lights = currentRenderState.state.lights;
      const shadowsArray = currentRenderState.state.shadowsArray;
      const lightsStateVersion = lights.state.version;
      const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
      const programCacheKey = programCache.getProgramCacheKey(parameters2);
      let programs = materialProperties.programs;
      materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
      materialProperties.fog = scene.fog;
      materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
      materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation;
      if (programs === void 0) {
        material.addEventListener("dispose", onMaterialDispose);
        programs = /* @__PURE__ */ new Map();
        materialProperties.programs = programs;
      }
      let program = programs.get(programCacheKey);
      if (program !== void 0) {
        if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
          updateCommonMaterialProperties(material, parameters2);
          return program;
        }
      } else {
        parameters2.uniforms = programCache.getUniforms(material);
        material.onBeforeCompile(parameters2, _this);
        program = programCache.acquireProgram(parameters2, programCacheKey);
        programs.set(programCacheKey, program);
        materialProperties.uniforms = parameters2.uniforms;
      }
      const uniforms = materialProperties.uniforms;
      if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
        uniforms.clippingPlanes = clipping.uniform;
      }
      updateCommonMaterialProperties(material, parameters2);
      materialProperties.needsLights = materialNeedsLights(material);
      materialProperties.lightsStateVersion = lightsStateVersion;
      if (materialProperties.needsLights) {
        uniforms.ambientLightColor.value = lights.state.ambient;
        uniforms.lightProbe.value = lights.state.probe;
        uniforms.directionalLights.value = lights.state.directional;
        uniforms.directionalLightShadows.value = lights.state.directionalShadow;
        uniforms.spotLights.value = lights.state.spot;
        uniforms.spotLightShadows.value = lights.state.spotShadow;
        uniforms.rectAreaLights.value = lights.state.rectArea;
        uniforms.ltc_1.value = lights.state.rectAreaLTC1;
        uniforms.ltc_2.value = lights.state.rectAreaLTC2;
        uniforms.pointLights.value = lights.state.point;
        uniforms.pointLightShadows.value = lights.state.pointShadow;
        uniforms.hemisphereLights.value = lights.state.hemi;
        uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
        uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
        uniforms.spotShadowMap.value = lights.state.spotShadowMap;
        uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
        uniforms.spotLightMap.value = lights.state.spotLightMap;
        uniforms.pointShadowMap.value = lights.state.pointShadowMap;
        uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
      }
      materialProperties.currentProgram = program;
      materialProperties.uniformsList = null;
      return program;
    }
    function getUniformList(materialProperties) {
      if (materialProperties.uniformsList === null) {
        const progUniforms = materialProperties.currentProgram.getUniforms();
        materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms);
      }
      return materialProperties.uniformsList;
    }
    function updateCommonMaterialProperties(material, parameters2) {
      const materialProperties = properties.get(material);
      materialProperties.outputColorSpace = parameters2.outputColorSpace;
      materialProperties.batching = parameters2.batching;
      materialProperties.batchingColor = parameters2.batchingColor;
      materialProperties.instancing = parameters2.instancing;
      materialProperties.instancingColor = parameters2.instancingColor;
      materialProperties.instancingMorph = parameters2.instancingMorph;
      materialProperties.skinning = parameters2.skinning;
      materialProperties.morphTargets = parameters2.morphTargets;
      materialProperties.morphNormals = parameters2.morphNormals;
      materialProperties.morphColors = parameters2.morphColors;
      materialProperties.morphTargetsCount = parameters2.morphTargetsCount;
      materialProperties.numClippingPlanes = parameters2.numClippingPlanes;
      materialProperties.numIntersection = parameters2.numClipIntersection;
      materialProperties.vertexAlphas = parameters2.vertexAlphas;
      materialProperties.vertexTangents = parameters2.vertexTangents;
      materialProperties.toneMapping = parameters2.toneMapping;
    }
    function setProgram(camera, scene, geometry, material, object) {
      if (scene.isScene !== true) scene = _emptyScene;
      textures.resetTextureUnits();
      const fog = scene.fog;
      const environment = material.isMeshStandardMaterial ? scene.environment : null;
      const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace;
      const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
      const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
      const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0);
      const morphTargets = !!geometry.morphAttributes.position;
      const morphNormals = !!geometry.morphAttributes.normal;
      const morphColors = !!geometry.morphAttributes.color;
      let toneMapping = NoToneMapping;
      if (material.toneMapped) {
        if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) {
          toneMapping = _this.toneMapping;
        }
      }
      const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
      const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0;
      const materialProperties = properties.get(material);
      const lights = currentRenderState.state.lights;
      if (_clippingEnabled === true) {
        if (_localClippingEnabled === true || camera !== _currentCamera) {
          const useCache = camera === _currentCamera && material.id === _currentMaterialId;
          clipping.setState(material, camera, useCache);
        }
      }
      let needsProgramChange = false;
      if (material.version === materialProperties.__version) {
        if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
          needsProgramChange = true;
        } else if (materialProperties.outputColorSpace !== colorSpace) {
          needsProgramChange = true;
        } else if (object.isBatchedMesh && materialProperties.batching === false) {
          needsProgramChange = true;
        } else if (!object.isBatchedMesh && materialProperties.batching === true) {
          needsProgramChange = true;
        } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) {
          needsProgramChange = true;
        } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) {
          needsProgramChange = true;
        } else if (object.isInstancedMesh && materialProperties.instancing === false) {
          needsProgramChange = true;
        } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
          needsProgramChange = true;
        } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
          needsProgramChange = true;
        } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
          needsProgramChange = true;
        } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) {
          needsProgramChange = true;
        } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) {
          needsProgramChange = true;
        } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) {
          needsProgramChange = true;
        } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) {
          needsProgramChange = true;
        } else if (materialProperties.envMap !== envMap) {
          needsProgramChange = true;
        } else if (material.fog === true && materialProperties.fog !== fog) {
          needsProgramChange = true;
        } else if (materialProperties.numClippingPlanes !== void 0 && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
          needsProgramChange = true;
        } else if (materialProperties.vertexAlphas !== vertexAlphas) {
          needsProgramChange = true;
        } else if (materialProperties.vertexTangents !== vertexTangents) {
          needsProgramChange = true;
        } else if (materialProperties.morphTargets !== morphTargets) {
          needsProgramChange = true;
        } else if (materialProperties.morphNormals !== morphNormals) {
          needsProgramChange = true;
        } else if (materialProperties.morphColors !== morphColors) {
          needsProgramChange = true;
        } else if (materialProperties.toneMapping !== toneMapping) {
          needsProgramChange = true;
        } else if (materialProperties.morphTargetsCount !== morphTargetsCount) {
          needsProgramChange = true;
        }
      } else {
        needsProgramChange = true;
        materialProperties.__version = material.version;
      }
      let program = materialProperties.currentProgram;
      if (needsProgramChange === true) {
        program = getProgram(material, scene, object);
      }
      let refreshProgram = false;
      let refreshMaterial = false;
      let refreshLights = false;
      const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms;
      if (state.useProgram(program.program)) {
        refreshProgram = true;
        refreshMaterial = true;
        refreshLights = true;
      }
      if (material.id !== _currentMaterialId) {
        _currentMaterialId = material.id;
        refreshMaterial = true;
      }
      if (refreshProgram || _currentCamera !== camera) {
        const reverseDepthBuffer2 = state.buffers.depth.getReversed();
        if (reverseDepthBuffer2) {
          _currentProjectionMatrix.copy(camera.projectionMatrix);
          toNormalizedProjectionMatrix(_currentProjectionMatrix);
          toReversedProjectionMatrix(_currentProjectionMatrix);
          p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix);
        } else {
          p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix);
        }
        p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse);
        const uCamPos = p_uniforms.map.cameraPosition;
        if (uCamPos !== void 0) {
          uCamPos.setValue(_gl, _vector32.setFromMatrixPosition(camera.matrixWorld));
        }
        if (capabilities.logarithmicDepthBuffer) {
          p_uniforms.setValue(
            _gl,
            "logDepthBufFC",
            2 / (Math.log(camera.far + 1) / Math.LN2)
          );
        }
        if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
          p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true);
        }
        if (_currentCamera !== camera) {
          _currentCamera = camera;
          refreshMaterial = true;
          refreshLights = true;
        }
      }
      if (object.isSkinnedMesh) {
        p_uniforms.setOptional(_gl, object, "bindMatrix");
        p_uniforms.setOptional(_gl, object, "bindMatrixInverse");
        const skeleton = object.skeleton;
        if (skeleton) {
          if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
          p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures);
        }
      }
      if (object.isBatchedMesh) {
        p_uniforms.setOptional(_gl, object, "batchingTexture");
        p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures);
        p_uniforms.setOptional(_gl, object, "batchingIdTexture");
        p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures);
        p_uniforms.setOptional(_gl, object, "batchingColorTexture");
        if (object._colorsTexture !== null) {
          p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures);
        }
      }
      const morphAttributes = geometry.morphAttributes;
      if (morphAttributes.position !== void 0 || morphAttributes.normal !== void 0 || morphAttributes.color !== void 0) {
        morphtargets.update(object, geometry, program);
      }
      if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
        materialProperties.receiveShadow = object.receiveShadow;
        p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow);
      }
      if (material.isMeshGouraudMaterial && material.envMap !== null) {
        m_uniforms.envMap.value = envMap;
        m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
      }
      if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) {
        m_uniforms.envMapIntensity.value = scene.environmentIntensity;
      }
      if (refreshMaterial) {
        p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure);
        if (materialProperties.needsLights) {
          markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
        }
        if (fog && material.fog === true) {
          materials.refreshFogUniforms(m_uniforms, fog);
        }
        materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]);
        WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures);
      }
      if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
        WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures);
        material.uniformsNeedUpdate = false;
      }
      if (material.isSpriteMaterial) {
        p_uniforms.setValue(_gl, "center", object.center);
      }
      p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix);
      p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix);
      p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld);
      if (material.isShaderMaterial || material.isRawShaderMaterial) {
        const groups = material.uniformsGroups;
        for (let i2 = 0, l2 = groups.length; i2 < l2; i2++) {
          const group = groups[i2];
          uniformsGroups.update(group, program);
          uniformsGroups.bind(group, program);
        }
      }
      return program;
    }
    function markUniformsLightsNeedsUpdate(uniforms, value) {
      uniforms.ambientLightColor.needsUpdate = value;
      uniforms.lightProbe.needsUpdate = value;
      uniforms.directionalLights.needsUpdate = value;
      uniforms.directionalLightShadows.needsUpdate = value;
      uniforms.pointLights.needsUpdate = value;
      uniforms.pointLightShadows.needsUpdate = value;
      uniforms.spotLights.needsUpdate = value;
      uniforms.spotLightShadows.needsUpdate = value;
      uniforms.rectAreaLights.needsUpdate = value;
      uniforms.hemisphereLights.needsUpdate = value;
    }
    function materialNeedsLights(material) {
      return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
    }
    this.getActiveCubeFace = function() {
      return _currentActiveCubeFace;
    };
    this.getActiveMipmapLevel = function() {
      return _currentActiveMipmapLevel;
    };
    this.getRenderTarget = function() {
      return _currentRenderTarget;
    };
    this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) {
      properties.get(renderTarget.texture).__webglTexture = colorTexture;
      properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
      const renderTargetProperties = properties.get(renderTarget);
      renderTargetProperties.__hasExternalTextures = true;
      renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === void 0;
      if (!renderTargetProperties.__autoAllocateDepthBuffer) {
        if (extensions.has("WEBGL_multisampled_render_to_texture") === true) {
          console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided");
          renderTargetProperties.__useRenderToTexture = false;
        }
      }
    };
    this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) {
      const renderTargetProperties = properties.get(renderTarget);
      renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
      renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === void 0;
    };
    this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
      _currentRenderTarget = renderTarget;
      _currentActiveCubeFace = activeCubeFace;
      _currentActiveMipmapLevel = activeMipmapLevel;
      let useDefaultFramebuffer = true;
      let framebuffer = null;
      let isCube = false;
      let isRenderTarget3D = false;
      if (renderTarget) {
        const renderTargetProperties = properties.get(renderTarget);
        if (renderTargetProperties.__useDefaultFramebuffer !== void 0) {
          state.bindFramebuffer(_gl.FRAMEBUFFER, null);
          useDefaultFramebuffer = false;
        } else if (renderTargetProperties.__webglFramebuffer === void 0) {
          textures.setupRenderTarget(renderTarget);
        } else if (renderTargetProperties.__hasExternalTextures) {
          textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
        } else if (renderTarget.depthBuffer) {
          const depthTexture = renderTarget.depthTexture;
          if (renderTargetProperties.__boundDepthTexture !== depthTexture) {
            if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) {
              throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");
            }
            textures.setupDepthRenderbuffer(renderTarget);
          }
        }
        const texture = renderTarget.texture;
        if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
          isRenderTarget3D = true;
        }
        const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
        if (renderTarget.isWebGLCubeRenderTarget) {
          if (Array.isArray(__webglFramebuffer[activeCubeFace])) {
            framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel];
          } else {
            framebuffer = __webglFramebuffer[activeCubeFace];
          }
          isCube = true;
        } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
          framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
        } else {
          if (Array.isArray(__webglFramebuffer)) {
            framebuffer = __webglFramebuffer[activeMipmapLevel];
          } else {
            framebuffer = __webglFramebuffer;
          }
        }
        _currentViewport.copy(renderTarget.viewport);
        _currentScissor.copy(renderTarget.scissor);
        _currentScissorTest = renderTarget.scissorTest;
      } else {
        _currentViewport.copy(_viewport2).multiplyScalar(_pixelRatio).floor();
        _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
        _currentScissorTest = _scissorTest;
      }
      const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
      if (framebufferBound && useDefaultFramebuffer) {
        state.drawBuffers(renderTarget, framebuffer);
      }
      state.viewport(_currentViewport);
      state.scissor(_currentScissor);
      state.setScissorTest(_currentScissorTest);
      if (isCube) {
        const textureProperties = properties.get(renderTarget.texture);
        _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
      } else if (isRenderTarget3D) {
        const textureProperties = properties.get(renderTarget.texture);
        const layer = activeCubeFace || 0;
        _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
      }
      _currentMaterialId = -1;
    };
    this.readRenderTargetPixels = function(renderTarget, x, y2, width, height, buffer, activeCubeFaceIndex) {
      if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
        console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
        return;
      }
      let framebuffer = properties.get(renderTarget).__webglFramebuffer;
      if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) {
        framebuffer = framebuffer[activeCubeFaceIndex];
      }
      if (framebuffer) {
        state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
        try {
          const texture = renderTarget.texture;
          const textureFormat = texture.format;
          const textureType = texture.type;
          if (!capabilities.textureFormatReadable(textureFormat)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");
            return;
          }
          if (!capabilities.textureTypeReadable(textureType)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");
            return;
          }
          if (x >= 0 && x <= renderTarget.width - width && (y2 >= 0 && y2 <= renderTarget.height - height)) {
            _gl.readPixels(x, y2, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
          }
        } finally {
          const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
          state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2);
        }
      }
    };
    this.readRenderTargetPixelsAsync = async function(renderTarget, x, y2, width, height, buffer, activeCubeFaceIndex) {
      if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
        throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
      }
      let framebuffer = properties.get(renderTarget).__webglFramebuffer;
      if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) {
        framebuffer = framebuffer[activeCubeFaceIndex];
      }
      if (framebuffer) {
        const texture = renderTarget.texture;
        const textureFormat = texture.format;
        const textureType = texture.type;
        if (!capabilities.textureFormatReadable(textureFormat)) {
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");
        }
        if (!capabilities.textureTypeReadable(textureType)) {
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");
        }
        if (x >= 0 && x <= renderTarget.width - width && (y2 >= 0 && y2 <= renderTarget.height - height)) {
          state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
          const glBuffer = _gl.createBuffer();
          _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer);
          _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ);
          _gl.readPixels(x, y2, width, height, utils.convert(textureFormat), utils.convert(textureType), 0);
          const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
          state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer);
          const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
          _gl.flush();
          await probeAsync(_gl, sync, 4);
          _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer);
          _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer);
          _gl.deleteBuffer(glBuffer);
          _gl.deleteSync(sync);
          return buffer;
        } else {
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
        }
      }
    };
    this.copyFramebufferToTexture = function(texture, position = null, level = 0) {
      if (texture.isTexture !== true) {
        warnOnce("WebGLRenderer: copyFramebufferToTexture function signature has changed.");
        position = arguments[0] || null;
        texture = arguments[1];
      }
      const levelScale = Math.pow(2, -level);
      const width = Math.floor(texture.image.width * levelScale);
      const height = Math.floor(texture.image.height * levelScale);
      const x = position !== null ? position.x : 0;
      const y2 = position !== null ? position.y : 0;
      textures.setTexture2D(texture, 0);
      _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y2, width, height);
      state.unbindTexture();
    };
    const _srcFramebuffer = _gl.createFramebuffer();
    const _dstFramebuffer = _gl.createFramebuffer();
    this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) {
      if (srcTexture.isTexture !== true) {
        warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed.");
        dstPosition = arguments[0] || null;
        srcTexture = arguments[1];
        dstTexture = arguments[2];
        dstLevel = arguments[3] || 0;
        srcRegion = null;
      }
      if (dstLevel === null) {
        if (srcLevel !== 0) {
          warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.");
          dstLevel = srcLevel;
          srcLevel = 0;
        } else {
          dstLevel = 0;
        }
      }
      let width, height, depth2, minX, minY, minZ;
      let dstX, dstY, dstZ;
      const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image;
      if (srcRegion !== null) {
        width = srcRegion.max.x - srcRegion.min.x;
        height = srcRegion.max.y - srcRegion.min.y;
        depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
        minX = srcRegion.min.x;
        minY = srcRegion.min.y;
        minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
      } else {
        const levelScale = Math.pow(2, -srcLevel);
        width = Math.floor(image.width * levelScale);
        height = Math.floor(image.height * levelScale);
        if (srcTexture.isDataArrayTexture) {
          depth2 = image.depth;
        } else if (srcTexture.isData3DTexture) {
          depth2 = Math.floor(image.depth * levelScale);
        } else {
          depth2 = 1;
        }
        minX = 0;
        minY = 0;
        minZ = 0;
      }
      if (dstPosition !== null) {
        dstX = dstPosition.x;
        dstY = dstPosition.y;
        dstZ = dstPosition.z;
      } else {
        dstX = 0;
        dstY = 0;
        dstZ = 0;
      }
      const glFormat = utils.convert(dstTexture.format);
      const glType = utils.convert(dstTexture.type);
      let glTarget;
      if (dstTexture.isData3DTexture) {
        textures.setTexture3D(dstTexture, 0);
        glTarget = _gl.TEXTURE_3D;
      } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) {
        textures.setTexture2DArray(dstTexture, 0);
        glTarget = _gl.TEXTURE_2D_ARRAY;
      } else {
        textures.setTexture2D(dstTexture, 0);
        glTarget = _gl.TEXTURE_2D;
      }
      _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
      _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
      _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
      const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
      const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
      const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
      const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
      const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
      _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
      _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
      _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX);
      _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY);
      _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ);
      const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
      const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
      if (srcTexture.isDepthTexture) {
        const srcTextureProperties = properties.get(srcTexture);
        const dstTextureProperties = properties.get(dstTexture);
        const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget);
        const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget);
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer);
        for (let i2 = 0; i2 < depth2; i2++) {
          if (isSrc3D) {
            _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i2);
            _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i2);
          }
          _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST);
        }
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null);
      } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) {
        const srcTextureProperties = properties.get(srcTexture);
        const dstTextureProperties = properties.get(dstTexture);
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer);
        for (let i2 = 0; i2 < depth2; i2++) {
          if (isSrc3D) {
            _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i2);
          } else {
            _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel);
          }
          if (isDst3D) {
            _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i2);
          } else {
            _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel);
          }
          if (srcLevel !== 0) {
            _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST);
          } else if (isDst3D) {
            _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i2, minX, minY, width, height);
          } else {
            _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width, height);
          }
        }
        state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
        state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null);
      } else {
        if (isDst3D) {
          if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
            _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image.data);
          } else if (dstTexture.isCompressedArrayTexture) {
            _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, image.data);
          } else {
            _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image);
          }
        } else {
          if (srcTexture.isDataTexture) {
            _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data);
          } else if (srcTexture.isCompressedTexture) {
            _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data);
          } else {
            _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image);
          }
        }
      }
      _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen);
      _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight);
      _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels);
      _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows);
      _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages);
      if (dstLevel === 0 && dstTexture.generateMipmaps) {
        _gl.generateMipmap(glTarget);
      }
      state.unbindTexture();
    };
    this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) {
      if (srcTexture.isTexture !== true) {
        warnOnce("WebGLRenderer: copyTextureToTexture3D function signature has changed.");
        srcRegion = arguments[0] || null;
        dstPosition = arguments[1] || null;
        srcTexture = arguments[2];
        dstTexture = arguments[3];
        level = arguments[4] || 0;
      }
      warnOnce('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.');
      return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level);
    };
    this.initRenderTarget = function(target) {
      if (properties.get(target).__webglFramebuffer === void 0) {
        textures.setupRenderTarget(target);
      }
    };
    this.initTexture = function(texture) {
      if (texture.isCubeTexture) {
        textures.setTextureCube(texture, 0);
      } else if (texture.isData3DTexture) {
        textures.setTexture3D(texture, 0);
      } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
        textures.setTexture2DArray(texture, 0);
      } else {
        textures.setTexture2D(texture, 0);
      }
      state.unbindTexture();
    };
    this.resetState = function() {
      _currentActiveCubeFace = 0;
      _currentActiveMipmapLevel = 0;
      _currentRenderTarget = null;
      state.reset();
      bindingStates.reset();
    };
    if (typeof __THREE_DEVTOOLS__ !== "undefined") {
      __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
    }
  }
  get coordinateSystem() {
    return WebGLCoordinateSystem;
  }
  get outputColorSpace() {
    return this._outputColorSpace;
  }
  set outputColorSpace(colorSpace) {
    this._outputColorSpace = colorSpace;
    const gl = this.getContext();
    gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace(colorSpace);
    gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  }
}
const THREE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  ACESFilmicToneMapping,
  AddEquation,
  AddOperation,
  AdditiveAnimationBlendMode,
  AdditiveBlending,
  AgXToneMapping,
  AlphaFormat,
  AlwaysCompare,
  AlwaysDepth,
  AlwaysStencilFunc,
  AmbientLight,
  AnimationAction,
  AnimationClip,
  AnimationLoader,
  AnimationMixer,
  AnimationObjectGroup,
  AnimationUtils,
  ArcCurve,
  ArrayCamera,
  ArrowHelper,
  AttachedBindMode,
  Audio,
  AudioAnalyser,
  AudioContext,
  AudioListener,
  AudioLoader,
  AxesHelper,
  BackSide,
  BasicDepthPacking,
  BasicShadowMap,
  BatchedMesh,
  Bone,
  BooleanKeyframeTrack,
  Box2,
  Box3,
  Box3Helper,
  BoxGeometry,
  BoxHelper,
  BufferAttribute,
  BufferGeometry,
  BufferGeometryLoader,
  ByteType,
  Cache,
  Camera,
  CameraHelper,
  CanvasTexture,
  CapsuleGeometry,
  CatmullRomCurve3,
  CineonToneMapping,
  CircleGeometry,
  ClampToEdgeWrapping,
  Clock,
  Color,
  ColorKeyframeTrack,
  ColorManagement,
  CompressedArrayTexture,
  CompressedCubeTexture,
  CompressedTexture,
  CompressedTextureLoader,
  ConeGeometry,
  ConstantAlphaFactor,
  ConstantColorFactor,
  Controls,
  CubeCamera,
  CubeReflectionMapping,
  CubeRefractionMapping,
  CubeTexture,
  CubeTextureLoader,
  CubeUVReflectionMapping,
  CubicBezierCurve,
  CubicBezierCurve3,
  CubicInterpolant,
  CullFaceBack,
  CullFaceFront,
  CullFaceFrontBack,
  CullFaceNone,
  Curve,
  CurvePath,
  CustomBlending,
  CustomToneMapping,
  CylinderGeometry,
  Cylindrical,
  Data3DTexture,
  DataArrayTexture,
  DataTexture,
  DataTextureLoader,
  DataUtils,
  DecrementStencilOp,
  DecrementWrapStencilOp,
  DefaultLoadingManager,
  DepthFormat,
  DepthStencilFormat,
  DepthTexture,
  DetachedBindMode,
  DirectionalLight,
  DirectionalLightHelper,
  DiscreteInterpolant,
  DodecahedronGeometry,
  DoubleSide,
  DstAlphaFactor,
  DstColorFactor,
  DynamicCopyUsage,
  DynamicDrawUsage,
  DynamicReadUsage,
  EdgesGeometry,
  EllipseCurve,
  EqualCompare,
  EqualDepth,
  EqualStencilFunc,
  EquirectangularReflectionMapping,
  EquirectangularRefractionMapping,
  Euler,
  EventDispatcher: EventDispatcher$1,
  ExtrudeGeometry,
  FileLoader,
  Float16BufferAttribute,
  Float32BufferAttribute,
  FloatType,
  Fog,
  FogExp2,
  FramebufferTexture,
  FrontSide,
  Frustum,
  GLBufferAttribute,
  GLSL1,
  GLSL3,
  GreaterCompare,
  GreaterDepth,
  GreaterEqualCompare,
  GreaterEqualDepth,
  GreaterEqualStencilFunc,
  GreaterStencilFunc,
  GridHelper,
  Group,
  HalfFloatType,
  HemisphereLight,
  HemisphereLightHelper,
  IcosahedronGeometry,
  ImageBitmapLoader,
  ImageLoader,
  ImageUtils,
  IncrementStencilOp,
  IncrementWrapStencilOp,
  InstancedBufferAttribute,
  InstancedBufferGeometry,
  InstancedInterleavedBuffer,
  InstancedMesh,
  Int16BufferAttribute,
  Int32BufferAttribute,
  Int8BufferAttribute,
  IntType,
  InterleavedBuffer,
  InterleavedBufferAttribute,
  Interpolant,
  InterpolateDiscrete,
  InterpolateLinear,
  InterpolateSmooth,
  InvertStencilOp,
  KeepStencilOp,
  KeyframeTrack,
  LOD,
  LatheGeometry,
  Layers,
  LessCompare,
  LessDepth,
  LessEqualCompare,
  LessEqualDepth,
  LessEqualStencilFunc,
  LessStencilFunc,
  Light,
  LightProbe,
  Line: Line$1,
  Line3,
  LineBasicMaterial,
  LineCurve,
  LineCurve3,
  LineDashedMaterial,
  LineLoop,
  LineSegments,
  LinearFilter,
  LinearInterpolant,
  LinearMipMapLinearFilter,
  LinearMipMapNearestFilter,
  LinearMipmapLinearFilter,
  LinearMipmapNearestFilter,
  LinearSRGBColorSpace,
  LinearToneMapping,
  LinearTransfer,
  Loader,
  LoaderUtils,
  LoadingManager,
  LoopOnce,
  LoopPingPong,
  LoopRepeat,
  LuminanceAlphaFormat,
  LuminanceFormat,
  MOUSE,
  Material,
  MaterialLoader,
  MathUtils,
  Matrix2,
  Matrix3,
  Matrix4,
  MaxEquation,
  Mesh,
  MeshBasicMaterial,
  MeshDepthMaterial,
  MeshDistanceMaterial,
  MeshLambertMaterial,
  MeshMatcapMaterial,
  MeshNormalMaterial,
  MeshPhongMaterial,
  MeshPhysicalMaterial,
  MeshStandardMaterial,
  MeshToonMaterial,
  MinEquation,
  MirroredRepeatWrapping,
  MixOperation,
  MultiplyBlending,
  MultiplyOperation,
  NearestFilter,
  NearestMipMapLinearFilter,
  NearestMipMapNearestFilter,
  NearestMipmapLinearFilter,
  NearestMipmapNearestFilter,
  NeutralToneMapping,
  NeverCompare,
  NeverDepth,
  NeverStencilFunc,
  NoBlending,
  NoColorSpace,
  NoToneMapping,
  NormalAnimationBlendMode,
  NormalBlending,
  NotEqualCompare,
  NotEqualDepth,
  NotEqualStencilFunc,
  NumberKeyframeTrack,
  Object3D,
  ObjectLoader,
  ObjectSpaceNormalMap,
  OctahedronGeometry,
  OneFactor,
  OneMinusConstantAlphaFactor,
  OneMinusConstantColorFactor,
  OneMinusDstAlphaFactor,
  OneMinusDstColorFactor,
  OneMinusSrcAlphaFactor,
  OneMinusSrcColorFactor,
  OrthographicCamera,
  PCFShadowMap,
  PCFSoftShadowMap,
  PMREMGenerator,
  Path,
  PerspectiveCamera,
  Plane,
  PlaneGeometry,
  PlaneHelper,
  PointLight,
  PointLightHelper,
  Points,
  PointsMaterial,
  PolarGridHelper,
  PolyhedronGeometry,
  PositionalAudio,
  PropertyBinding,
  PropertyMixer,
  QuadraticBezierCurve,
  QuadraticBezierCurve3,
  Quaternion,
  QuaternionKeyframeTrack,
  QuaternionLinearInterpolant,
  RED_GREEN_RGTC2_Format,
  RED_RGTC1_Format,
  REVISION,
  RGBADepthPacking,
  RGBAFormat,
  RGBAIntegerFormat,
  RGBA_ASTC_10x10_Format,
  RGBA_ASTC_10x5_Format,
  RGBA_ASTC_10x6_Format,
  RGBA_ASTC_10x8_Format,
  RGBA_ASTC_12x10_Format,
  RGBA_ASTC_12x12_Format,
  RGBA_ASTC_4x4_Format,
  RGBA_ASTC_5x4_Format,
  RGBA_ASTC_5x5_Format,
  RGBA_ASTC_6x5_Format,
  RGBA_ASTC_6x6_Format,
  RGBA_ASTC_8x5_Format,
  RGBA_ASTC_8x6_Format,
  RGBA_ASTC_8x8_Format,
  RGBA_BPTC_Format,
  RGBA_ETC2_EAC_Format,
  RGBA_PVRTC_2BPPV1_Format,
  RGBA_PVRTC_4BPPV1_Format,
  RGBA_S3TC_DXT1_Format,
  RGBA_S3TC_DXT3_Format,
  RGBA_S3TC_DXT5_Format,
  RGBDepthPacking,
  RGBFormat,
  RGBIntegerFormat,
  RGB_BPTC_SIGNED_Format,
  RGB_BPTC_UNSIGNED_Format,
  RGB_ETC1_Format,
  RGB_ETC2_Format,
  RGB_PVRTC_2BPPV1_Format,
  RGB_PVRTC_4BPPV1_Format,
  RGB_S3TC_DXT1_Format,
  RGDepthPacking,
  RGFormat,
  RGIntegerFormat,
  RawShaderMaterial,
  Ray,
  Raycaster,
  RectAreaLight,
  RedFormat,
  RedIntegerFormat,
  ReinhardToneMapping,
  RenderTarget,
  RepeatWrapping,
  ReplaceStencilOp,
  ReverseSubtractEquation,
  RingGeometry,
  SIGNED_RED_GREEN_RGTC2_Format,
  SIGNED_RED_RGTC1_Format,
  SRGBColorSpace,
  SRGBTransfer,
  Scene,
  ShaderChunk,
  ShaderLib,
  ShaderMaterial,
  ShadowMaterial,
  Shape,
  ShapeGeometry,
  ShapePath,
  ShapeUtils,
  ShortType,
  Skeleton,
  SkeletonHelper,
  SkinnedMesh,
  Source,
  Sphere,
  SphereGeometry,
  Spherical,
  SphericalHarmonics3,
  SplineCurve,
  SpotLight,
  SpotLightHelper,
  Sprite,
  SpriteMaterial,
  SrcAlphaFactor,
  SrcAlphaSaturateFactor,
  SrcColorFactor,
  StaticCopyUsage,
  StaticDrawUsage,
  StaticReadUsage,
  StereoCamera,
  StreamCopyUsage,
  StreamDrawUsage,
  StreamReadUsage,
  StringKeyframeTrack,
  SubtractEquation,
  SubtractiveBlending,
  TOUCH,
  TangentSpaceNormalMap,
  TetrahedronGeometry,
  Texture,
  TextureLoader,
  TextureUtils,
  TorusGeometry,
  TorusKnotGeometry,
  Triangle,
  TriangleFanDrawMode,
  TriangleStripDrawMode,
  TrianglesDrawMode,
  TubeGeometry,
  UVMapping,
  Uint16BufferAttribute,
  Uint32BufferAttribute,
  Uint8BufferAttribute,
  Uint8ClampedBufferAttribute,
  Uniform,
  UniformsGroup,
  UniformsLib,
  UniformsUtils,
  UnsignedByteType,
  UnsignedInt248Type,
  UnsignedInt5999Type,
  UnsignedIntType,
  UnsignedShort4444Type,
  UnsignedShort5551Type,
  UnsignedShortType,
  VSMShadowMap,
  Vector2,
  Vector3,
  Vector4,
  VectorKeyframeTrack,
  VideoTexture,
  WebGL3DRenderTarget,
  WebGLArrayRenderTarget,
  WebGLCoordinateSystem,
  WebGLCubeRenderTarget,
  WebGLMultipleRenderTargets,
  WebGLRenderTarget,
  WebGLRenderer,
  WebGLUtils,
  WebGPUCoordinateSystem,
  WireframeGeometry,
  WrapAroundEnding,
  ZeroCurvatureEnding,
  ZeroFactor,
  ZeroSlopeEnding,
  ZeroStencilOp,
  createCanvasElement
}, Symbol.toStringTag, { value: "Module" }));
var constants = { exports: {} };
var reactReconcilerConstants_production_min = {};
/**
 * @license React
 * react-reconciler-constants.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactReconcilerConstants_production_min;
function requireReactReconcilerConstants_production_min() {
  if (hasRequiredReactReconcilerConstants_production_min) return reactReconcilerConstants_production_min;
  hasRequiredReactReconcilerConstants_production_min = 1;
  reactReconcilerConstants_production_min.ConcurrentRoot = 1;
  reactReconcilerConstants_production_min.ContinuousEventPriority = 4;
  reactReconcilerConstants_production_min.DefaultEventPriority = 16;
  reactReconcilerConstants_production_min.DiscreteEventPriority = 1;
  reactReconcilerConstants_production_min.IdleEventPriority = 536870912;
  reactReconcilerConstants_production_min.LegacyRoot = 0;
  return reactReconcilerConstants_production_min;
}
var hasRequiredConstants;
function requireConstants() {
  if (hasRequiredConstants) return constants.exports;
  hasRequiredConstants = 1;
  {
    constants.exports = requireReactReconcilerConstants_production_min();
  }
  return constants.exports;
}
var constantsExports = requireConstants();
function createStore$1(createState) {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (nextState !== state) {
      const previousState = state;
      state = replace ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => {
    console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");
    let currentSlice = selector(state);
    function listenerToAdd() {
      const nextSlice = selector(state);
      if (!equalityFn(currentSlice, nextSlice)) {
        const previousSlice = currentSlice;
        listener(currentSlice = nextSlice, previousSlice);
      }
    }
    listeners.add(listenerToAdd);
    return () => listeners.delete(listenerToAdd);
  };
  const subscribe = (listener, selector, equalityFn) => {
    if (selector || equalityFn) {
      return subscribeWithSelector(listener, selector, equalityFn);
    }
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const destroy = () => listeners.clear();
  const api = { setState, getState, subscribe, destroy };
  state = createState(setState, getState, api);
  return api;
}
const isSSR = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
const useIsomorphicLayoutEffect$1 = isSSR ? reactExports.useEffect : reactExports.useLayoutEffect;
function create$1(createState) {
  const api = typeof createState === "function" ? createStore$1(createState) : createState;
  const useStore2 = (selector = api.getState, equalityFn = Object.is) => {
    const [, forceUpdate] = reactExports.useReducer((c2) => c2 + 1, 0);
    const state = api.getState();
    const stateRef = reactExports.useRef(state);
    const selectorRef = reactExports.useRef(selector);
    const equalityFnRef = reactExports.useRef(equalityFn);
    const erroredRef = reactExports.useRef(false);
    const currentSliceRef = reactExports.useRef();
    if (currentSliceRef.current === void 0) {
      currentSliceRef.current = selector(state);
    }
    let newStateSlice;
    let hasNewStateSlice = false;
    if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) {
      newStateSlice = selector(state);
      hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice);
    }
    useIsomorphicLayoutEffect$1(() => {
      if (hasNewStateSlice) {
        currentSliceRef.current = newStateSlice;
      }
      stateRef.current = state;
      selectorRef.current = selector;
      equalityFnRef.current = equalityFn;
      erroredRef.current = false;
    });
    const stateBeforeSubscriptionRef = reactExports.useRef(state);
    useIsomorphicLayoutEffect$1(() => {
      const listener = () => {
        try {
          const nextState = api.getState();
          const nextStateSlice = selectorRef.current(nextState);
          if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) {
            stateRef.current = nextState;
            currentSliceRef.current = nextStateSlice;
            forceUpdate();
          }
        } catch (error2) {
          erroredRef.current = true;
          forceUpdate();
        }
      };
      const unsubscribe = api.subscribe(listener);
      if (api.getState() !== stateBeforeSubscriptionRef.current) {
        listener();
      }
      return unsubscribe;
    }, []);
    const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current;
    reactExports.useDebugValue(sliceToReturn);
    return sliceToReturn;
  };
  Object.assign(useStore2, api);
  useStore2[Symbol.iterator] = function() {
    console.warn("[useStore, api] = create() is deprecated and will be removed in v4");
    const items = [useStore2, api];
    return {
      next() {
        const done = items.length <= 0;
        return { value: items.shift(), done };
      }
    };
  };
  return useStore2;
}
const isPromise = (promise) => typeof promise === "object" && typeof promise.then === "function";
const globalCache = [];
function shallowEqualArrays(arrA, arrB, equal = (a3, b2) => a3 === b2) {
  if (arrA === arrB) return true;
  if (!arrA || !arrB) return false;
  const len = arrA.length;
  if (arrB.length !== len) return false;
  for (let i2 = 0; i2 < len; i2++) if (!equal(arrA[i2], arrB[i2])) return false;
  return true;
}
function query(fn2, keys = null, preload2 = false, config = {}) {
  if (keys === null) keys = [fn2];
  for (const entry3 of globalCache) {
    if (shallowEqualArrays(keys, entry3.keys, entry3.equal)) {
      if (preload2) return void 0;
      if (Object.prototype.hasOwnProperty.call(entry3, "error")) throw entry3.error;
      if (Object.prototype.hasOwnProperty.call(entry3, "response")) {
        if (config.lifespan && config.lifespan > 0) {
          if (entry3.timeout) clearTimeout(entry3.timeout);
          entry3.timeout = setTimeout(entry3.remove, config.lifespan);
        }
        return entry3.response;
      }
      if (!preload2) throw entry3.promise;
    }
  }
  const entry2 = {
    keys,
    equal: config.equal,
    remove: () => {
      const index = globalCache.indexOf(entry2);
      if (index !== -1) globalCache.splice(index, 1);
    },
    promise: (
      // Execute the promise
      (isPromise(fn2) ? fn2 : fn2(...keys)).then((response) => {
        entry2.response = response;
        if (config.lifespan && config.lifespan > 0) {
          entry2.timeout = setTimeout(entry2.remove, config.lifespan);
        }
      }).catch((error2) => entry2.error = error2)
    )
  };
  globalCache.push(entry2);
  if (!preload2) throw entry2.promise;
  return void 0;
}
const suspend = (fn2, keys, config) => query(fn2, keys, false, config);
const preload = (fn2, keys, config) => void query(fn2, keys, true, config);
const clear = (keys) => {
  if (keys === void 0 || keys.length === 0) globalCache.splice(0, globalCache.length);
  else {
    const entry2 = globalCache.find((entry3) => shallowEqualArrays(keys, entry3.keys, entry3.equal));
    if (entry2) entry2.remove();
  }
};
var reactReconciler = { exports: {} };
var scheduler = { exports: {} };
var scheduler_production_min = {};
/**
 * @license React
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredScheduler_production_min;
function requireScheduler_production_min() {
  if (hasRequiredScheduler_production_min) return scheduler_production_min;
  hasRequiredScheduler_production_min = 1;
  (function(exports$1) {
    function f2(a3, b2) {
      var c2 = a3.length;
      a3.push(b2);
      a: for (; 0 < c2; ) {
        var d2 = c2 - 1 >>> 1, e2 = a3[d2];
        if (0 < g2(e2, b2)) a3[d2] = b2, a3[c2] = e2, c2 = d2;
        else break a;
      }
    }
    function h2(a3) {
      return 0 === a3.length ? null : a3[0];
    }
    function k2(a3) {
      if (0 === a3.length) return null;
      var b2 = a3[0], c2 = a3.pop();
      if (c2 !== b2) {
        a3[0] = c2;
        a: for (var d2 = 0, e2 = a3.length, w2 = e2 >>> 1; d2 < w2; ) {
          var m2 = 2 * (d2 + 1) - 1, C2 = a3[m2], n2 = m2 + 1, x = a3[n2];
          if (0 > g2(C2, c2)) n2 < e2 && 0 > g2(x, C2) ? (a3[d2] = x, a3[n2] = c2, d2 = n2) : (a3[d2] = C2, a3[m2] = c2, d2 = m2);
          else if (n2 < e2 && 0 > g2(x, c2)) a3[d2] = x, a3[n2] = c2, d2 = n2;
          else break a;
        }
      }
      return b2;
    }
    function g2(a3, b2) {
      var c2 = a3.sortIndex - b2.sortIndex;
      return 0 !== c2 ? c2 : a3.id - b2.id;
    }
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var l2 = performance;
      exports$1.unstable_now = function() {
        return l2.now();
      };
    } else {
      var p2 = Date, q3 = p2.now();
      exports$1.unstable_now = function() {
        return p2.now() - q3;
      };
    }
    var r2 = [], t2 = [], u2 = 1, v5 = null, y2 = 3, z2 = false, A2 = false, B = false, D2 = "function" === typeof setTimeout ? setTimeout : null, E2 = "function" === typeof clearTimeout ? clearTimeout : null, F2 = "undefined" !== typeof setImmediate ? setImmediate : null;
    "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
    function G2(a3) {
      for (var b2 = h2(t2); null !== b2; ) {
        if (null === b2.callback) k2(t2);
        else if (b2.startTime <= a3) k2(t2), b2.sortIndex = b2.expirationTime, f2(r2, b2);
        else break;
        b2 = h2(t2);
      }
    }
    function H2(a3) {
      B = false;
      G2(a3);
      if (!A2) if (null !== h2(r2)) A2 = true, I2(J2);
      else {
        var b2 = h2(t2);
        null !== b2 && K2(H2, b2.startTime - a3);
      }
    }
    function J2(a3, b2) {
      A2 = false;
      B && (B = false, E2(L2), L2 = -1);
      z2 = true;
      var c2 = y2;
      try {
        G2(b2);
        for (v5 = h2(r2); null !== v5 && (!(v5.expirationTime > b2) || a3 && !M2()); ) {
          var d2 = v5.callback;
          if ("function" === typeof d2) {
            v5.callback = null;
            y2 = v5.priorityLevel;
            var e2 = d2(v5.expirationTime <= b2);
            b2 = exports$1.unstable_now();
            "function" === typeof e2 ? v5.callback = e2 : v5 === h2(r2) && k2(r2);
            G2(b2);
          } else k2(r2);
          v5 = h2(r2);
        }
        if (null !== v5) var w2 = true;
        else {
          var m2 = h2(t2);
          null !== m2 && K2(H2, m2.startTime - b2);
          w2 = false;
        }
        return w2;
      } finally {
        v5 = null, y2 = c2, z2 = false;
      }
    }
    var N2 = false, O2 = null, L2 = -1, P2 = 5, Q2 = -1;
    function M2() {
      return exports$1.unstable_now() - Q2 < P2 ? false : true;
    }
    function R2() {
      if (null !== O2) {
        var a3 = exports$1.unstable_now();
        Q2 = a3;
        var b2 = true;
        try {
          b2 = O2(true, a3);
        } finally {
          b2 ? S2() : (N2 = false, O2 = null);
        }
      } else N2 = false;
    }
    var S2;
    if ("function" === typeof F2) S2 = function() {
      F2(R2);
    };
    else if ("undefined" !== typeof MessageChannel) {
      var T3 = new MessageChannel(), U2 = T3.port2;
      T3.port1.onmessage = R2;
      S2 = function() {
        U2.postMessage(null);
      };
    } else S2 = function() {
      D2(R2, 0);
    };
    function I2(a3) {
      O2 = a3;
      N2 || (N2 = true, S2());
    }
    function K2(a3, b2) {
      L2 = D2(function() {
        a3(exports$1.unstable_now());
      }, b2);
    }
    exports$1.unstable_IdlePriority = 5;
    exports$1.unstable_ImmediatePriority = 1;
    exports$1.unstable_LowPriority = 4;
    exports$1.unstable_NormalPriority = 3;
    exports$1.unstable_Profiling = null;
    exports$1.unstable_UserBlockingPriority = 2;
    exports$1.unstable_cancelCallback = function(a3) {
      a3.callback = null;
    };
    exports$1.unstable_continueExecution = function() {
      A2 || z2 || (A2 = true, I2(J2));
    };
    exports$1.unstable_forceFrameRate = function(a3) {
      0 > a3 || 125 < a3 ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P2 = 0 < a3 ? Math.floor(1e3 / a3) : 5;
    };
    exports$1.unstable_getCurrentPriorityLevel = function() {
      return y2;
    };
    exports$1.unstable_getFirstCallbackNode = function() {
      return h2(r2);
    };
    exports$1.unstable_next = function(a3) {
      switch (y2) {
        case 1:
        case 2:
        case 3:
          var b2 = 3;
          break;
        default:
          b2 = y2;
      }
      var c2 = y2;
      y2 = b2;
      try {
        return a3();
      } finally {
        y2 = c2;
      }
    };
    exports$1.unstable_pauseExecution = function() {
    };
    exports$1.unstable_requestPaint = function() {
    };
    exports$1.unstable_runWithPriority = function(a3, b2) {
      switch (a3) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          a3 = 3;
      }
      var c2 = y2;
      y2 = a3;
      try {
        return b2();
      } finally {
        y2 = c2;
      }
    };
    exports$1.unstable_scheduleCallback = function(a3, b2, c2) {
      var d2 = exports$1.unstable_now();
      "object" === typeof c2 && null !== c2 ? (c2 = c2.delay, c2 = "number" === typeof c2 && 0 < c2 ? d2 + c2 : d2) : c2 = d2;
      switch (a3) {
        case 1:
          var e2 = -1;
          break;
        case 2:
          e2 = 250;
          break;
        case 5:
          e2 = 1073741823;
          break;
        case 4:
          e2 = 1e4;
          break;
        default:
          e2 = 5e3;
      }
      e2 = c2 + e2;
      a3 = { id: u2++, callback: b2, priorityLevel: a3, startTime: c2, expirationTime: e2, sortIndex: -1 };
      c2 > d2 ? (a3.sortIndex = c2, f2(t2, a3), null === h2(r2) && a3 === h2(t2) && (B ? (E2(L2), L2 = -1) : B = true, K2(H2, c2 - d2))) : (a3.sortIndex = e2, f2(r2, a3), A2 || z2 || (A2 = true, I2(J2)));
      return a3;
    };
    exports$1.unstable_shouldYield = M2;
    exports$1.unstable_wrapCallback = function(a3) {
      var b2 = y2;
      return function() {
        var c2 = y2;
        y2 = b2;
        try {
          return a3.apply(this, arguments);
        } finally {
          y2 = c2;
        }
      };
    };
  })(scheduler_production_min);
  return scheduler_production_min;
}
var hasRequiredScheduler;
function requireScheduler() {
  if (hasRequiredScheduler) return scheduler.exports;
  hasRequiredScheduler = 1;
  {
    scheduler.exports = requireScheduler_production_min();
  }
  return scheduler.exports;
}
/**
 * @license React
 * react-reconciler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var reactReconciler_production_min;
var hasRequiredReactReconciler_production_min;
function requireReactReconciler_production_min() {
  if (hasRequiredReactReconciler_production_min) return reactReconciler_production_min;
  hasRequiredReactReconciler_production_min = 1;
  reactReconciler_production_min = function $$$reconciler($$$hostConfig) {
    var exports$1 = {};
    var aa = requireReact(), ba = requireScheduler(), ca = Object.assign;
    function n2(a3) {
      for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a3, c2 = 1; c2 < arguments.length; c2++) b2 += "&args[]=" + encodeURIComponent(arguments[c2]);
      return "Minified React error #" + a3 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    var ea2 = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, fa = Symbol.for("react.element"), ha = Symbol.for("react.portal"), ia = Symbol.for("react.fragment"), ja = Symbol.for("react.strict_mode"), ka = Symbol.for("react.profiler"), la2 = Symbol.for("react.provider"), ma = Symbol.for("react.context"), na = Symbol.for("react.forward_ref"), oa = Symbol.for("react.suspense"), pa2 = Symbol.for("react.suspense_list"), qa = Symbol.for("react.memo"), ra = Symbol.for("react.lazy");
    var sa = Symbol.for("react.offscreen");
    var ta = Symbol.iterator;
    function ua2(a3) {
      if (null === a3 || "object" !== typeof a3) return null;
      a3 = ta && a3[ta] || a3["@@iterator"];
      return "function" === typeof a3 ? a3 : null;
    }
    function va(a3) {
      if (null == a3) return null;
      if ("function" === typeof a3) return a3.displayName || a3.name || null;
      if ("string" === typeof a3) return a3;
      switch (a3) {
        case ia:
          return "Fragment";
        case ha:
          return "Portal";
        case ka:
          return "Profiler";
        case ja:
          return "StrictMode";
        case oa:
          return "Suspense";
        case pa2:
          return "SuspenseList";
      }
      if ("object" === typeof a3) switch (a3.$$typeof) {
        case ma:
          return (a3.displayName || "Context") + ".Consumer";
        case la2:
          return (a3._context.displayName || "Context") + ".Provider";
        case na:
          var b2 = a3.render;
          a3 = a3.displayName;
          a3 || (a3 = b2.displayName || b2.name || "", a3 = "" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
          return a3;
        case qa:
          return b2 = a3.displayName || null, null !== b2 ? b2 : va(a3.type) || "Memo";
        case ra:
          b2 = a3._payload;
          a3 = a3._init;
          try {
            return va(a3(b2));
          } catch (c2) {
          }
      }
      return null;
    }
    function xa(a3) {
      var b2 = a3.type;
      switch (a3.tag) {
        case 24:
          return "Cache";
        case 9:
          return (b2.displayName || "Context") + ".Consumer";
        case 10:
          return (b2._context.displayName || "Context") + ".Provider";
        case 18:
          return "DehydratedFragment";
        case 11:
          return a3 = b2.render, a3 = a3.displayName || a3.name || "", b2.displayName || ("" !== a3 ? "ForwardRef(" + a3 + ")" : "ForwardRef");
        case 7:
          return "Fragment";
        case 5:
          return b2;
        case 4:
          return "Portal";
        case 3:
          return "Root";
        case 6:
          return "Text";
        case 16:
          return va(b2);
        case 8:
          return b2 === ja ? "StrictMode" : "Mode";
        case 22:
          return "Offscreen";
        case 12:
          return "Profiler";
        case 21:
          return "Scope";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 25:
          return "TracingMarker";
        case 1:
        case 0:
        case 17:
        case 2:
        case 14:
        case 15:
          if ("function" === typeof b2) return b2.displayName || b2.name || null;
          if ("string" === typeof b2) return b2;
      }
      return null;
    }
    function ya(a3) {
      var b2 = a3, c2 = a3;
      if (a3.alternate) for (; b2.return; ) b2 = b2.return;
      else {
        a3 = b2;
        do
          b2 = a3, 0 !== (b2.flags & 4098) && (c2 = b2.return), a3 = b2.return;
        while (a3);
      }
      return 3 === b2.tag ? c2 : null;
    }
    function za(a3) {
      if (ya(a3) !== a3) throw Error(n2(188));
    }
    function Aa(a3) {
      var b2 = a3.alternate;
      if (!b2) {
        b2 = ya(a3);
        if (null === b2) throw Error(n2(188));
        return b2 !== a3 ? null : a3;
      }
      for (var c2 = a3, d2 = b2; ; ) {
        var e2 = c2.return;
        if (null === e2) break;
        var f2 = e2.alternate;
        if (null === f2) {
          d2 = e2.return;
          if (null !== d2) {
            c2 = d2;
            continue;
          }
          break;
        }
        if (e2.child === f2.child) {
          for (f2 = e2.child; f2; ) {
            if (f2 === c2) return za(e2), a3;
            if (f2 === d2) return za(e2), b2;
            f2 = f2.sibling;
          }
          throw Error(n2(188));
        }
        if (c2.return !== d2.return) c2 = e2, d2 = f2;
        else {
          for (var g2 = false, h2 = e2.child; h2; ) {
            if (h2 === c2) {
              g2 = true;
              c2 = e2;
              d2 = f2;
              break;
            }
            if (h2 === d2) {
              g2 = true;
              d2 = e2;
              c2 = f2;
              break;
            }
            h2 = h2.sibling;
          }
          if (!g2) {
            for (h2 = f2.child; h2; ) {
              if (h2 === c2) {
                g2 = true;
                c2 = f2;
                d2 = e2;
                break;
              }
              if (h2 === d2) {
                g2 = true;
                d2 = f2;
                c2 = e2;
                break;
              }
              h2 = h2.sibling;
            }
            if (!g2) throw Error(n2(189));
          }
        }
        if (c2.alternate !== d2) throw Error(n2(190));
      }
      if (3 !== c2.tag) throw Error(n2(188));
      return c2.stateNode.current === c2 ? a3 : b2;
    }
    function Ba(a3) {
      a3 = Aa(a3);
      return null !== a3 ? Ca(a3) : null;
    }
    function Ca(a3) {
      if (5 === a3.tag || 6 === a3.tag) return a3;
      for (a3 = a3.child; null !== a3; ) {
        var b2 = Ca(a3);
        if (null !== b2) return b2;
        a3 = a3.sibling;
      }
      return null;
    }
    function Da(a3) {
      if (5 === a3.tag || 6 === a3.tag) return a3;
      for (a3 = a3.child; null !== a3; ) {
        if (4 !== a3.tag) {
          var b2 = Da(a3);
          if (null !== b2) return b2;
        }
        a3 = a3.sibling;
      }
      return null;
    }
    var Ea = Array.isArray, Fa = $$$hostConfig.getPublicInstance, Ga = $$$hostConfig.getRootHostContext, Ha = $$$hostConfig.getChildHostContext, Ia = $$$hostConfig.prepareForCommit, Ja = $$$hostConfig.resetAfterCommit, Ka = $$$hostConfig.createInstance, La = $$$hostConfig.appendInitialChild, Ma = $$$hostConfig.finalizeInitialChildren, Na = $$$hostConfig.prepareUpdate, Oa = $$$hostConfig.shouldSetTextContent, Pa = $$$hostConfig.createTextInstance, Qa = $$$hostConfig.scheduleTimeout, Ra = $$$hostConfig.cancelTimeout, Sa = $$$hostConfig.noTimeout, Ta = $$$hostConfig.isPrimaryRenderer, Ua = $$$hostConfig.supportsMutation, Va = $$$hostConfig.supportsPersistence, p2 = $$$hostConfig.supportsHydration, Wa = $$$hostConfig.getInstanceFromNode, Xa = $$$hostConfig.preparePortalMount, Ya = $$$hostConfig.getCurrentEventPriority, Za = $$$hostConfig.detachDeletedInstance, $a = $$$hostConfig.supportsMicrotasks, ab = $$$hostConfig.scheduleMicrotask, bb = $$$hostConfig.supportsTestSelectors, cb = $$$hostConfig.findFiberRoot, db = $$$hostConfig.getBoundingRect, eb = $$$hostConfig.getTextContent, fb = $$$hostConfig.isHiddenSubtree, gb = $$$hostConfig.matchAccessibilityRole, hb = $$$hostConfig.setFocusIfFocusable, ib = $$$hostConfig.setupIntersectionObserver, jb = $$$hostConfig.appendChild, kb = $$$hostConfig.appendChildToContainer, lb = $$$hostConfig.commitTextUpdate, mb = $$$hostConfig.commitMount, nb = $$$hostConfig.commitUpdate, ob = $$$hostConfig.insertBefore, pb = $$$hostConfig.insertInContainerBefore, qb = $$$hostConfig.removeChild, rb = $$$hostConfig.removeChildFromContainer, sb = $$$hostConfig.resetTextContent, tb = $$$hostConfig.hideInstance, ub = $$$hostConfig.hideTextInstance, vb = $$$hostConfig.unhideInstance, wb = $$$hostConfig.unhideTextInstance, xb = $$$hostConfig.clearContainer, yb = $$$hostConfig.cloneInstance, zb = $$$hostConfig.createContainerChildSet, Ab = $$$hostConfig.appendChildToContainerChildSet, Bb = $$$hostConfig.finalizeContainerChildren, Cb = $$$hostConfig.replaceContainerChildren, Db = $$$hostConfig.cloneHiddenInstance, Eb = $$$hostConfig.cloneHiddenTextInstance, Fb = $$$hostConfig.canHydrateInstance, Gb = $$$hostConfig.canHydrateTextInstance, Hb = $$$hostConfig.canHydrateSuspenseInstance, Ib = $$$hostConfig.isSuspenseInstancePending, Jb = $$$hostConfig.isSuspenseInstanceFallback, Kb = $$$hostConfig.registerSuspenseInstanceRetry, Lb = $$$hostConfig.getNextHydratableSibling, Mb = $$$hostConfig.getFirstHydratableChild, Nb = $$$hostConfig.getFirstHydratableChildWithinContainer, Ob = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance, Pb = $$$hostConfig.hydrateInstance, Qb = $$$hostConfig.hydrateTextInstance, Rb = $$$hostConfig.hydrateSuspenseInstance, Sb = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance, Tb = $$$hostConfig.commitHydratedContainer, Ub = $$$hostConfig.commitHydratedSuspenseInstance, Vb = $$$hostConfig.clearSuspenseBoundary, Wb = $$$hostConfig.clearSuspenseBoundaryFromContainer, Xb = $$$hostConfig.shouldDeleteUnhydratedTailInstances, Yb = $$$hostConfig.didNotMatchHydratedContainerTextInstance, Zb = $$$hostConfig.didNotMatchHydratedTextInstance, $b;
    function ac(a3) {
      if (void 0 === $b) try {
        throw Error();
      } catch (c2) {
        var b2 = c2.stack.trim().match(/\n( *(at )?)/);
        $b = b2 && b2[1] || "";
      }
      return "\n" + $b + a3;
    }
    var bc = false;
    function cc(a3, b2) {
      if (!a3 || bc) return "";
      bc = true;
      var c2 = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      try {
        if (b2) if (b2 = function() {
          throw Error();
        }, Object.defineProperty(b2.prototype, "props", { set: function() {
          throw Error();
        } }), "object" === typeof Reflect && Reflect.construct) {
          try {
            Reflect.construct(b2, []);
          } catch (l2) {
            var d2 = l2;
          }
          Reflect.construct(a3, [], b2);
        } else {
          try {
            b2.call();
          } catch (l2) {
            d2 = l2;
          }
          a3.call(b2.prototype);
        }
        else {
          try {
            throw Error();
          } catch (l2) {
            d2 = l2;
          }
          a3();
        }
      } catch (l2) {
        if (l2 && d2 && "string" === typeof l2.stack) {
          for (var e2 = l2.stack.split("\n"), f2 = d2.stack.split("\n"), g2 = e2.length - 1, h2 = f2.length - 1; 1 <= g2 && 0 <= h2 && e2[g2] !== f2[h2]; ) h2--;
          for (; 1 <= g2 && 0 <= h2; g2--, h2--) if (e2[g2] !== f2[h2]) {
            if (1 !== g2 || 1 !== h2) {
              do
                if (g2--, h2--, 0 > h2 || e2[g2] !== f2[h2]) {
                  var k2 = "\n" + e2[g2].replace(" at new ", " at ");
                  a3.displayName && k2.includes("<anonymous>") && (k2 = k2.replace("<anonymous>", a3.displayName));
                  return k2;
                }
              while (1 <= g2 && 0 <= h2);
            }
            break;
          }
        }
      } finally {
        bc = false, Error.prepareStackTrace = c2;
      }
      return (a3 = a3 ? a3.displayName || a3.name : "") ? ac(a3) : "";
    }
    var dc = Object.prototype.hasOwnProperty, ec = [], fc = -1;
    function gc(a3) {
      return { current: a3 };
    }
    function x(a3) {
      0 > fc || (a3.current = ec[fc], ec[fc] = null, fc--);
    }
    function y2(a3, b2) {
      fc++;
      ec[fc] = a3.current;
      a3.current = b2;
    }
    var hc = {}, A2 = gc(hc), B = gc(false), ic = hc;
    function jc(a3, b2) {
      var c2 = a3.type.contextTypes;
      if (!c2) return hc;
      var d2 = a3.stateNode;
      if (d2 && d2.__reactInternalMemoizedUnmaskedChildContext === b2) return d2.__reactInternalMemoizedMaskedChildContext;
      var e2 = {}, f2;
      for (f2 in c2) e2[f2] = b2[f2];
      d2 && (a3 = a3.stateNode, a3.__reactInternalMemoizedUnmaskedChildContext = b2, a3.__reactInternalMemoizedMaskedChildContext = e2);
      return e2;
    }
    function C2(a3) {
      a3 = a3.childContextTypes;
      return null !== a3 && void 0 !== a3;
    }
    function kc() {
      x(B);
      x(A2);
    }
    function lc(a3, b2, c2) {
      if (A2.current !== hc) throw Error(n2(168));
      y2(A2, b2);
      y2(B, c2);
    }
    function mc(a3, b2, c2) {
      var d2 = a3.stateNode;
      b2 = b2.childContextTypes;
      if ("function" !== typeof d2.getChildContext) return c2;
      d2 = d2.getChildContext();
      for (var e2 in d2) if (!(e2 in b2)) throw Error(n2(108, xa(a3) || "Unknown", e2));
      return ca({}, c2, d2);
    }
    function nc(a3) {
      a3 = (a3 = a3.stateNode) && a3.__reactInternalMemoizedMergedChildContext || hc;
      ic = A2.current;
      y2(A2, a3);
      y2(B, B.current);
      return true;
    }
    function oc(a3, b2, c2) {
      var d2 = a3.stateNode;
      if (!d2) throw Error(n2(169));
      c2 ? (a3 = mc(a3, b2, ic), d2.__reactInternalMemoizedMergedChildContext = a3, x(B), x(A2), y2(A2, a3)) : x(B);
      y2(B, c2);
    }
    var qc = Math.clz32 ? Math.clz32 : pc, rc = Math.log, sc = Math.LN2;
    function pc(a3) {
      a3 >>>= 0;
      return 0 === a3 ? 32 : 31 - (rc(a3) / sc | 0) | 0;
    }
    var tc = 64, uc = 4194304;
    function vc(a3) {
      switch (a3 & -a3) {
        case 1:
          return 1;
        case 2:
          return 2;
        case 4:
          return 4;
        case 8:
          return 8;
        case 16:
          return 16;
        case 32:
          return 32;
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return a3 & 4194240;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return a3 & 130023424;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 1073741824;
        default:
          return a3;
      }
    }
    function wc(a3, b2) {
      var c2 = a3.pendingLanes;
      if (0 === c2) return 0;
      var d2 = 0, e2 = a3.suspendedLanes, f2 = a3.pingedLanes, g2 = c2 & 268435455;
      if (0 !== g2) {
        var h2 = g2 & ~e2;
        0 !== h2 ? d2 = vc(h2) : (f2 &= g2, 0 !== f2 && (d2 = vc(f2)));
      } else g2 = c2 & ~e2, 0 !== g2 ? d2 = vc(g2) : 0 !== f2 && (d2 = vc(f2));
      if (0 === d2) return 0;
      if (0 !== b2 && b2 !== d2 && 0 === (b2 & e2) && (e2 = d2 & -d2, f2 = b2 & -b2, e2 >= f2 || 16 === e2 && 0 !== (f2 & 4194240))) return b2;
      0 !== (d2 & 4) && (d2 |= c2 & 16);
      b2 = a3.entangledLanes;
      if (0 !== b2) for (a3 = a3.entanglements, b2 &= d2; 0 < b2; ) c2 = 31 - qc(b2), e2 = 1 << c2, d2 |= a3[c2], b2 &= ~e2;
      return d2;
    }
    function xc(a3, b2) {
      switch (a3) {
        case 1:
        case 2:
        case 4:
          return b2 + 250;
        case 8:
        case 16:
        case 32:
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return b2 + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return -1;
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return -1;
      }
    }
    function yc(a3, b2) {
      for (var c2 = a3.suspendedLanes, d2 = a3.pingedLanes, e2 = a3.expirationTimes, f2 = a3.pendingLanes; 0 < f2; ) {
        var g2 = 31 - qc(f2), h2 = 1 << g2, k2 = e2[g2];
        if (-1 === k2) {
          if (0 === (h2 & c2) || 0 !== (h2 & d2)) e2[g2] = xc(h2, b2);
        } else k2 <= b2 && (a3.expiredLanes |= h2);
        f2 &= ~h2;
      }
    }
    function zc(a3) {
      a3 = a3.pendingLanes & -1073741825;
      return 0 !== a3 ? a3 : a3 & 1073741824 ? 1073741824 : 0;
    }
    function Ac(a3) {
      for (var b2 = [], c2 = 0; 31 > c2; c2++) b2.push(a3);
      return b2;
    }
    function Bc(a3, b2, c2) {
      a3.pendingLanes |= b2;
      536870912 !== b2 && (a3.suspendedLanes = 0, a3.pingedLanes = 0);
      a3 = a3.eventTimes;
      b2 = 31 - qc(b2);
      a3[b2] = c2;
    }
    function Cc(a3, b2) {
      var c2 = a3.pendingLanes & ~b2;
      a3.pendingLanes = b2;
      a3.suspendedLanes = 0;
      a3.pingedLanes = 0;
      a3.expiredLanes &= b2;
      a3.mutableReadLanes &= b2;
      a3.entangledLanes &= b2;
      b2 = a3.entanglements;
      var d2 = a3.eventTimes;
      for (a3 = a3.expirationTimes; 0 < c2; ) {
        var e2 = 31 - qc(c2), f2 = 1 << e2;
        b2[e2] = 0;
        d2[e2] = -1;
        a3[e2] = -1;
        c2 &= ~f2;
      }
    }
    function Dc(a3, b2) {
      var c2 = a3.entangledLanes |= b2;
      for (a3 = a3.entanglements; c2; ) {
        var d2 = 31 - qc(c2), e2 = 1 << d2;
        e2 & b2 | a3[d2] & b2 && (a3[d2] |= b2);
        c2 &= ~e2;
      }
    }
    var D2 = 0;
    function Ec(a3) {
      a3 &= -a3;
      return 1 < a3 ? 4 < a3 ? 0 !== (a3 & 268435455) ? 16 : 536870912 : 4 : 1;
    }
    var Fc = ba.unstable_scheduleCallback, Gc = ba.unstable_cancelCallback, Hc = ba.unstable_shouldYield, Ic = ba.unstable_requestPaint, E2 = ba.unstable_now, Jc = ba.unstable_ImmediatePriority, Kc = ba.unstable_UserBlockingPriority, Lc = ba.unstable_NormalPriority, Mc = ba.unstable_IdlePriority, Nc = null, Oc = null;
    function Pc(a3) {
      if (Oc && "function" === typeof Oc.onCommitFiberRoot) try {
        Oc.onCommitFiberRoot(Nc, a3, void 0, 128 === (a3.current.flags & 128));
      } catch (b2) {
      }
    }
    function Qc(a3, b2) {
      return a3 === b2 && (0 !== a3 || 1 / a3 === 1 / b2) || a3 !== a3 && b2 !== b2;
    }
    var Rc = "function" === typeof Object.is ? Object.is : Qc, Sc = null, Tc = false, Uc = false;
    function Vc(a3) {
      null === Sc ? Sc = [a3] : Sc.push(a3);
    }
    function Wc(a3) {
      Tc = true;
      Vc(a3);
    }
    function Xc() {
      if (!Uc && null !== Sc) {
        Uc = true;
        var a3 = 0, b2 = D2;
        try {
          var c2 = Sc;
          for (D2 = 1; a3 < c2.length; a3++) {
            var d2 = c2[a3];
            do
              d2 = d2(true);
            while (null !== d2);
          }
          Sc = null;
          Tc = false;
        } catch (e2) {
          throw null !== Sc && (Sc = Sc.slice(a3 + 1)), Fc(Jc, Xc), e2;
        } finally {
          D2 = b2, Uc = false;
        }
      }
      return null;
    }
    var Yc = ea2.ReactCurrentBatchConfig;
    function Zc(a3, b2) {
      if (Rc(a3, b2)) return true;
      if ("object" !== typeof a3 || null === a3 || "object" !== typeof b2 || null === b2) return false;
      var c2 = Object.keys(a3), d2 = Object.keys(b2);
      if (c2.length !== d2.length) return false;
      for (d2 = 0; d2 < c2.length; d2++) {
        var e2 = c2[d2];
        if (!dc.call(b2, e2) || !Rc(a3[e2], b2[e2])) return false;
      }
      return true;
    }
    function $c(a3) {
      switch (a3.tag) {
        case 5:
          return ac(a3.type);
        case 16:
          return ac("Lazy");
        case 13:
          return ac("Suspense");
        case 19:
          return ac("SuspenseList");
        case 0:
        case 2:
        case 15:
          return a3 = cc(a3.type, false), a3;
        case 11:
          return a3 = cc(a3.type.render, false), a3;
        case 1:
          return a3 = cc(a3.type, true), a3;
        default:
          return "";
      }
    }
    function ad(a3, b2) {
      if (a3 && a3.defaultProps) {
        b2 = ca({}, b2);
        a3 = a3.defaultProps;
        for (var c2 in a3) void 0 === b2[c2] && (b2[c2] = a3[c2]);
        return b2;
      }
      return b2;
    }
    var bd = gc(null), cd = null, dd = null, ed = null;
    function fd2() {
      ed = dd = cd = null;
    }
    function gd(a3, b2, c2) {
      Ta ? (y2(bd, b2._currentValue), b2._currentValue = c2) : (y2(bd, b2._currentValue2), b2._currentValue2 = c2);
    }
    function hd(a3) {
      var b2 = bd.current;
      x(bd);
      Ta ? a3._currentValue = b2 : a3._currentValue2 = b2;
    }
    function id(a3, b2, c2) {
      for (; null !== a3; ) {
        var d2 = a3.alternate;
        (a3.childLanes & b2) !== b2 ? (a3.childLanes |= b2, null !== d2 && (d2.childLanes |= b2)) : null !== d2 && (d2.childLanes & b2) !== b2 && (d2.childLanes |= b2);
        if (a3 === c2) break;
        a3 = a3.return;
      }
    }
    function jd(a3, b2) {
      cd = a3;
      ed = dd = null;
      a3 = a3.dependencies;
      null !== a3 && null !== a3.firstContext && (0 !== (a3.lanes & b2) && (kd = true), a3.firstContext = null);
    }
    function ld(a3) {
      var b2 = Ta ? a3._currentValue : a3._currentValue2;
      if (ed !== a3) if (a3 = { context: a3, memoizedValue: b2, next: null }, null === dd) {
        if (null === cd) throw Error(n2(308));
        dd = a3;
        cd.dependencies = { lanes: 0, firstContext: a3 };
      } else dd = dd.next = a3;
      return b2;
    }
    var md = null, nd = false;
    function od(a3) {
      a3.updateQueue = { baseState: a3.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null };
    }
    function pd(a3, b2) {
      a3 = a3.updateQueue;
      b2.updateQueue === a3 && (b2.updateQueue = { baseState: a3.baseState, firstBaseUpdate: a3.firstBaseUpdate, lastBaseUpdate: a3.lastBaseUpdate, shared: a3.shared, effects: a3.effects });
    }
    function qd(a3, b2) {
      return { eventTime: a3, lane: b2, tag: 0, payload: null, callback: null, next: null };
    }
    function rd(a3, b2) {
      var c2 = a3.updateQueue;
      null !== c2 && (c2 = c2.shared, null !== F2 && 0 !== (a3.mode & 1) && 0 === (G2 & 2) ? (a3 = c2.interleaved, null === a3 ? (b2.next = b2, null === md ? md = [c2] : md.push(c2)) : (b2.next = a3.next, a3.next = b2), c2.interleaved = b2) : (a3 = c2.pending, null === a3 ? b2.next = b2 : (b2.next = a3.next, a3.next = b2), c2.pending = b2));
    }
    function sd(a3, b2, c2) {
      b2 = b2.updateQueue;
      if (null !== b2 && (b2 = b2.shared, 0 !== (c2 & 4194240))) {
        var d2 = b2.lanes;
        d2 &= a3.pendingLanes;
        c2 |= d2;
        b2.lanes = c2;
        Dc(a3, c2);
      }
    }
    function td2(a3, b2) {
      var c2 = a3.updateQueue, d2 = a3.alternate;
      if (null !== d2 && (d2 = d2.updateQueue, c2 === d2)) {
        var e2 = null, f2 = null;
        c2 = c2.firstBaseUpdate;
        if (null !== c2) {
          do {
            var g2 = { eventTime: c2.eventTime, lane: c2.lane, tag: c2.tag, payload: c2.payload, callback: c2.callback, next: null };
            null === f2 ? e2 = f2 = g2 : f2 = f2.next = g2;
            c2 = c2.next;
          } while (null !== c2);
          null === f2 ? e2 = f2 = b2 : f2 = f2.next = b2;
        } else e2 = f2 = b2;
        c2 = { baseState: d2.baseState, firstBaseUpdate: e2, lastBaseUpdate: f2, shared: d2.shared, effects: d2.effects };
        a3.updateQueue = c2;
        return;
      }
      a3 = c2.lastBaseUpdate;
      null === a3 ? c2.firstBaseUpdate = b2 : a3.next = b2;
      c2.lastBaseUpdate = b2;
    }
    function ud(a3, b2, c2, d2) {
      var e2 = a3.updateQueue;
      nd = false;
      var f2 = e2.firstBaseUpdate, g2 = e2.lastBaseUpdate, h2 = e2.shared.pending;
      if (null !== h2) {
        e2.shared.pending = null;
        var k2 = h2, l2 = k2.next;
        k2.next = null;
        null === g2 ? f2 = l2 : g2.next = l2;
        g2 = k2;
        var m2 = a3.alternate;
        null !== m2 && (m2 = m2.updateQueue, h2 = m2.lastBaseUpdate, h2 !== g2 && (null === h2 ? m2.firstBaseUpdate = l2 : h2.next = l2, m2.lastBaseUpdate = k2));
      }
      if (null !== f2) {
        var v5 = e2.baseState;
        g2 = 0;
        m2 = l2 = k2 = null;
        h2 = f2;
        do {
          var r2 = h2.lane, z2 = h2.eventTime;
          if ((d2 & r2) === r2) {
            null !== m2 && (m2 = m2.next = {
              eventTime: z2,
              lane: 0,
              tag: h2.tag,
              payload: h2.payload,
              callback: h2.callback,
              next: null
            });
            a: {
              var q3 = a3, N2 = h2;
              r2 = b2;
              z2 = c2;
              switch (N2.tag) {
                case 1:
                  q3 = N2.payload;
                  if ("function" === typeof q3) {
                    v5 = q3.call(z2, v5, r2);
                    break a;
                  }
                  v5 = q3;
                  break a;
                case 3:
                  q3.flags = q3.flags & -65537 | 128;
                case 0:
                  q3 = N2.payload;
                  r2 = "function" === typeof q3 ? q3.call(z2, v5, r2) : q3;
                  if (null === r2 || void 0 === r2) break a;
                  v5 = ca({}, v5, r2);
                  break a;
                case 2:
                  nd = true;
              }
            }
            null !== h2.callback && 0 !== h2.lane && (a3.flags |= 64, r2 = e2.effects, null === r2 ? e2.effects = [h2] : r2.push(h2));
          } else z2 = { eventTime: z2, lane: r2, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }, null === m2 ? (l2 = m2 = z2, k2 = v5) : m2 = m2.next = z2, g2 |= r2;
          h2 = h2.next;
          if (null === h2) if (h2 = e2.shared.pending, null === h2) break;
          else r2 = h2, h2 = r2.next, r2.next = null, e2.lastBaseUpdate = r2, e2.shared.pending = null;
        } while (1);
        null === m2 && (k2 = v5);
        e2.baseState = k2;
        e2.firstBaseUpdate = l2;
        e2.lastBaseUpdate = m2;
        b2 = e2.shared.interleaved;
        if (null !== b2) {
          e2 = b2;
          do
            g2 |= e2.lane, e2 = e2.next;
          while (e2 !== b2);
        } else null === f2 && (e2.shared.lanes = 0);
        vd |= g2;
        a3.lanes = g2;
        a3.memoizedState = v5;
      }
    }
    function wd(a3, b2, c2) {
      a3 = b2.effects;
      b2.effects = null;
      if (null !== a3) for (b2 = 0; b2 < a3.length; b2++) {
        var d2 = a3[b2], e2 = d2.callback;
        if (null !== e2) {
          d2.callback = null;
          d2 = c2;
          if ("function" !== typeof e2) throw Error(n2(191, e2));
          e2.call(d2);
        }
      }
    }
    var xd = new aa.Component().refs;
    function yd(a3, b2, c2, d2) {
      b2 = a3.memoizedState;
      c2 = c2(d2, b2);
      c2 = null === c2 || void 0 === c2 ? b2 : ca({}, b2, c2);
      a3.memoizedState = c2;
      0 === a3.lanes && (a3.updateQueue.baseState = c2);
    }
    var Bd = { isMounted: function(a3) {
      return (a3 = a3._reactInternals) ? ya(a3) === a3 : false;
    }, enqueueSetState: function(a3, b2, c2) {
      a3 = a3._reactInternals;
      var d2 = H2(), e2 = zd(a3), f2 = qd(d2, e2);
      f2.payload = b2;
      void 0 !== c2 && null !== c2 && (f2.callback = c2);
      rd(a3, f2);
      b2 = Ad(a3, e2, d2);
      null !== b2 && sd(b2, a3, e2);
    }, enqueueReplaceState: function(a3, b2, c2) {
      a3 = a3._reactInternals;
      var d2 = H2(), e2 = zd(a3), f2 = qd(d2, e2);
      f2.tag = 1;
      f2.payload = b2;
      void 0 !== c2 && null !== c2 && (f2.callback = c2);
      rd(a3, f2);
      b2 = Ad(a3, e2, d2);
      null !== b2 && sd(b2, a3, e2);
    }, enqueueForceUpdate: function(a3, b2) {
      a3 = a3._reactInternals;
      var c2 = H2(), d2 = zd(a3), e2 = qd(
        c2,
        d2
      );
      e2.tag = 2;
      void 0 !== b2 && null !== b2 && (e2.callback = b2);
      rd(a3, e2);
      b2 = Ad(a3, d2, c2);
      null !== b2 && sd(b2, a3, d2);
    } };
    function Cd(a3, b2, c2, d2, e2, f2, g2) {
      a3 = a3.stateNode;
      return "function" === typeof a3.shouldComponentUpdate ? a3.shouldComponentUpdate(d2, f2, g2) : b2.prototype && b2.prototype.isPureReactComponent ? !Zc(c2, d2) || !Zc(e2, f2) : true;
    }
    function Dd(a3, b2, c2) {
      var d2 = false, e2 = hc;
      var f2 = b2.contextType;
      "object" === typeof f2 && null !== f2 ? f2 = ld(f2) : (e2 = C2(b2) ? ic : A2.current, d2 = b2.contextTypes, f2 = (d2 = null !== d2 && void 0 !== d2) ? jc(a3, e2) : hc);
      b2 = new b2(c2, f2);
      a3.memoizedState = null !== b2.state && void 0 !== b2.state ? b2.state : null;
      b2.updater = Bd;
      a3.stateNode = b2;
      b2._reactInternals = a3;
      d2 && (a3 = a3.stateNode, a3.__reactInternalMemoizedUnmaskedChildContext = e2, a3.__reactInternalMemoizedMaskedChildContext = f2);
      return b2;
    }
    function Ed(a3, b2, c2, d2) {
      a3 = b2.state;
      "function" === typeof b2.componentWillReceiveProps && b2.componentWillReceiveProps(c2, d2);
      "function" === typeof b2.UNSAFE_componentWillReceiveProps && b2.UNSAFE_componentWillReceiveProps(c2, d2);
      b2.state !== a3 && Bd.enqueueReplaceState(b2, b2.state, null);
    }
    function Fd(a3, b2, c2, d2) {
      var e2 = a3.stateNode;
      e2.props = c2;
      e2.state = a3.memoizedState;
      e2.refs = xd;
      od(a3);
      var f2 = b2.contextType;
      "object" === typeof f2 && null !== f2 ? e2.context = ld(f2) : (f2 = C2(b2) ? ic : A2.current, e2.context = jc(a3, f2));
      e2.state = a3.memoizedState;
      f2 = b2.getDerivedStateFromProps;
      "function" === typeof f2 && (yd(a3, b2, f2, c2), e2.state = a3.memoizedState);
      "function" === typeof b2.getDerivedStateFromProps || "function" === typeof e2.getSnapshotBeforeUpdate || "function" !== typeof e2.UNSAFE_componentWillMount && "function" !== typeof e2.componentWillMount || (b2 = e2.state, "function" === typeof e2.componentWillMount && e2.componentWillMount(), "function" === typeof e2.UNSAFE_componentWillMount && e2.UNSAFE_componentWillMount(), b2 !== e2.state && Bd.enqueueReplaceState(e2, e2.state, null), ud(a3, c2, e2, d2), e2.state = a3.memoizedState);
      "function" === typeof e2.componentDidMount && (a3.flags |= 4194308);
    }
    var Gd = [], Hd = 0, Id = null, Jd = 0, Kd = [], Ld = 0, Md = null, Nd = 1, Od = "";
    function Pd(a3, b2) {
      Gd[Hd++] = Jd;
      Gd[Hd++] = Id;
      Id = a3;
      Jd = b2;
    }
    function Qd(a3, b2, c2) {
      Kd[Ld++] = Nd;
      Kd[Ld++] = Od;
      Kd[Ld++] = Md;
      Md = a3;
      var d2 = Nd;
      a3 = Od;
      var e2 = 32 - qc(d2) - 1;
      d2 &= ~(1 << e2);
      c2 += 1;
      var f2 = 32 - qc(b2) + e2;
      if (30 < f2) {
        var g2 = e2 - e2 % 5;
        f2 = (d2 & (1 << g2) - 1).toString(32);
        d2 >>= g2;
        e2 -= g2;
        Nd = 1 << 32 - qc(b2) + e2 | c2 << e2 | d2;
        Od = f2 + a3;
      } else Nd = 1 << f2 | c2 << e2 | d2, Od = a3;
    }
    function Rd(a3) {
      null !== a3.return && (Pd(a3, 1), Qd(a3, 1, 0));
    }
    function Sd(a3) {
      for (; a3 === Id; ) Id = Gd[--Hd], Gd[Hd] = null, Jd = Gd[--Hd], Gd[Hd] = null;
      for (; a3 === Md; ) Md = Kd[--Ld], Kd[Ld] = null, Od = Kd[--Ld], Kd[Ld] = null, Nd = Kd[--Ld], Kd[Ld] = null;
    }
    var Td = null, Ud = null, I2 = false, Vd = false, Wd = null;
    function Xd(a3, b2) {
      var c2 = Yd(5, null, null, 0);
      c2.elementType = "DELETED";
      c2.stateNode = b2;
      c2.return = a3;
      b2 = a3.deletions;
      null === b2 ? (a3.deletions = [c2], a3.flags |= 16) : b2.push(c2);
    }
    function Zd(a3, b2) {
      switch (a3.tag) {
        case 5:
          return b2 = Fb(b2, a3.type, a3.pendingProps), null !== b2 ? (a3.stateNode = b2, Td = a3, Ud = Mb(b2), true) : false;
        case 6:
          return b2 = Gb(b2, a3.pendingProps), null !== b2 ? (a3.stateNode = b2, Td = a3, Ud = null, true) : false;
        case 13:
          b2 = Hb(b2);
          if (null !== b2) {
            var c2 = null !== Md ? { id: Nd, overflow: Od } : null;
            a3.memoizedState = { dehydrated: b2, treeContext: c2, retryLane: 1073741824 };
            c2 = Yd(18, null, null, 0);
            c2.stateNode = b2;
            c2.return = a3;
            a3.child = c2;
            Td = a3;
            Ud = null;
            return true;
          }
          return false;
        default:
          return false;
      }
    }
    function $d(a3) {
      return 0 !== (a3.mode & 1) && 0 === (a3.flags & 128);
    }
    function ae(a3) {
      if (I2) {
        var b2 = Ud;
        if (b2) {
          var c2 = b2;
          if (!Zd(a3, b2)) {
            if ($d(a3)) throw Error(n2(418));
            b2 = Lb(c2);
            var d2 = Td;
            b2 && Zd(a3, b2) ? Xd(d2, c2) : (a3.flags = a3.flags & -4097 | 2, I2 = false, Td = a3);
          }
        } else {
          if ($d(a3)) throw Error(n2(418));
          a3.flags = a3.flags & -4097 | 2;
          I2 = false;
          Td = a3;
        }
      }
    }
    function be2(a3) {
      for (a3 = a3.return; null !== a3 && 5 !== a3.tag && 3 !== a3.tag && 13 !== a3.tag; ) a3 = a3.return;
      Td = a3;
    }
    function ce2(a3) {
      if (!p2 || a3 !== Td) return false;
      if (!I2) return be2(a3), I2 = true, false;
      if (3 !== a3.tag && (5 !== a3.tag || Xb(a3.type) && !Oa(a3.type, a3.memoizedProps))) {
        var b2 = Ud;
        if (b2) {
          if ($d(a3)) {
            for (a3 = Ud; a3; ) a3 = Lb(a3);
            throw Error(n2(418));
          }
          for (; b2; ) Xd(a3, b2), b2 = Lb(b2);
        }
      }
      be2(a3);
      if (13 === a3.tag) {
        if (!p2) throw Error(n2(316));
        a3 = a3.memoizedState;
        a3 = null !== a3 ? a3.dehydrated : null;
        if (!a3) throw Error(n2(317));
        Ud = Sb(a3);
      } else Ud = Td ? Lb(a3.stateNode) : null;
      return true;
    }
    function de2() {
      p2 && (Ud = Td = null, Vd = I2 = false);
    }
    function ee2(a3) {
      null === Wd ? Wd = [a3] : Wd.push(a3);
    }
    function fe2(a3, b2, c2) {
      a3 = c2.ref;
      if (null !== a3 && "function" !== typeof a3 && "object" !== typeof a3) {
        if (c2._owner) {
          c2 = c2._owner;
          if (c2) {
            if (1 !== c2.tag) throw Error(n2(309));
            var d2 = c2.stateNode;
          }
          if (!d2) throw Error(n2(147, a3));
          var e2 = d2, f2 = "" + a3;
          if (null !== b2 && null !== b2.ref && "function" === typeof b2.ref && b2.ref._stringRef === f2) return b2.ref;
          b2 = function(a4) {
            var b3 = e2.refs;
            b3 === xd && (b3 = e2.refs = {});
            null === a4 ? delete b3[f2] : b3[f2] = a4;
          };
          b2._stringRef = f2;
          return b2;
        }
        if ("string" !== typeof a3) throw Error(n2(284));
        if (!c2._owner) throw Error(n2(290, a3));
      }
      return a3;
    }
    function ge2(a3, b2) {
      a3 = Object.prototype.toString.call(b2);
      throw Error(n2(31, "[object Object]" === a3 ? "object with keys {" + Object.keys(b2).join(", ") + "}" : a3));
    }
    function he2(a3) {
      var b2 = a3._init;
      return b2(a3._payload);
    }
    function ie(a3) {
      function b2(b3, c3) {
        if (a3) {
          var d3 = b3.deletions;
          null === d3 ? (b3.deletions = [c3], b3.flags |= 16) : d3.push(c3);
        }
      }
      function c2(c3, d3) {
        if (!a3) return null;
        for (; null !== d3; ) b2(c3, d3), d3 = d3.sibling;
        return null;
      }
      function d2(a4, b3) {
        for (a4 = /* @__PURE__ */ new Map(); null !== b3; ) null !== b3.key ? a4.set(b3.key, b3) : a4.set(b3.index, b3), b3 = b3.sibling;
        return a4;
      }
      function e2(a4, b3) {
        a4 = je2(a4, b3);
        a4.index = 0;
        a4.sibling = null;
        return a4;
      }
      function f2(b3, c3, d3) {
        b3.index = d3;
        if (!a3) return b3.flags |= 1048576, c3;
        d3 = b3.alternate;
        if (null !== d3) return d3 = d3.index, d3 < c3 ? (b3.flags |= 2, c3) : d3;
        b3.flags |= 2;
        return c3;
      }
      function g2(b3) {
        a3 && null === b3.alternate && (b3.flags |= 2);
        return b3;
      }
      function h2(a4, b3, c3, d3) {
        if (null === b3 || 6 !== b3.tag) return b3 = ke2(c3, a4.mode, d3), b3.return = a4, b3;
        b3 = e2(b3, c3);
        b3.return = a4;
        return b3;
      }
      function k2(a4, b3, c3, d3) {
        var f3 = c3.type;
        if (f3 === ia) return m2(a4, b3, c3.props.children, d3, c3.key);
        if (null !== b3 && (b3.elementType === f3 || "object" === typeof f3 && null !== f3 && f3.$$typeof === ra && he2(f3) === b3.type)) return d3 = e2(b3, c3.props), d3.ref = fe2(a4, b3, c3), d3.return = a4, d3;
        d3 = le2(c3.type, c3.key, c3.props, null, a4.mode, d3);
        d3.ref = fe2(a4, b3, c3);
        d3.return = a4;
        return d3;
      }
      function l2(a4, b3, c3, d3) {
        if (null === b3 || 4 !== b3.tag || b3.stateNode.containerInfo !== c3.containerInfo || b3.stateNode.implementation !== c3.implementation) return b3 = me2(c3, a4.mode, d3), b3.return = a4, b3;
        b3 = e2(b3, c3.children || []);
        b3.return = a4;
        return b3;
      }
      function m2(a4, b3, c3, d3, f3) {
        if (null === b3 || 7 !== b3.tag) return b3 = ne2(c3, a4.mode, d3, f3), b3.return = a4, b3;
        b3 = e2(b3, c3);
        b3.return = a4;
        return b3;
      }
      function v5(a4, b3, c3) {
        if ("string" === typeof b3 && "" !== b3 || "number" === typeof b3) return b3 = ke2("" + b3, a4.mode, c3), b3.return = a4, b3;
        if ("object" === typeof b3 && null !== b3) {
          switch (b3.$$typeof) {
            case fa:
              return c3 = le2(b3.type, b3.key, b3.props, null, a4.mode, c3), c3.ref = fe2(a4, null, b3), c3.return = a4, c3;
            case ha:
              return b3 = me2(b3, a4.mode, c3), b3.return = a4, b3;
            case ra:
              var d3 = b3._init;
              return v5(a4, d3(b3._payload), c3);
          }
          if (Ea(b3) || ua2(b3)) return b3 = ne2(b3, a4.mode, c3, null), b3.return = a4, b3;
          ge2(a4, b3);
        }
        return null;
      }
      function r2(a4, b3, c3, d3) {
        var e3 = null !== b3 ? b3.key : null;
        if ("string" === typeof c3 && "" !== c3 || "number" === typeof c3) return null !== e3 ? null : h2(a4, b3, "" + c3, d3);
        if ("object" === typeof c3 && null !== c3) {
          switch (c3.$$typeof) {
            case fa:
              return c3.key === e3 ? k2(a4, b3, c3, d3) : null;
            case ha:
              return c3.key === e3 ? l2(a4, b3, c3, d3) : null;
            case ra:
              return e3 = c3._init, r2(
                a4,
                b3,
                e3(c3._payload),
                d3
              );
          }
          if (Ea(c3) || ua2(c3)) return null !== e3 ? null : m2(a4, b3, c3, d3, null);
          ge2(a4, c3);
        }
        return null;
      }
      function z2(a4, b3, c3, d3, e3) {
        if ("string" === typeof d3 && "" !== d3 || "number" === typeof d3) return a4 = a4.get(c3) || null, h2(b3, a4, "" + d3, e3);
        if ("object" === typeof d3 && null !== d3) {
          switch (d3.$$typeof) {
            case fa:
              return a4 = a4.get(null === d3.key ? c3 : d3.key) || null, k2(b3, a4, d3, e3);
            case ha:
              return a4 = a4.get(null === d3.key ? c3 : d3.key) || null, l2(b3, a4, d3, e3);
            case ra:
              var f3 = d3._init;
              return z2(a4, b3, c3, f3(d3._payload), e3);
          }
          if (Ea(d3) || ua2(d3)) return a4 = a4.get(c3) || null, m2(b3, a4, d3, e3, null);
          ge2(b3, d3);
        }
        return null;
      }
      function q3(e3, g3, h3, k3) {
        for (var l3 = null, m3 = null, w2 = g3, u2 = g3 = 0, t2 = null; null !== w2 && u2 < h3.length; u2++) {
          w2.index > u2 ? (t2 = w2, w2 = null) : t2 = w2.sibling;
          var q4 = r2(e3, w2, h3[u2], k3);
          if (null === q4) {
            null === w2 && (w2 = t2);
            break;
          }
          a3 && w2 && null === q4.alternate && b2(e3, w2);
          g3 = f2(q4, g3, u2);
          null === m3 ? l3 = q4 : m3.sibling = q4;
          m3 = q4;
          w2 = t2;
        }
        if (u2 === h3.length) return c2(e3, w2), I2 && Pd(e3, u2), l3;
        if (null === w2) {
          for (; u2 < h3.length; u2++) w2 = v5(e3, h3[u2], k3), null !== w2 && (g3 = f2(w2, g3, u2), null === m3 ? l3 = w2 : m3.sibling = w2, m3 = w2);
          I2 && Pd(e3, u2);
          return l3;
        }
        for (w2 = d2(e3, w2); u2 < h3.length; u2++) t2 = z2(w2, e3, u2, h3[u2], k3), null !== t2 && (a3 && null !== t2.alternate && w2.delete(null === t2.key ? u2 : t2.key), g3 = f2(t2, g3, u2), null === m3 ? l3 = t2 : m3.sibling = t2, m3 = t2);
        a3 && w2.forEach(function(a4) {
          return b2(e3, a4);
        });
        I2 && Pd(e3, u2);
        return l3;
      }
      function N2(e3, g3, h3, k3) {
        var l3 = ua2(h3);
        if ("function" !== typeof l3) throw Error(n2(150));
        h3 = l3.call(h3);
        if (null == h3) throw Error(n2(151));
        for (var w2 = l3 = null, m3 = g3, u2 = g3 = 0, q4 = null, t2 = h3.next(); null !== m3 && !t2.done; u2++, t2 = h3.next()) {
          m3.index > u2 ? (q4 = m3, m3 = null) : q4 = m3.sibling;
          var V2 = r2(e3, m3, t2.value, k3);
          if (null === V2) {
            null === m3 && (m3 = q4);
            break;
          }
          a3 && m3 && null === V2.alternate && b2(e3, m3);
          g3 = f2(V2, g3, u2);
          null === w2 ? l3 = V2 : w2.sibling = V2;
          w2 = V2;
          m3 = q4;
        }
        if (t2.done) return c2(
          e3,
          m3
        ), I2 && Pd(e3, u2), l3;
        if (null === m3) {
          for (; !t2.done; u2++, t2 = h3.next()) t2 = v5(e3, t2.value, k3), null !== t2 && (g3 = f2(t2, g3, u2), null === w2 ? l3 = t2 : w2.sibling = t2, w2 = t2);
          I2 && Pd(e3, u2);
          return l3;
        }
        for (m3 = d2(e3, m3); !t2.done; u2++, t2 = h3.next()) t2 = z2(m3, e3, u2, t2.value, k3), null !== t2 && (a3 && null !== t2.alternate && m3.delete(null === t2.key ? u2 : t2.key), g3 = f2(t2, g3, u2), null === w2 ? l3 = t2 : w2.sibling = t2, w2 = t2);
        a3 && m3.forEach(function(a4) {
          return b2(e3, a4);
        });
        I2 && Pd(e3, u2);
        return l3;
      }
      function da2(a4, d3, f3, h3) {
        "object" === typeof f3 && null !== f3 && f3.type === ia && null === f3.key && (f3 = f3.props.children);
        if ("object" === typeof f3 && null !== f3) {
          switch (f3.$$typeof) {
            case fa:
              a: {
                for (var k3 = f3.key, l3 = d3; null !== l3; ) {
                  if (l3.key === k3) {
                    k3 = f3.type;
                    if (k3 === ia) {
                      if (7 === l3.tag) {
                        c2(a4, l3.sibling);
                        d3 = e2(l3, f3.props.children);
                        d3.return = a4;
                        a4 = d3;
                        break a;
                      }
                    } else if (l3.elementType === k3 || "object" === typeof k3 && null !== k3 && k3.$$typeof === ra && he2(k3) === l3.type) {
                      c2(a4, l3.sibling);
                      d3 = e2(l3, f3.props);
                      d3.ref = fe2(a4, l3, f3);
                      d3.return = a4;
                      a4 = d3;
                      break a;
                    }
                    c2(a4, l3);
                    break;
                  } else b2(a4, l3);
                  l3 = l3.sibling;
                }
                f3.type === ia ? (d3 = ne2(f3.props.children, a4.mode, h3, f3.key), d3.return = a4, a4 = d3) : (h3 = le2(f3.type, f3.key, f3.props, null, a4.mode, h3), h3.ref = fe2(a4, d3, f3), h3.return = a4, a4 = h3);
              }
              return g2(a4);
            case ha:
              a: {
                for (l3 = f3.key; null !== d3; ) {
                  if (d3.key === l3) if (4 === d3.tag && d3.stateNode.containerInfo === f3.containerInfo && d3.stateNode.implementation === f3.implementation) {
                    c2(a4, d3.sibling);
                    d3 = e2(d3, f3.children || []);
                    d3.return = a4;
                    a4 = d3;
                    break a;
                  } else {
                    c2(a4, d3);
                    break;
                  }
                  else b2(a4, d3);
                  d3 = d3.sibling;
                }
                d3 = me2(f3, a4.mode, h3);
                d3.return = a4;
                a4 = d3;
              }
              return g2(a4);
            case ra:
              return l3 = f3._init, da2(a4, d3, l3(f3._payload), h3);
          }
          if (Ea(f3)) return q3(a4, d3, f3, h3);
          if (ua2(f3)) return N2(a4, d3, f3, h3);
          ge2(a4, f3);
        }
        return "string" === typeof f3 && "" !== f3 || "number" === typeof f3 ? (f3 = "" + f3, null !== d3 && 6 === d3.tag ? (c2(a4, d3.sibling), d3 = e2(d3, f3), d3.return = a4, a4 = d3) : (c2(a4, d3), d3 = ke2(f3, a4.mode, h3), d3.return = a4, a4 = d3), g2(a4)) : c2(a4, d3);
      }
      return da2;
    }
    var oe2 = ie(true), pe = ie(false), qe2 = {}, re2 = gc(qe2), se = gc(qe2), te2 = gc(qe2);
    function ue3(a3) {
      if (a3 === qe2) throw Error(n2(174));
      return a3;
    }
    function ve2(a3, b2) {
      y2(te2, b2);
      y2(se, a3);
      y2(re2, qe2);
      a3 = Ga(b2);
      x(re2);
      y2(re2, a3);
    }
    function we2() {
      x(re2);
      x(se);
      x(te2);
    }
    function xe2(a3) {
      var b2 = ue3(te2.current), c2 = ue3(re2.current);
      b2 = Ha(c2, a3.type, b2);
      c2 !== b2 && (y2(se, a3), y2(re2, b2));
    }
    function ye2(a3) {
      se.current === a3 && (x(re2), x(se));
    }
    var J2 = gc(0);
    function ze2(a3) {
      for (var b2 = a3; null !== b2; ) {
        if (13 === b2.tag) {
          var c2 = b2.memoizedState;
          if (null !== c2 && (c2 = c2.dehydrated, null === c2 || Ib(c2) || Jb(c2))) return b2;
        } else if (19 === b2.tag && void 0 !== b2.memoizedProps.revealOrder) {
          if (0 !== (b2.flags & 128)) return b2;
        } else if (null !== b2.child) {
          b2.child.return = b2;
          b2 = b2.child;
          continue;
        }
        if (b2 === a3) break;
        for (; null === b2.sibling; ) {
          if (null === b2.return || b2.return === a3) return null;
          b2 = b2.return;
        }
        b2.sibling.return = b2.return;
        b2 = b2.sibling;
      }
      return null;
    }
    var Ae2 = [];
    function Be2() {
      for (var a3 = 0; a3 < Ae2.length; a3++) {
        var b2 = Ae2[a3];
        Ta ? b2._workInProgressVersionPrimary = null : b2._workInProgressVersionSecondary = null;
      }
      Ae2.length = 0;
    }
    var Ce2 = ea2.ReactCurrentDispatcher, De2 = ea2.ReactCurrentBatchConfig, Ee2 = 0, K2 = null, L2 = null, M2 = null, Fe2 = false, Ge2 = false, He2 = 0, Ie2 = 0;
    function O2() {
      throw Error(n2(321));
    }
    function Je2(a3, b2) {
      if (null === b2) return false;
      for (var c2 = 0; c2 < b2.length && c2 < a3.length; c2++) if (!Rc(a3[c2], b2[c2])) return false;
      return true;
    }
    function Ke2(a3, b2, c2, d2, e2, f2) {
      Ee2 = f2;
      K2 = b2;
      b2.memoizedState = null;
      b2.updateQueue = null;
      b2.lanes = 0;
      Ce2.current = null === a3 || null === a3.memoizedState ? Le2 : Me2;
      a3 = c2(d2, e2);
      if (Ge2) {
        f2 = 0;
        do {
          Ge2 = false;
          He2 = 0;
          if (25 <= f2) throw Error(n2(301));
          f2 += 1;
          M2 = L2 = null;
          b2.updateQueue = null;
          Ce2.current = Ne2;
          a3 = c2(d2, e2);
        } while (Ge2);
      }
      Ce2.current = Oe2;
      b2 = null !== L2 && null !== L2.next;
      Ee2 = 0;
      M2 = L2 = K2 = null;
      Fe2 = false;
      if (b2) throw Error(n2(300));
      return a3;
    }
    function Pe2() {
      var a3 = 0 !== He2;
      He2 = 0;
      return a3;
    }
    function Qe2() {
      var a3 = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
      null === M2 ? K2.memoizedState = M2 = a3 : M2 = M2.next = a3;
      return M2;
    }
    function Re2() {
      if (null === L2) {
        var a3 = K2.alternate;
        a3 = null !== a3 ? a3.memoizedState : null;
      } else a3 = L2.next;
      var b2 = null === M2 ? K2.memoizedState : M2.next;
      if (null !== b2) M2 = b2, L2 = a3;
      else {
        if (null === a3) throw Error(n2(310));
        L2 = a3;
        a3 = { memoizedState: L2.memoizedState, baseState: L2.baseState, baseQueue: L2.baseQueue, queue: L2.queue, next: null };
        null === M2 ? K2.memoizedState = M2 = a3 : M2 = M2.next = a3;
      }
      return M2;
    }
    function Se2(a3, b2) {
      return "function" === typeof b2 ? b2(a3) : b2;
    }
    function Te2(a3) {
      var b2 = Re2(), c2 = b2.queue;
      if (null === c2) throw Error(n2(311));
      c2.lastRenderedReducer = a3;
      var d2 = L2, e2 = d2.baseQueue, f2 = c2.pending;
      if (null !== f2) {
        if (null !== e2) {
          var g2 = e2.next;
          e2.next = f2.next;
          f2.next = g2;
        }
        d2.baseQueue = e2 = f2;
        c2.pending = null;
      }
      if (null !== e2) {
        f2 = e2.next;
        d2 = d2.baseState;
        var h2 = g2 = null, k2 = null, l2 = f2;
        do {
          var m2 = l2.lane;
          if ((Ee2 & m2) === m2) null !== k2 && (k2 = k2.next = { lane: 0, action: l2.action, hasEagerState: l2.hasEagerState, eagerState: l2.eagerState, next: null }), d2 = l2.hasEagerState ? l2.eagerState : a3(d2, l2.action);
          else {
            var v5 = {
              lane: m2,
              action: l2.action,
              hasEagerState: l2.hasEagerState,
              eagerState: l2.eagerState,
              next: null
            };
            null === k2 ? (h2 = k2 = v5, g2 = d2) : k2 = k2.next = v5;
            K2.lanes |= m2;
            vd |= m2;
          }
          l2 = l2.next;
        } while (null !== l2 && l2 !== f2);
        null === k2 ? g2 = d2 : k2.next = h2;
        Rc(d2, b2.memoizedState) || (kd = true);
        b2.memoizedState = d2;
        b2.baseState = g2;
        b2.baseQueue = k2;
        c2.lastRenderedState = d2;
      }
      a3 = c2.interleaved;
      if (null !== a3) {
        e2 = a3;
        do
          f2 = e2.lane, K2.lanes |= f2, vd |= f2, e2 = e2.next;
        while (e2 !== a3);
      } else null === e2 && (c2.lanes = 0);
      return [b2.memoizedState, c2.dispatch];
    }
    function Ue2(a3) {
      var b2 = Re2(), c2 = b2.queue;
      if (null === c2) throw Error(n2(311));
      c2.lastRenderedReducer = a3;
      var d2 = c2.dispatch, e2 = c2.pending, f2 = b2.memoizedState;
      if (null !== e2) {
        c2.pending = null;
        var g2 = e2 = e2.next;
        do
          f2 = a3(f2, g2.action), g2 = g2.next;
        while (g2 !== e2);
        Rc(f2, b2.memoizedState) || (kd = true);
        b2.memoizedState = f2;
        null === b2.baseQueue && (b2.baseState = f2);
        c2.lastRenderedState = f2;
      }
      return [f2, d2];
    }
    function Ve2() {
    }
    function We2(a3, b2) {
      var c2 = K2, d2 = Re2(), e2 = b2(), f2 = !Rc(d2.memoizedState, e2);
      f2 && (d2.memoizedState = e2, kd = true);
      d2 = d2.queue;
      Xe2(Ye2.bind(null, c2, d2, a3), [a3]);
      if (d2.getSnapshot !== b2 || f2 || null !== M2 && M2.memoizedState.tag & 1) {
        c2.flags |= 2048;
        Ze2(9, $e2.bind(null, c2, d2, e2, b2), void 0, null);
        if (null === F2) throw Error(n2(349));
        0 !== (Ee2 & 30) || af(c2, b2, e2);
      }
      return e2;
    }
    function af(a3, b2, c2) {
      a3.flags |= 16384;
      a3 = { getSnapshot: b2, value: c2 };
      b2 = K2.updateQueue;
      null === b2 ? (b2 = { lastEffect: null, stores: null }, K2.updateQueue = b2, b2.stores = [a3]) : (c2 = b2.stores, null === c2 ? b2.stores = [a3] : c2.push(a3));
    }
    function $e2(a3, b2, c2, d2) {
      b2.value = c2;
      b2.getSnapshot = d2;
      bf(b2) && Ad(a3, 1, -1);
    }
    function Ye2(a3, b2, c2) {
      return c2(function() {
        bf(b2) && Ad(a3, 1, -1);
      });
    }
    function bf(a3) {
      var b2 = a3.getSnapshot;
      a3 = a3.value;
      try {
        var c2 = b2();
        return !Rc(a3, c2);
      } catch (d2) {
        return true;
      }
    }
    function cf(a3) {
      var b2 = Qe2();
      "function" === typeof a3 && (a3 = a3());
      b2.memoizedState = b2.baseState = a3;
      a3 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Se2, lastRenderedState: a3 };
      b2.queue = a3;
      a3 = a3.dispatch = df.bind(null, K2, a3);
      return [b2.memoizedState, a3];
    }
    function Ze2(a3, b2, c2, d2) {
      a3 = { tag: a3, create: b2, destroy: c2, deps: d2, next: null };
      b2 = K2.updateQueue;
      null === b2 ? (b2 = { lastEffect: null, stores: null }, K2.updateQueue = b2, b2.lastEffect = a3.next = a3) : (c2 = b2.lastEffect, null === c2 ? b2.lastEffect = a3.next = a3 : (d2 = c2.next, c2.next = a3, a3.next = d2, b2.lastEffect = a3));
      return a3;
    }
    function ef() {
      return Re2().memoizedState;
    }
    function ff(a3, b2, c2, d2) {
      var e2 = Qe2();
      K2.flags |= a3;
      e2.memoizedState = Ze2(1 | b2, c2, void 0, void 0 === d2 ? null : d2);
    }
    function gf(a3, b2, c2, d2) {
      var e2 = Re2();
      d2 = void 0 === d2 ? null : d2;
      var f2 = void 0;
      if (null !== L2) {
        var g2 = L2.memoizedState;
        f2 = g2.destroy;
        if (null !== d2 && Je2(d2, g2.deps)) {
          e2.memoizedState = Ze2(b2, c2, f2, d2);
          return;
        }
      }
      K2.flags |= a3;
      e2.memoizedState = Ze2(1 | b2, c2, f2, d2);
    }
    function hf(a3, b2) {
      return ff(8390656, 8, a3, b2);
    }
    function Xe2(a3, b2) {
      return gf(2048, 8, a3, b2);
    }
    function jf(a3, b2) {
      return gf(4, 2, a3, b2);
    }
    function kf(a3, b2) {
      return gf(4, 4, a3, b2);
    }
    function lf(a3, b2) {
      if ("function" === typeof b2) return a3 = a3(), b2(a3), function() {
        b2(null);
      };
      if (null !== b2 && void 0 !== b2) return a3 = a3(), b2.current = a3, function() {
        b2.current = null;
      };
    }
    function mf(a3, b2, c2) {
      c2 = null !== c2 && void 0 !== c2 ? c2.concat([a3]) : null;
      return gf(4, 4, lf.bind(null, b2, a3), c2);
    }
    function nf() {
    }
    function of(a3, b2) {
      var c2 = Re2();
      b2 = void 0 === b2 ? null : b2;
      var d2 = c2.memoizedState;
      if (null !== d2 && null !== b2 && Je2(b2, d2[1])) return d2[0];
      c2.memoizedState = [a3, b2];
      return a3;
    }
    function pf(a3, b2) {
      var c2 = Re2();
      b2 = void 0 === b2 ? null : b2;
      var d2 = c2.memoizedState;
      if (null !== d2 && null !== b2 && Je2(b2, d2[1])) return d2[0];
      a3 = a3();
      c2.memoizedState = [a3, b2];
      return a3;
    }
    function qf(a3, b2) {
      var c2 = D2;
      D2 = 0 !== c2 && 4 > c2 ? c2 : 4;
      a3(true);
      var d2 = De2.transition;
      De2.transition = {};
      try {
        a3(false), b2();
      } finally {
        D2 = c2, De2.transition = d2;
      }
    }
    function rf() {
      return Re2().memoizedState;
    }
    function sf(a3, b2, c2) {
      var d2 = zd(a3);
      c2 = { lane: d2, action: c2, hasEagerState: false, eagerState: null, next: null };
      tf(a3) ? uf(b2, c2) : (vf(a3, b2, c2), c2 = H2(), a3 = Ad(a3, d2, c2), null !== a3 && wf(a3, b2, d2));
    }
    function df(a3, b2, c2) {
      var d2 = zd(a3), e2 = { lane: d2, action: c2, hasEagerState: false, eagerState: null, next: null };
      if (tf(a3)) uf(b2, e2);
      else {
        vf(a3, b2, e2);
        var f2 = a3.alternate;
        if (0 === a3.lanes && (null === f2 || 0 === f2.lanes) && (f2 = b2.lastRenderedReducer, null !== f2)) try {
          var g2 = b2.lastRenderedState, h2 = f2(g2, c2);
          e2.hasEagerState = true;
          e2.eagerState = h2;
          if (Rc(h2, g2)) return;
        } catch (k2) {
        } finally {
        }
        c2 = H2();
        a3 = Ad(a3, d2, c2);
        null !== a3 && wf(a3, b2, d2);
      }
    }
    function tf(a3) {
      var b2 = a3.alternate;
      return a3 === K2 || null !== b2 && b2 === K2;
    }
    function uf(a3, b2) {
      Ge2 = Fe2 = true;
      var c2 = a3.pending;
      null === c2 ? b2.next = b2 : (b2.next = c2.next, c2.next = b2);
      a3.pending = b2;
    }
    function vf(a3, b2, c2) {
      null !== F2 && 0 !== (a3.mode & 1) && 0 === (G2 & 2) ? (a3 = b2.interleaved, null === a3 ? (c2.next = c2, null === md ? md = [b2] : md.push(b2)) : (c2.next = a3.next, a3.next = c2), b2.interleaved = c2) : (a3 = b2.pending, null === a3 ? c2.next = c2 : (c2.next = a3.next, a3.next = c2), b2.pending = c2);
    }
    function wf(a3, b2, c2) {
      if (0 !== (c2 & 4194240)) {
        var d2 = b2.lanes;
        d2 &= a3.pendingLanes;
        c2 |= d2;
        b2.lanes = c2;
        Dc(a3, c2);
      }
    }
    var Oe2 = { readContext: ld, useCallback: O2, useContext: O2, useEffect: O2, useImperativeHandle: O2, useInsertionEffect: O2, useLayoutEffect: O2, useMemo: O2, useReducer: O2, useRef: O2, useState: O2, useDebugValue: O2, useDeferredValue: O2, useTransition: O2, useMutableSource: O2, useSyncExternalStore: O2, useId: O2, unstable_isNewReconciler: false }, Le2 = { readContext: ld, useCallback: function(a3, b2) {
      Qe2().memoizedState = [a3, void 0 === b2 ? null : b2];
      return a3;
    }, useContext: ld, useEffect: hf, useImperativeHandle: function(a3, b2, c2) {
      c2 = null !== c2 && void 0 !== c2 ? c2.concat([a3]) : null;
      return ff(
        4194308,
        4,
        lf.bind(null, b2, a3),
        c2
      );
    }, useLayoutEffect: function(a3, b2) {
      return ff(4194308, 4, a3, b2);
    }, useInsertionEffect: function(a3, b2) {
      return ff(4, 2, a3, b2);
    }, useMemo: function(a3, b2) {
      var c2 = Qe2();
      b2 = void 0 === b2 ? null : b2;
      a3 = a3();
      c2.memoizedState = [a3, b2];
      return a3;
    }, useReducer: function(a3, b2, c2) {
      var d2 = Qe2();
      b2 = void 0 !== c2 ? c2(b2) : b2;
      d2.memoizedState = d2.baseState = b2;
      a3 = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a3, lastRenderedState: b2 };
      d2.queue = a3;
      a3 = a3.dispatch = sf.bind(null, K2, a3);
      return [d2.memoizedState, a3];
    }, useRef: function(a3) {
      var b2 = Qe2();
      a3 = { current: a3 };
      return b2.memoizedState = a3;
    }, useState: cf, useDebugValue: nf, useDeferredValue: function(a3) {
      var b2 = cf(a3), c2 = b2[0], d2 = b2[1];
      hf(function() {
        var b3 = De2.transition;
        De2.transition = {};
        try {
          d2(a3);
        } finally {
          De2.transition = b3;
        }
      }, [a3]);
      return c2;
    }, useTransition: function() {
      var a3 = cf(false), b2 = a3[0];
      a3 = qf.bind(null, a3[1]);
      Qe2().memoizedState = a3;
      return [b2, a3];
    }, useMutableSource: function() {
    }, useSyncExternalStore: function(a3, b2, c2) {
      var d2 = K2, e2 = Qe2();
      if (I2) {
        if (void 0 === c2) throw Error(n2(407));
        c2 = c2();
      } else {
        c2 = b2();
        if (null === F2) throw Error(n2(349));
        0 !== (Ee2 & 30) || af(d2, b2, c2);
      }
      e2.memoizedState = c2;
      var f2 = { value: c2, getSnapshot: b2 };
      e2.queue = f2;
      hf(Ye2.bind(null, d2, f2, a3), [a3]);
      d2.flags |= 2048;
      Ze2(9, $e2.bind(null, d2, f2, c2, b2), void 0, null);
      return c2;
    }, useId: function() {
      var a3 = Qe2(), b2 = F2.identifierPrefix;
      if (I2) {
        var c2 = Od;
        var d2 = Nd;
        c2 = (d2 & ~(1 << 32 - qc(d2) - 1)).toString(32) + c2;
        b2 = ":" + b2 + "R" + c2;
        c2 = He2++;
        0 < c2 && (b2 += "H" + c2.toString(32));
        b2 += ":";
      } else c2 = Ie2++, b2 = ":" + b2 + "r" + c2.toString(32) + ":";
      return a3.memoizedState = b2;
    }, unstable_isNewReconciler: false }, Me2 = {
      readContext: ld,
      useCallback: of,
      useContext: ld,
      useEffect: Xe2,
      useImperativeHandle: mf,
      useInsertionEffect: jf,
      useLayoutEffect: kf,
      useMemo: pf,
      useReducer: Te2,
      useRef: ef,
      useState: function() {
        return Te2(Se2);
      },
      useDebugValue: nf,
      useDeferredValue: function(a3) {
        var b2 = Te2(Se2), c2 = b2[0], d2 = b2[1];
        Xe2(function() {
          var b3 = De2.transition;
          De2.transition = {};
          try {
            d2(a3);
          } finally {
            De2.transition = b3;
          }
        }, [a3]);
        return c2;
      },
      useTransition: function() {
        var a3 = Te2(Se2)[0], b2 = Re2().memoizedState;
        return [a3, b2];
      },
      useMutableSource: Ve2,
      useSyncExternalStore: We2,
      useId: rf,
      unstable_isNewReconciler: false
    }, Ne2 = {
      readContext: ld,
      useCallback: of,
      useContext: ld,
      useEffect: Xe2,
      useImperativeHandle: mf,
      useInsertionEffect: jf,
      useLayoutEffect: kf,
      useMemo: pf,
      useReducer: Ue2,
      useRef: ef,
      useState: function() {
        return Ue2(Se2);
      },
      useDebugValue: nf,
      useDeferredValue: function(a3) {
        var b2 = Ue2(Se2), c2 = b2[0], d2 = b2[1];
        Xe2(function() {
          var b3 = De2.transition;
          De2.transition = {};
          try {
            d2(a3);
          } finally {
            De2.transition = b3;
          }
        }, [a3]);
        return c2;
      },
      useTransition: function() {
        var a3 = Ue2(Se2)[0], b2 = Re2().memoizedState;
        return [a3, b2];
      },
      useMutableSource: Ve2,
      useSyncExternalStore: We2,
      useId: rf,
      unstable_isNewReconciler: false
    };
    function xf(a3, b2) {
      try {
        var c2 = "", d2 = b2;
        do
          c2 += $c(d2), d2 = d2.return;
        while (d2);
        var e2 = c2;
      } catch (f2) {
        e2 = "\nError generating stack: " + f2.message + "\n" + f2.stack;
      }
      return { value: a3, source: b2, stack: e2 };
    }
    function yf(a3, b2) {
      try {
        console.error(b2.value);
      } catch (c2) {
        setTimeout(function() {
          throw c2;
        });
      }
    }
    var zf = "function" === typeof WeakMap ? WeakMap : Map;
    function Af(a3, b2, c2) {
      c2 = qd(-1, c2);
      c2.tag = 3;
      c2.payload = { element: null };
      var d2 = b2.value;
      c2.callback = function() {
        Bf || (Bf = true, Cf = d2);
        yf(a3, b2);
      };
      return c2;
    }
    function Df(a3, b2, c2) {
      c2 = qd(-1, c2);
      c2.tag = 3;
      var d2 = a3.type.getDerivedStateFromError;
      if ("function" === typeof d2) {
        var e2 = b2.value;
        c2.payload = function() {
          return d2(e2);
        };
        c2.callback = function() {
          yf(a3, b2);
        };
      }
      var f2 = a3.stateNode;
      null !== f2 && "function" === typeof f2.componentDidCatch && (c2.callback = function() {
        yf(a3, b2);
        "function" !== typeof d2 && (null === Ef ? Ef = /* @__PURE__ */ new Set([this]) : Ef.add(this));
        var c3 = b2.stack;
        this.componentDidCatch(b2.value, { componentStack: null !== c3 ? c3 : "" });
      });
      return c2;
    }
    function Ff(a3, b2, c2) {
      var d2 = a3.pingCache;
      if (null === d2) {
        d2 = a3.pingCache = new zf();
        var e2 = /* @__PURE__ */ new Set();
        d2.set(b2, e2);
      } else e2 = d2.get(b2), void 0 === e2 && (e2 = /* @__PURE__ */ new Set(), d2.set(b2, e2));
      e2.has(c2) || (e2.add(c2), a3 = Gf.bind(null, a3, b2, c2), b2.then(a3, a3));
    }
    function Hf(a3) {
      do {
        var b2;
        if (b2 = 13 === a3.tag) b2 = a3.memoizedState, b2 = null !== b2 ? null !== b2.dehydrated ? true : false : true;
        if (b2) return a3;
        a3 = a3.return;
      } while (null !== a3);
      return null;
    }
    function If(a3, b2, c2, d2, e2) {
      if (0 === (a3.mode & 1)) return a3 === b2 ? a3.flags |= 65536 : (a3.flags |= 128, c2.flags |= 131072, c2.flags &= -52805, 1 === c2.tag && (null === c2.alternate ? c2.tag = 17 : (b2 = qd(-1, 1), b2.tag = 2, rd(c2, b2))), c2.lanes |= 1), a3;
      a3.flags |= 65536;
      a3.lanes = e2;
      return a3;
    }
    function Jf(a3) {
      a3.flags |= 4;
    }
    function Kf(a3, b2) {
      if (null !== a3 && a3.child === b2.child) return true;
      if (0 !== (b2.flags & 16)) return false;
      for (a3 = b2.child; null !== a3; ) {
        if (0 !== (a3.flags & 12854) || 0 !== (a3.subtreeFlags & 12854)) return false;
        a3 = a3.sibling;
      }
      return true;
    }
    var Lf, Mf, Nf, Of;
    if (Ua) Lf = function(a3, b2) {
      for (var c2 = b2.child; null !== c2; ) {
        if (5 === c2.tag || 6 === c2.tag) La(a3, c2.stateNode);
        else if (4 !== c2.tag && null !== c2.child) {
          c2.child.return = c2;
          c2 = c2.child;
          continue;
        }
        if (c2 === b2) break;
        for (; null === c2.sibling; ) {
          if (null === c2.return || c2.return === b2) return;
          c2 = c2.return;
        }
        c2.sibling.return = c2.return;
        c2 = c2.sibling;
      }
    }, Mf = function() {
    }, Nf = function(a3, b2, c2, d2, e2) {
      a3 = a3.memoizedProps;
      if (a3 !== d2) {
        var f2 = b2.stateNode, g2 = ue3(re2.current);
        c2 = Na(f2, c2, a3, d2, e2, g2);
        (b2.updateQueue = c2) && Jf(b2);
      }
    }, Of = function(a3, b2, c2, d2) {
      c2 !== d2 && Jf(b2);
    };
    else if (Va) {
      Lf = function(a3, b2, c2, d2) {
        for (var e2 = b2.child; null !== e2; ) {
          if (5 === e2.tag) {
            var f2 = e2.stateNode;
            c2 && d2 && (f2 = Db(f2, e2.type, e2.memoizedProps, e2));
            La(a3, f2);
          } else if (6 === e2.tag) f2 = e2.stateNode, c2 && d2 && (f2 = Eb(f2, e2.memoizedProps, e2)), La(a3, f2);
          else if (4 !== e2.tag) {
            if (22 === e2.tag && null !== e2.memoizedState) f2 = e2.child, null !== f2 && (f2.return = e2), Lf(a3, e2, true, true);
            else if (null !== e2.child) {
              e2.child.return = e2;
              e2 = e2.child;
              continue;
            }
          }
          if (e2 === b2) break;
          for (; null === e2.sibling; ) {
            if (null === e2.return || e2.return === b2) return;
            e2 = e2.return;
          }
          e2.sibling.return = e2.return;
          e2 = e2.sibling;
        }
      };
      var Pf = function(a3, b2, c2, d2) {
        for (var e2 = b2.child; null !== e2; ) {
          if (5 === e2.tag) {
            var f2 = e2.stateNode;
            c2 && d2 && (f2 = Db(f2, e2.type, e2.memoizedProps, e2));
            Ab(a3, f2);
          } else if (6 === e2.tag) f2 = e2.stateNode, c2 && d2 && (f2 = Eb(f2, e2.memoizedProps, e2)), Ab(a3, f2);
          else if (4 !== e2.tag) {
            if (22 === e2.tag && null !== e2.memoizedState) f2 = e2.child, null !== f2 && (f2.return = e2), Pf(a3, e2, true, true);
            else if (null !== e2.child) {
              e2.child.return = e2;
              e2 = e2.child;
              continue;
            }
          }
          if (e2 === b2) break;
          for (; null === e2.sibling; ) {
            if (null === e2.return || e2.return === b2) return;
            e2 = e2.return;
          }
          e2.sibling.return = e2.return;
          e2 = e2.sibling;
        }
      };
      Mf = function(a3, b2) {
        var c2 = b2.stateNode;
        if (!Kf(a3, b2)) {
          a3 = c2.containerInfo;
          var d2 = zb(a3);
          Pf(d2, b2, false, false);
          c2.pendingChildren = d2;
          Jf(b2);
          Bb(a3, d2);
        }
      };
      Nf = function(a3, b2, c2, d2, e2) {
        var f2 = a3.stateNode, g2 = a3.memoizedProps;
        if ((a3 = Kf(a3, b2)) && g2 === d2) b2.stateNode = f2;
        else {
          var h2 = b2.stateNode, k2 = ue3(re2.current), l2 = null;
          g2 !== d2 && (l2 = Na(h2, c2, g2, d2, e2, k2));
          a3 && null === l2 ? b2.stateNode = f2 : (f2 = yb(f2, l2, c2, g2, d2, b2, a3, h2), Ma(f2, c2, d2, e2, k2) && Jf(b2), b2.stateNode = f2, a3 ? Jf(b2) : Lf(f2, b2, false, false));
        }
      };
      Of = function(a3, b2, c2, d2) {
        c2 !== d2 ? (a3 = ue3(te2.current), c2 = ue3(re2.current), b2.stateNode = Pa(d2, a3, c2, b2), Jf(b2)) : b2.stateNode = a3.stateNode;
      };
    } else Mf = function() {
    }, Nf = function() {
    }, Of = function() {
    };
    function Qf(a3, b2) {
      if (!I2) switch (a3.tailMode) {
        case "hidden":
          b2 = a3.tail;
          for (var c2 = null; null !== b2; ) null !== b2.alternate && (c2 = b2), b2 = b2.sibling;
          null === c2 ? a3.tail = null : c2.sibling = null;
          break;
        case "collapsed":
          c2 = a3.tail;
          for (var d2 = null; null !== c2; ) null !== c2.alternate && (d2 = c2), c2 = c2.sibling;
          null === d2 ? b2 || null === a3.tail ? a3.tail = null : a3.tail.sibling = null : d2.sibling = null;
      }
    }
    function P2(a3) {
      var b2 = null !== a3.alternate && a3.alternate.child === a3.child, c2 = 0, d2 = 0;
      if (b2) for (var e2 = a3.child; null !== e2; ) c2 |= e2.lanes | e2.childLanes, d2 |= e2.subtreeFlags & 14680064, d2 |= e2.flags & 14680064, e2.return = a3, e2 = e2.sibling;
      else for (e2 = a3.child; null !== e2; ) c2 |= e2.lanes | e2.childLanes, d2 |= e2.subtreeFlags, d2 |= e2.flags, e2.return = a3, e2 = e2.sibling;
      a3.subtreeFlags |= d2;
      a3.childLanes = c2;
      return b2;
    }
    function Rf(a3, b2, c2) {
      var d2 = b2.pendingProps;
      Sd(b2);
      switch (b2.tag) {
        case 2:
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return P2(b2), null;
        case 1:
          return C2(b2.type) && kc(), P2(b2), null;
        case 3:
          d2 = b2.stateNode;
          we2();
          x(B);
          x(A2);
          Be2();
          d2.pendingContext && (d2.context = d2.pendingContext, d2.pendingContext = null);
          if (null === a3 || null === a3.child) ce2(b2) ? Jf(b2) : null === a3 || a3.memoizedState.isDehydrated && 0 === (b2.flags & 256) || (b2.flags |= 1024, null !== Wd && (Sf(Wd), Wd = null));
          Mf(a3, b2);
          P2(b2);
          return null;
        case 5:
          ye2(b2);
          c2 = ue3(te2.current);
          var e2 = b2.type;
          if (null !== a3 && null != b2.stateNode) Nf(a3, b2, e2, d2, c2), a3.ref !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
          else {
            if (!d2) {
              if (null === b2.stateNode) throw Error(n2(166));
              P2(b2);
              return null;
            }
            a3 = ue3(re2.current);
            if (ce2(b2)) {
              if (!p2) throw Error(n2(175));
              a3 = Pb(b2.stateNode, b2.type, b2.memoizedProps, c2, a3, b2, !Vd);
              b2.updateQueue = a3;
              null !== a3 && Jf(b2);
            } else {
              var f2 = Ka(e2, d2, c2, a3, b2);
              Lf(f2, b2, false, false);
              b2.stateNode = f2;
              Ma(f2, e2, d2, c2, a3) && Jf(b2);
            }
            null !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
          }
          P2(b2);
          return null;
        case 6:
          if (a3 && null != b2.stateNode) Of(a3, b2, a3.memoizedProps, d2);
          else {
            if ("string" !== typeof d2 && null === b2.stateNode) throw Error(n2(166));
            a3 = ue3(te2.current);
            c2 = ue3(re2.current);
            if (ce2(b2)) {
              if (!p2) throw Error(n2(176));
              a3 = b2.stateNode;
              d2 = b2.memoizedProps;
              if (c2 = Qb(a3, d2, b2, !Vd)) {
                if (e2 = Td, null !== e2) switch (f2 = 0 !== (e2.mode & 1), e2.tag) {
                  case 3:
                    Yb(e2.stateNode.containerInfo, a3, d2, f2);
                    break;
                  case 5:
                    Zb(e2.type, e2.memoizedProps, e2.stateNode, a3, d2, f2);
                }
              }
              c2 && Jf(b2);
            } else b2.stateNode = Pa(d2, a3, c2, b2);
          }
          P2(b2);
          return null;
        case 13:
          x(J2);
          d2 = b2.memoizedState;
          if (I2 && null !== Ud && 0 !== (b2.mode & 1) && 0 === (b2.flags & 128)) {
            for (a3 = Ud; a3; ) a3 = Lb(a3);
            de2();
            b2.flags |= 98560;
            return b2;
          }
          if (null !== d2 && null !== d2.dehydrated) {
            d2 = ce2(b2);
            if (null === a3) {
              if (!d2) throw Error(n2(318));
              if (!p2) throw Error(n2(344));
              a3 = b2.memoizedState;
              a3 = null !== a3 ? a3.dehydrated : null;
              if (!a3) throw Error(n2(317));
              Rb(a3, b2);
            } else de2(), 0 === (b2.flags & 128) && (b2.memoizedState = null), b2.flags |= 4;
            P2(b2);
            return null;
          }
          null !== Wd && (Sf(Wd), Wd = null);
          if (0 !== (b2.flags & 128)) return b2.lanes = c2, b2;
          d2 = null !== d2;
          c2 = false;
          null === a3 ? ce2(b2) : c2 = null !== a3.memoizedState;
          d2 && !c2 && (b2.child.flags |= 8192, 0 !== (b2.mode & 1) && (null === a3 || 0 !== (J2.current & 1) ? 0 === Q2 && (Q2 = 3) : Tf()));
          null !== b2.updateQueue && (b2.flags |= 4);
          P2(b2);
          return null;
        case 4:
          return we2(), Mf(a3, b2), null === a3 && Xa(b2.stateNode.containerInfo), P2(b2), null;
        case 10:
          return hd(b2.type._context), P2(b2), null;
        case 17:
          return C2(b2.type) && kc(), P2(b2), null;
        case 19:
          x(J2);
          e2 = b2.memoizedState;
          if (null === e2) return P2(b2), null;
          d2 = 0 !== (b2.flags & 128);
          f2 = e2.rendering;
          if (null === f2) if (d2) Qf(e2, false);
          else {
            if (0 !== Q2 || null !== a3 && 0 !== (a3.flags & 128)) for (a3 = b2.child; null !== a3; ) {
              f2 = ze2(a3);
              if (null !== f2) {
                b2.flags |= 128;
                Qf(e2, false);
                a3 = f2.updateQueue;
                null !== a3 && (b2.updateQueue = a3, b2.flags |= 4);
                b2.subtreeFlags = 0;
                a3 = c2;
                for (d2 = b2.child; null !== d2; ) c2 = d2, e2 = a3, c2.flags &= 14680066, f2 = c2.alternate, null === f2 ? (c2.childLanes = 0, c2.lanes = e2, c2.child = null, c2.subtreeFlags = 0, c2.memoizedProps = null, c2.memoizedState = null, c2.updateQueue = null, c2.dependencies = null, c2.stateNode = null) : (c2.childLanes = f2.childLanes, c2.lanes = f2.lanes, c2.child = f2.child, c2.subtreeFlags = 0, c2.deletions = null, c2.memoizedProps = f2.memoizedProps, c2.memoizedState = f2.memoizedState, c2.updateQueue = f2.updateQueue, c2.type = f2.type, e2 = f2.dependencies, c2.dependencies = null === e2 ? null : { lanes: e2.lanes, firstContext: e2.firstContext }), d2 = d2.sibling;
                y2(J2, J2.current & 1 | 2);
                return b2.child;
              }
              a3 = a3.sibling;
            }
            null !== e2.tail && E2() > Uf && (b2.flags |= 128, d2 = true, Qf(e2, false), b2.lanes = 4194304);
          }
          else {
            if (!d2) if (a3 = ze2(f2), null !== a3) {
              if (b2.flags |= 128, d2 = true, a3 = a3.updateQueue, null !== a3 && (b2.updateQueue = a3, b2.flags |= 4), Qf(e2, true), null === e2.tail && "hidden" === e2.tailMode && !f2.alternate && !I2) return P2(b2), null;
            } else 2 * E2() - e2.renderingStartTime > Uf && 1073741824 !== c2 && (b2.flags |= 128, d2 = true, Qf(e2, false), b2.lanes = 4194304);
            e2.isBackwards ? (f2.sibling = b2.child, b2.child = f2) : (a3 = e2.last, null !== a3 ? a3.sibling = f2 : b2.child = f2, e2.last = f2);
          }
          if (null !== e2.tail) return b2 = e2.tail, e2.rendering = b2, e2.tail = b2.sibling, e2.renderingStartTime = E2(), b2.sibling = null, a3 = J2.current, y2(J2, d2 ? a3 & 1 | 2 : a3 & 1), b2;
          P2(b2);
          return null;
        case 22:
        case 23:
          return Vf(), d2 = null !== b2.memoizedState, null !== a3 && null !== a3.memoizedState !== d2 && (b2.flags |= 8192), d2 && 0 !== (b2.mode & 1) ? 0 !== (Wf & 1073741824) && (P2(b2), Ua && b2.subtreeFlags & 6 && (b2.flags |= 8192)) : P2(b2), null;
        case 24:
          return null;
        case 25:
          return null;
      }
      throw Error(n2(156, b2.tag));
    }
    var Xf = ea2.ReactCurrentOwner, kd = false;
    function R2(a3, b2, c2, d2) {
      b2.child = null === a3 ? pe(b2, null, c2, d2) : oe2(b2, a3.child, c2, d2);
    }
    function Yf(a3, b2, c2, d2, e2) {
      c2 = c2.render;
      var f2 = b2.ref;
      jd(b2, e2);
      d2 = Ke2(a3, b2, c2, d2, f2, e2);
      c2 = Pe2();
      if (null !== a3 && !kd) return b2.updateQueue = a3.updateQueue, b2.flags &= -2053, a3.lanes &= ~e2, Zf(a3, b2, e2);
      I2 && c2 && Rd(b2);
      b2.flags |= 1;
      R2(a3, b2, d2, e2);
      return b2.child;
    }
    function $f(a3, b2, c2, d2, e2) {
      if (null === a3) {
        var f2 = c2.type;
        if ("function" === typeof f2 && !ag(f2) && void 0 === f2.defaultProps && null === c2.compare && void 0 === c2.defaultProps) return b2.tag = 15, b2.type = f2, bg(a3, b2, f2, d2, e2);
        a3 = le2(c2.type, null, d2, b2, b2.mode, e2);
        a3.ref = b2.ref;
        a3.return = b2;
        return b2.child = a3;
      }
      f2 = a3.child;
      if (0 === (a3.lanes & e2)) {
        var g2 = f2.memoizedProps;
        c2 = c2.compare;
        c2 = null !== c2 ? c2 : Zc;
        if (c2(g2, d2) && a3.ref === b2.ref) return Zf(a3, b2, e2);
      }
      b2.flags |= 1;
      a3 = je2(f2, d2);
      a3.ref = b2.ref;
      a3.return = b2;
      return b2.child = a3;
    }
    function bg(a3, b2, c2, d2, e2) {
      if (null !== a3 && Zc(a3.memoizedProps, d2) && a3.ref === b2.ref) if (kd = false, 0 !== (a3.lanes & e2)) 0 !== (a3.flags & 131072) && (kd = true);
      else return b2.lanes = a3.lanes, Zf(a3, b2, e2);
      return cg(a3, b2, c2, d2, e2);
    }
    function dg(a3, b2, c2) {
      var d2 = b2.pendingProps, e2 = d2.children, f2 = null !== a3 ? a3.memoizedState : null;
      if ("hidden" === d2.mode) if (0 === (b2.mode & 1)) b2.memoizedState = { baseLanes: 0, cachePool: null }, y2(eg, Wf), Wf |= c2;
      else if (0 !== (c2 & 1073741824)) b2.memoizedState = { baseLanes: 0, cachePool: null }, d2 = null !== f2 ? f2.baseLanes : c2, y2(eg, Wf), Wf |= d2;
      else return a3 = null !== f2 ? f2.baseLanes | c2 : c2, b2.lanes = b2.childLanes = 1073741824, b2.memoizedState = { baseLanes: a3, cachePool: null }, b2.updateQueue = null, y2(eg, Wf), Wf |= a3, null;
      else null !== f2 ? (d2 = f2.baseLanes | c2, b2.memoizedState = null) : d2 = c2, y2(eg, Wf), Wf |= d2;
      R2(a3, b2, e2, c2);
      return b2.child;
    }
    function fg(a3, b2) {
      var c2 = b2.ref;
      if (null === a3 && null !== c2 || null !== a3 && a3.ref !== c2) b2.flags |= 512, b2.flags |= 2097152;
    }
    function cg(a3, b2, c2, d2, e2) {
      var f2 = C2(c2) ? ic : A2.current;
      f2 = jc(b2, f2);
      jd(b2, e2);
      c2 = Ke2(a3, b2, c2, d2, f2, e2);
      d2 = Pe2();
      if (null !== a3 && !kd) return b2.updateQueue = a3.updateQueue, b2.flags &= -2053, a3.lanes &= ~e2, Zf(a3, b2, e2);
      I2 && d2 && Rd(b2);
      b2.flags |= 1;
      R2(a3, b2, c2, e2);
      return b2.child;
    }
    function gg(a3, b2, c2, d2, e2) {
      if (C2(c2)) {
        var f2 = true;
        nc(b2);
      } else f2 = false;
      jd(b2, e2);
      if (null === b2.stateNode) null !== a3 && (a3.alternate = null, b2.alternate = null, b2.flags |= 2), Dd(b2, c2, d2), Fd(b2, c2, d2, e2), d2 = true;
      else if (null === a3) {
        var g2 = b2.stateNode, h2 = b2.memoizedProps;
        g2.props = h2;
        var k2 = g2.context, l2 = c2.contextType;
        "object" === typeof l2 && null !== l2 ? l2 = ld(l2) : (l2 = C2(c2) ? ic : A2.current, l2 = jc(b2, l2));
        var m2 = c2.getDerivedStateFromProps, v5 = "function" === typeof m2 || "function" === typeof g2.getSnapshotBeforeUpdate;
        v5 || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== d2 || k2 !== l2) && Ed(b2, g2, d2, l2);
        nd = false;
        var r2 = b2.memoizedState;
        g2.state = r2;
        ud(b2, d2, g2, e2);
        k2 = b2.memoizedState;
        h2 !== d2 || r2 !== k2 || B.current || nd ? ("function" === typeof m2 && (yd(b2, c2, m2, d2), k2 = b2.memoizedState), (h2 = nd || Cd(b2, c2, h2, d2, r2, k2, l2)) ? (v5 || "function" !== typeof g2.UNSAFE_componentWillMount && "function" !== typeof g2.componentWillMount || ("function" === typeof g2.componentWillMount && g2.componentWillMount(), "function" === typeof g2.UNSAFE_componentWillMount && g2.UNSAFE_componentWillMount()), "function" === typeof g2.componentDidMount && (b2.flags |= 4194308)) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), b2.memoizedProps = d2, b2.memoizedState = k2), g2.props = d2, g2.state = k2, g2.context = l2, d2 = h2) : ("function" === typeof g2.componentDidMount && (b2.flags |= 4194308), d2 = false);
      } else {
        g2 = b2.stateNode;
        pd(a3, b2);
        h2 = b2.memoizedProps;
        l2 = b2.type === b2.elementType ? h2 : ad(b2.type, h2);
        g2.props = l2;
        v5 = b2.pendingProps;
        r2 = g2.context;
        k2 = c2.contextType;
        "object" === typeof k2 && null !== k2 ? k2 = ld(k2) : (k2 = C2(c2) ? ic : A2.current, k2 = jc(b2, k2));
        var z2 = c2.getDerivedStateFromProps;
        (m2 = "function" === typeof z2 || "function" === typeof g2.getSnapshotBeforeUpdate) || "function" !== typeof g2.UNSAFE_componentWillReceiveProps && "function" !== typeof g2.componentWillReceiveProps || (h2 !== v5 || r2 !== k2) && Ed(b2, g2, d2, k2);
        nd = false;
        r2 = b2.memoizedState;
        g2.state = r2;
        ud(b2, d2, g2, e2);
        var q3 = b2.memoizedState;
        h2 !== v5 || r2 !== q3 || B.current || nd ? ("function" === typeof z2 && (yd(b2, c2, z2, d2), q3 = b2.memoizedState), (l2 = nd || Cd(b2, c2, l2, d2, r2, q3, k2) || false) ? (m2 || "function" !== typeof g2.UNSAFE_componentWillUpdate && "function" !== typeof g2.componentWillUpdate || ("function" === typeof g2.componentWillUpdate && g2.componentWillUpdate(
          d2,
          q3,
          k2
        ), "function" === typeof g2.UNSAFE_componentWillUpdate && g2.UNSAFE_componentWillUpdate(d2, q3, k2)), "function" === typeof g2.componentDidUpdate && (b2.flags |= 4), "function" === typeof g2.getSnapshotBeforeUpdate && (b2.flags |= 1024)) : ("function" !== typeof g2.componentDidUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 1024), b2.memoizedProps = d2, b2.memoizedState = q3), g2.props = d2, g2.state = q3, g2.context = k2, d2 = l2) : ("function" !== typeof g2.componentDidUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 4), "function" !== typeof g2.getSnapshotBeforeUpdate || h2 === a3.memoizedProps && r2 === a3.memoizedState || (b2.flags |= 1024), d2 = false);
      }
      return hg(a3, b2, c2, d2, f2, e2);
    }
    function hg(a3, b2, c2, d2, e2, f2) {
      fg(a3, b2);
      var g2 = 0 !== (b2.flags & 128);
      if (!d2 && !g2) return e2 && oc(b2, c2, false), Zf(a3, b2, f2);
      d2 = b2.stateNode;
      Xf.current = b2;
      var h2 = g2 && "function" !== typeof c2.getDerivedStateFromError ? null : d2.render();
      b2.flags |= 1;
      null !== a3 && g2 ? (b2.child = oe2(b2, a3.child, null, f2), b2.child = oe2(b2, null, h2, f2)) : R2(a3, b2, h2, f2);
      b2.memoizedState = d2.state;
      e2 && oc(b2, c2, true);
      return b2.child;
    }
    function ig(a3) {
      var b2 = a3.stateNode;
      b2.pendingContext ? lc(a3, b2.pendingContext, b2.pendingContext !== b2.context) : b2.context && lc(a3, b2.context, false);
      ve2(a3, b2.containerInfo);
    }
    function jg(a3, b2, c2, d2, e2) {
      de2();
      ee2(e2);
      b2.flags |= 256;
      R2(a3, b2, c2, d2);
      return b2.child;
    }
    var kg = { dehydrated: null, treeContext: null, retryLane: 0 };
    function lg(a3) {
      return { baseLanes: a3, cachePool: null };
    }
    function mg(a3, b2, c2) {
      var d2 = b2.pendingProps, e2 = J2.current, f2 = false, g2 = 0 !== (b2.flags & 128), h2;
      (h2 = g2) || (h2 = null !== a3 && null === a3.memoizedState ? false : 0 !== (e2 & 2));
      if (h2) f2 = true, b2.flags &= -129;
      else if (null === a3 || null !== a3.memoizedState) e2 |= 1;
      y2(J2, e2 & 1);
      if (null === a3) {
        ae(b2);
        a3 = b2.memoizedState;
        if (null !== a3 && (a3 = a3.dehydrated, null !== a3)) return 0 === (b2.mode & 1) ? b2.lanes = 1 : Jb(a3) ? b2.lanes = 8 : b2.lanes = 1073741824, null;
        e2 = d2.children;
        a3 = d2.fallback;
        return f2 ? (d2 = b2.mode, f2 = b2.child, e2 = { mode: "hidden", children: e2 }, 0 === (d2 & 1) && null !== f2 ? (f2.childLanes = 0, f2.pendingProps = e2) : f2 = ng(e2, d2, 0, null), a3 = ne2(a3, d2, c2, null), f2.return = b2, a3.return = b2, f2.sibling = a3, b2.child = f2, b2.child.memoizedState = lg(c2), b2.memoizedState = kg, a3) : og(b2, e2);
      }
      e2 = a3.memoizedState;
      if (null !== e2) {
        h2 = e2.dehydrated;
        if (null !== h2) {
          if (g2) {
            if (b2.flags & 256) return b2.flags &= -257, pg(a3, b2, c2, Error(n2(422)));
            if (null !== b2.memoizedState) return b2.child = a3.child, b2.flags |= 128, null;
            f2 = d2.fallback;
            e2 = b2.mode;
            d2 = ng({ mode: "visible", children: d2.children }, e2, 0, null);
            f2 = ne2(f2, e2, c2, null);
            f2.flags |= 2;
            d2.return = b2;
            f2.return = b2;
            d2.sibling = f2;
            b2.child = d2;
            0 !== (b2.mode & 1) && oe2(
              b2,
              a3.child,
              null,
              c2
            );
            b2.child.memoizedState = lg(c2);
            b2.memoizedState = kg;
            return f2;
          }
          if (0 === (b2.mode & 1)) b2 = pg(a3, b2, c2, null);
          else if (Jb(h2)) b2 = pg(a3, b2, c2, Error(n2(419)));
          else if (d2 = 0 !== (c2 & a3.childLanes), kd || d2) {
            d2 = F2;
            if (null !== d2) {
              switch (c2 & -c2) {
                case 4:
                  f2 = 2;
                  break;
                case 16:
                  f2 = 8;
                  break;
                case 64:
                case 128:
                case 256:
                case 512:
                case 1024:
                case 2048:
                case 4096:
                case 8192:
                case 16384:
                case 32768:
                case 65536:
                case 131072:
                case 262144:
                case 524288:
                case 1048576:
                case 2097152:
                case 4194304:
                case 8388608:
                case 16777216:
                case 33554432:
                case 67108864:
                  f2 = 32;
                  break;
                case 536870912:
                  f2 = 268435456;
                  break;
                default:
                  f2 = 0;
              }
              d2 = 0 !== (f2 & (d2.suspendedLanes | c2)) ? 0 : f2;
              0 !== d2 && d2 !== e2.retryLane && (e2.retryLane = d2, Ad(a3, d2, -1));
            }
            Tf();
            b2 = pg(a3, b2, c2, Error(n2(421)));
          } else Ib(h2) ? (b2.flags |= 128, b2.child = a3.child, b2 = qg.bind(null, a3), Kb(h2, b2), b2 = null) : (c2 = e2.treeContext, p2 && (Ud = Ob(h2), Td = b2, I2 = true, Wd = null, Vd = false, null !== c2 && (Kd[Ld++] = Nd, Kd[Ld++] = Od, Kd[Ld++] = Md, Nd = c2.id, Od = c2.overflow, Md = b2)), b2 = og(b2, b2.pendingProps.children), b2.flags |= 4096);
          return b2;
        }
        if (f2) return d2 = rg(a3, b2, d2.children, d2.fallback, c2), f2 = b2.child, e2 = a3.child.memoizedState, f2.memoizedState = null === e2 ? lg(c2) : { baseLanes: e2.baseLanes | c2, cachePool: null }, f2.childLanes = a3.childLanes & ~c2, b2.memoizedState = kg, d2;
        c2 = sg(a3, b2, d2.children, c2);
        b2.memoizedState = null;
        return c2;
      }
      if (f2) return d2 = rg(a3, b2, d2.children, d2.fallback, c2), f2 = b2.child, e2 = a3.child.memoizedState, f2.memoizedState = null === e2 ? lg(c2) : { baseLanes: e2.baseLanes | c2, cachePool: null }, f2.childLanes = a3.childLanes & ~c2, b2.memoizedState = kg, d2;
      c2 = sg(a3, b2, d2.children, c2);
      b2.memoizedState = null;
      return c2;
    }
    function og(a3, b2) {
      b2 = ng({ mode: "visible", children: b2 }, a3.mode, 0, null);
      b2.return = a3;
      return a3.child = b2;
    }
    function sg(a3, b2, c2, d2) {
      var e2 = a3.child;
      a3 = e2.sibling;
      c2 = je2(e2, { mode: "visible", children: c2 });
      0 === (b2.mode & 1) && (c2.lanes = d2);
      c2.return = b2;
      c2.sibling = null;
      null !== a3 && (d2 = b2.deletions, null === d2 ? (b2.deletions = [a3], b2.flags |= 16) : d2.push(a3));
      return b2.child = c2;
    }
    function rg(a3, b2, c2, d2, e2) {
      var f2 = b2.mode;
      a3 = a3.child;
      var g2 = a3.sibling, h2 = { mode: "hidden", children: c2 };
      0 === (f2 & 1) && b2.child !== a3 ? (c2 = b2.child, c2.childLanes = 0, c2.pendingProps = h2, b2.deletions = null) : (c2 = je2(a3, h2), c2.subtreeFlags = a3.subtreeFlags & 14680064);
      null !== g2 ? d2 = je2(g2, d2) : (d2 = ne2(d2, f2, e2, null), d2.flags |= 2);
      d2.return = b2;
      c2.return = b2;
      c2.sibling = d2;
      b2.child = c2;
      return d2;
    }
    function pg(a3, b2, c2, d2) {
      null !== d2 && ee2(d2);
      oe2(b2, a3.child, null, c2);
      a3 = og(b2, b2.pendingProps.children);
      a3.flags |= 2;
      b2.memoizedState = null;
      return a3;
    }
    function tg(a3, b2, c2) {
      a3.lanes |= b2;
      var d2 = a3.alternate;
      null !== d2 && (d2.lanes |= b2);
      id(a3.return, b2, c2);
    }
    function ug(a3, b2, c2, d2, e2) {
      var f2 = a3.memoizedState;
      null === f2 ? a3.memoizedState = { isBackwards: b2, rendering: null, renderingStartTime: 0, last: d2, tail: c2, tailMode: e2 } : (f2.isBackwards = b2, f2.rendering = null, f2.renderingStartTime = 0, f2.last = d2, f2.tail = c2, f2.tailMode = e2);
    }
    function vg(a3, b2, c2) {
      var d2 = b2.pendingProps, e2 = d2.revealOrder, f2 = d2.tail;
      R2(a3, b2, d2.children, c2);
      d2 = J2.current;
      if (0 !== (d2 & 2)) d2 = d2 & 1 | 2, b2.flags |= 128;
      else {
        if (null !== a3 && 0 !== (a3.flags & 128)) a: for (a3 = b2.child; null !== a3; ) {
          if (13 === a3.tag) null !== a3.memoizedState && tg(a3, c2, b2);
          else if (19 === a3.tag) tg(a3, c2, b2);
          else if (null !== a3.child) {
            a3.child.return = a3;
            a3 = a3.child;
            continue;
          }
          if (a3 === b2) break a;
          for (; null === a3.sibling; ) {
            if (null === a3.return || a3.return === b2) break a;
            a3 = a3.return;
          }
          a3.sibling.return = a3.return;
          a3 = a3.sibling;
        }
        d2 &= 1;
      }
      y2(J2, d2);
      if (0 === (b2.mode & 1)) b2.memoizedState = null;
      else switch (e2) {
        case "forwards":
          c2 = b2.child;
          for (e2 = null; null !== c2; ) a3 = c2.alternate, null !== a3 && null === ze2(a3) && (e2 = c2), c2 = c2.sibling;
          c2 = e2;
          null === c2 ? (e2 = b2.child, b2.child = null) : (e2 = c2.sibling, c2.sibling = null);
          ug(b2, false, e2, c2, f2);
          break;
        case "backwards":
          c2 = null;
          e2 = b2.child;
          for (b2.child = null; null !== e2; ) {
            a3 = e2.alternate;
            if (null !== a3 && null === ze2(a3)) {
              b2.child = e2;
              break;
            }
            a3 = e2.sibling;
            e2.sibling = c2;
            c2 = e2;
            e2 = a3;
          }
          ug(b2, true, c2, null, f2);
          break;
        case "together":
          ug(b2, false, null, null, void 0);
          break;
        default:
          b2.memoizedState = null;
      }
      return b2.child;
    }
    function Zf(a3, b2, c2) {
      null !== a3 && (b2.dependencies = a3.dependencies);
      vd |= b2.lanes;
      if (0 === (c2 & b2.childLanes)) return null;
      if (null !== a3 && b2.child !== a3.child) throw Error(n2(153));
      if (null !== b2.child) {
        a3 = b2.child;
        c2 = je2(a3, a3.pendingProps);
        b2.child = c2;
        for (c2.return = b2; null !== a3.sibling; ) a3 = a3.sibling, c2 = c2.sibling = je2(a3, a3.pendingProps), c2.return = b2;
        c2.sibling = null;
      }
      return b2.child;
    }
    function wg(a3, b2, c2) {
      switch (b2.tag) {
        case 3:
          ig(b2);
          de2();
          break;
        case 5:
          xe2(b2);
          break;
        case 1:
          C2(b2.type) && nc(b2);
          break;
        case 4:
          ve2(b2, b2.stateNode.containerInfo);
          break;
        case 10:
          gd(b2, b2.type._context, b2.memoizedProps.value);
          break;
        case 13:
          var d2 = b2.memoizedState;
          if (null !== d2) {
            if (null !== d2.dehydrated) return y2(J2, J2.current & 1), b2.flags |= 128, null;
            if (0 !== (c2 & b2.child.childLanes)) return mg(a3, b2, c2);
            y2(J2, J2.current & 1);
            a3 = Zf(a3, b2, c2);
            return null !== a3 ? a3.sibling : null;
          }
          y2(J2, J2.current & 1);
          break;
        case 19:
          d2 = 0 !== (c2 & b2.childLanes);
          if (0 !== (a3.flags & 128)) {
            if (d2) return vg(
              a3,
              b2,
              c2
            );
            b2.flags |= 128;
          }
          var e2 = b2.memoizedState;
          null !== e2 && (e2.rendering = null, e2.tail = null, e2.lastEffect = null);
          y2(J2, J2.current);
          if (d2) break;
          else return null;
        case 22:
        case 23:
          return b2.lanes = 0, dg(a3, b2, c2);
      }
      return Zf(a3, b2, c2);
    }
    function xg(a3, b2) {
      Sd(b2);
      switch (b2.tag) {
        case 1:
          return C2(b2.type) && kc(), a3 = b2.flags, a3 & 65536 ? (b2.flags = a3 & -65537 | 128, b2) : null;
        case 3:
          return we2(), x(B), x(A2), Be2(), a3 = b2.flags, 0 !== (a3 & 65536) && 0 === (a3 & 128) ? (b2.flags = a3 & -65537 | 128, b2) : null;
        case 5:
          return ye2(b2), null;
        case 13:
          x(J2);
          a3 = b2.memoizedState;
          if (null !== a3 && null !== a3.dehydrated) {
            if (null === b2.alternate) throw Error(n2(340));
            de2();
          }
          a3 = b2.flags;
          return a3 & 65536 ? (b2.flags = a3 & -65537 | 128, b2) : null;
        case 19:
          return x(J2), null;
        case 4:
          return we2(), null;
        case 10:
          return hd(b2.type._context), null;
        case 22:
        case 23:
          return Vf(), null;
        case 24:
          return null;
        default:
          return null;
      }
    }
    var yg = false, zg = false, Ag = "function" === typeof WeakSet ? WeakSet : Set, S2 = null;
    function Bg(a3, b2) {
      var c2 = a3.ref;
      if (null !== c2) if ("function" === typeof c2) try {
        c2(null);
      } catch (d2) {
        T3(a3, b2, d2);
      }
      else c2.current = null;
    }
    function Cg(a3, b2, c2) {
      try {
        c2();
      } catch (d2) {
        T3(a3, b2, d2);
      }
    }
    var Dg = false;
    function Eg(a3, b2) {
      Ia(a3.containerInfo);
      for (S2 = b2; null !== S2; ) if (a3 = S2, b2 = a3.child, 0 !== (a3.subtreeFlags & 1028) && null !== b2) b2.return = a3, S2 = b2;
      else for (; null !== S2; ) {
        a3 = S2;
        try {
          var c2 = a3.alternate;
          if (0 !== (a3.flags & 1024)) switch (a3.tag) {
            case 0:
            case 11:
            case 15:
              break;
            case 1:
              if (null !== c2) {
                var d2 = c2.memoizedProps, e2 = c2.memoizedState, f2 = a3.stateNode, g2 = f2.getSnapshotBeforeUpdate(a3.elementType === a3.type ? d2 : ad(a3.type, d2), e2);
                f2.__reactInternalSnapshotBeforeUpdate = g2;
              }
              break;
            case 3:
              Ua && xb(a3.stateNode.containerInfo);
              break;
            case 5:
            case 6:
            case 4:
            case 17:
              break;
            default:
              throw Error(n2(163));
          }
        } catch (h2) {
          T3(a3, a3.return, h2);
        }
        b2 = a3.sibling;
        if (null !== b2) {
          b2.return = a3.return;
          S2 = b2;
          break;
        }
        S2 = a3.return;
      }
      c2 = Dg;
      Dg = false;
      return c2;
    }
    function Fg(a3, b2, c2) {
      var d2 = b2.updateQueue;
      d2 = null !== d2 ? d2.lastEffect : null;
      if (null !== d2) {
        var e2 = d2 = d2.next;
        do {
          if ((e2.tag & a3) === a3) {
            var f2 = e2.destroy;
            e2.destroy = void 0;
            void 0 !== f2 && Cg(b2, c2, f2);
          }
          e2 = e2.next;
        } while (e2 !== d2);
      }
    }
    function Gg(a3, b2) {
      b2 = b2.updateQueue;
      b2 = null !== b2 ? b2.lastEffect : null;
      if (null !== b2) {
        var c2 = b2 = b2.next;
        do {
          if ((c2.tag & a3) === a3) {
            var d2 = c2.create;
            c2.destroy = d2();
          }
          c2 = c2.next;
        } while (c2 !== b2);
      }
    }
    function Hg(a3) {
      var b2 = a3.ref;
      if (null !== b2) {
        var c2 = a3.stateNode;
        switch (a3.tag) {
          case 5:
            a3 = Fa(c2);
            break;
          default:
            a3 = c2;
        }
        "function" === typeof b2 ? b2(a3) : b2.current = a3;
      }
    }
    function Ig(a3, b2, c2) {
      if (Oc && "function" === typeof Oc.onCommitFiberUnmount) try {
        Oc.onCommitFiberUnmount(Nc, b2);
      } catch (g2) {
      }
      switch (b2.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          a3 = b2.updateQueue;
          if (null !== a3 && (a3 = a3.lastEffect, null !== a3)) {
            var d2 = a3 = a3.next;
            do {
              var e2 = d2, f2 = e2.destroy;
              e2 = e2.tag;
              void 0 !== f2 && (0 !== (e2 & 2) ? Cg(b2, c2, f2) : 0 !== (e2 & 4) && Cg(b2, c2, f2));
              d2 = d2.next;
            } while (d2 !== a3);
          }
          break;
        case 1:
          Bg(b2, c2);
          a3 = b2.stateNode;
          if ("function" === typeof a3.componentWillUnmount) try {
            a3.props = b2.memoizedProps, a3.state = b2.memoizedState, a3.componentWillUnmount();
          } catch (g2) {
            T3(
              b2,
              c2,
              g2
            );
          }
          break;
        case 5:
          Bg(b2, c2);
          break;
        case 4:
          Ua ? Jg(a3, b2, c2) : Va && Va && (b2 = b2.stateNode.containerInfo, c2 = zb(b2), Cb(b2, c2));
      }
    }
    function Kg(a3, b2, c2) {
      for (var d2 = b2; ; ) if (Ig(a3, d2, c2), null === d2.child || Ua && 4 === d2.tag) {
        if (d2 === b2) break;
        for (; null === d2.sibling; ) {
          if (null === d2.return || d2.return === b2) return;
          d2 = d2.return;
        }
        d2.sibling.return = d2.return;
        d2 = d2.sibling;
      } else d2.child.return = d2, d2 = d2.child;
    }
    function Lg(a3) {
      var b2 = a3.alternate;
      null !== b2 && (a3.alternate = null, Lg(b2));
      a3.child = null;
      a3.deletions = null;
      a3.sibling = null;
      5 === a3.tag && (b2 = a3.stateNode, null !== b2 && Za(b2));
      a3.stateNode = null;
      a3.return = null;
      a3.dependencies = null;
      a3.memoizedProps = null;
      a3.memoizedState = null;
      a3.pendingProps = null;
      a3.stateNode = null;
      a3.updateQueue = null;
    }
    function Mg(a3) {
      return 5 === a3.tag || 3 === a3.tag || 4 === a3.tag;
    }
    function Ng(a3) {
      a: for (; ; ) {
        for (; null === a3.sibling; ) {
          if (null === a3.return || Mg(a3.return)) return null;
          a3 = a3.return;
        }
        a3.sibling.return = a3.return;
        for (a3 = a3.sibling; 5 !== a3.tag && 6 !== a3.tag && 18 !== a3.tag; ) {
          if (a3.flags & 2) continue a;
          if (null === a3.child || 4 === a3.tag) continue a;
          else a3.child.return = a3, a3 = a3.child;
        }
        if (!(a3.flags & 2)) return a3.stateNode;
      }
    }
    function Og(a3) {
      if (Ua) {
        a: {
          for (var b2 = a3.return; null !== b2; ) {
            if (Mg(b2)) break a;
            b2 = b2.return;
          }
          throw Error(n2(160));
        }
        var c2 = b2;
        switch (c2.tag) {
          case 5:
            b2 = c2.stateNode;
            c2.flags & 32 && (sb(b2), c2.flags &= -33);
            c2 = Ng(a3);
            Pg(a3, c2, b2);
            break;
          case 3:
          case 4:
            b2 = c2.stateNode.containerInfo;
            c2 = Ng(a3);
            Qg(a3, c2, b2);
            break;
          default:
            throw Error(n2(161));
        }
      }
    }
    function Qg(a3, b2, c2) {
      var d2 = a3.tag;
      if (5 === d2 || 6 === d2) a3 = a3.stateNode, b2 ? pb(c2, a3, b2) : kb(c2, a3);
      else if (4 !== d2 && (a3 = a3.child, null !== a3)) for (Qg(a3, b2, c2), a3 = a3.sibling; null !== a3; ) Qg(a3, b2, c2), a3 = a3.sibling;
    }
    function Pg(a3, b2, c2) {
      var d2 = a3.tag;
      if (5 === d2 || 6 === d2) a3 = a3.stateNode, b2 ? ob(c2, a3, b2) : jb(c2, a3);
      else if (4 !== d2 && (a3 = a3.child, null !== a3)) for (Pg(a3, b2, c2), a3 = a3.sibling; null !== a3; ) Pg(a3, b2, c2), a3 = a3.sibling;
    }
    function Jg(a3, b2, c2) {
      for (var d2 = b2, e2 = false, f2, g2; ; ) {
        if (!e2) {
          e2 = d2.return;
          a: for (; ; ) {
            if (null === e2) throw Error(n2(160));
            f2 = e2.stateNode;
            switch (e2.tag) {
              case 5:
                g2 = false;
                break a;
              case 3:
                f2 = f2.containerInfo;
                g2 = true;
                break a;
              case 4:
                f2 = f2.containerInfo;
                g2 = true;
                break a;
            }
            e2 = e2.return;
          }
          e2 = true;
        }
        if (5 === d2.tag || 6 === d2.tag) Kg(a3, d2, c2), g2 ? rb(f2, d2.stateNode) : qb(f2, d2.stateNode);
        else if (18 === d2.tag) g2 ? Wb(f2, d2.stateNode) : Vb(f2, d2.stateNode);
        else if (4 === d2.tag) {
          if (null !== d2.child) {
            f2 = d2.stateNode.containerInfo;
            g2 = true;
            d2.child.return = d2;
            d2 = d2.child;
            continue;
          }
        } else if (Ig(a3, d2, c2), null !== d2.child) {
          d2.child.return = d2;
          d2 = d2.child;
          continue;
        }
        if (d2 === b2) break;
        for (; null === d2.sibling; ) {
          if (null === d2.return || d2.return === b2) return;
          d2 = d2.return;
          4 === d2.tag && (e2 = false);
        }
        d2.sibling.return = d2.return;
        d2 = d2.sibling;
      }
    }
    function Rg(a3, b2) {
      if (Ua) {
        switch (b2.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            Fg(3, b2, b2.return);
            Gg(3, b2);
            Fg(5, b2, b2.return);
            return;
          case 1:
            return;
          case 5:
            var c2 = b2.stateNode;
            if (null != c2) {
              var d2 = b2.memoizedProps;
              a3 = null !== a3 ? a3.memoizedProps : d2;
              var e2 = b2.type, f2 = b2.updateQueue;
              b2.updateQueue = null;
              null !== f2 && nb(c2, f2, e2, a3, d2, b2);
            }
            return;
          case 6:
            if (null === b2.stateNode) throw Error(n2(162));
            c2 = b2.memoizedProps;
            lb(b2.stateNode, null !== a3 ? a3.memoizedProps : c2, c2);
            return;
          case 3:
            p2 && null !== a3 && a3.memoizedState.isDehydrated && Tb(b2.stateNode.containerInfo);
            return;
          case 12:
            return;
          case 13:
            Sg(b2);
            return;
          case 19:
            Sg(b2);
            return;
          case 17:
            return;
        }
        throw Error(n2(163));
      }
      switch (b2.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          Fg(3, b2, b2.return);
          Gg(3, b2);
          Fg(5, b2, b2.return);
          return;
        case 12:
          return;
        case 13:
          Sg(b2);
          return;
        case 19:
          Sg(b2);
          return;
        case 3:
          p2 && null !== a3 && a3.memoizedState.isDehydrated && Tb(b2.stateNode.containerInfo);
          break;
        case 22:
        case 23:
          return;
      }
      a: if (Va) {
        switch (b2.tag) {
          case 1:
          case 5:
          case 6:
            break a;
          case 3:
          case 4:
            b2 = b2.stateNode;
            Cb(b2.containerInfo, b2.pendingChildren);
            break a;
        }
        throw Error(n2(163));
      }
    }
    function Sg(a3) {
      var b2 = a3.updateQueue;
      if (null !== b2) {
        a3.updateQueue = null;
        var c2 = a3.stateNode;
        null === c2 && (c2 = a3.stateNode = new Ag());
        b2.forEach(function(b3) {
          var d2 = Tg.bind(null, a3, b3);
          c2.has(b3) || (c2.add(b3), b3.then(d2, d2));
        });
      }
    }
    function Ug(a3, b2) {
      for (S2 = b2; null !== S2; ) {
        b2 = S2;
        var c2 = b2.deletions;
        if (null !== c2) for (var d2 = 0; d2 < c2.length; d2++) {
          var e2 = c2[d2];
          try {
            var f2 = a3;
            Ua ? Jg(f2, e2, b2) : Kg(f2, e2, b2);
            var g2 = e2.alternate;
            null !== g2 && (g2.return = null);
            e2.return = null;
          } catch (wa) {
            T3(e2, b2, wa);
          }
        }
        c2 = b2.child;
        if (0 !== (b2.subtreeFlags & 12854) && null !== c2) c2.return = b2, S2 = c2;
        else for (; null !== S2; ) {
          b2 = S2;
          try {
            var h2 = b2.flags;
            h2 & 32 && Ua && sb(b2.stateNode);
            if (h2 & 512) {
              var k2 = b2.alternate;
              if (null !== k2) {
                var l2 = k2.ref;
                null !== l2 && ("function" === typeof l2 ? l2(null) : l2.current = null);
              }
            }
            if (h2 & 8192) switch (b2.tag) {
              case 13:
                if (null !== b2.memoizedState) {
                  var m2 = b2.alternate;
                  if (null === m2 || null === m2.memoizedState) Vg = E2();
                }
                break;
              case 22:
                var v5 = null !== b2.memoizedState, r2 = b2.alternate, z2 = null !== r2 && null !== r2.memoizedState;
                c2 = b2;
                if (Ua) {
                  a: if (d2 = c2, e2 = v5, f2 = null, Ua) for (var q3 = d2; ; ) {
                    if (5 === q3.tag) {
                      if (null === f2) {
                        f2 = q3;
                        var N2 = q3.stateNode;
                        e2 ? tb(N2) : vb(q3.stateNode, q3.memoizedProps);
                      }
                    } else if (6 === q3.tag) {
                      if (null === f2) {
                        var da2 = q3.stateNode;
                        e2 ? ub(da2) : wb(da2, q3.memoizedProps);
                      }
                    } else if ((22 !== q3.tag && 23 !== q3.tag || null === q3.memoizedState || q3 === d2) && null !== q3.child) {
                      q3.child.return = q3;
                      q3 = q3.child;
                      continue;
                    }
                    if (q3 === d2) break;
                    for (; null === q3.sibling; ) {
                      if (null === q3.return || q3.return === d2) break a;
                      f2 === q3 && (f2 = null);
                      q3 = q3.return;
                    }
                    f2 === q3 && (f2 = null);
                    q3.sibling.return = q3.return;
                    q3 = q3.sibling;
                  }
                }
                if (v5 && !z2 && 0 !== (c2.mode & 1)) {
                  S2 = c2;
                  for (var t2 = c2.child; null !== t2; ) {
                    for (c2 = S2 = t2; null !== S2; ) {
                      d2 = S2;
                      var w2 = d2.child;
                      switch (d2.tag) {
                        case 0:
                        case 11:
                        case 14:
                        case 15:
                          Fg(4, d2, d2.return);
                          break;
                        case 1:
                          Bg(d2, d2.return);
                          var u2 = d2.stateNode;
                          if ("function" === typeof u2.componentWillUnmount) {
                            var V2 = d2.return;
                            try {
                              u2.props = d2.memoizedProps, u2.state = d2.memoizedState, u2.componentWillUnmount();
                            } catch (wa) {
                              T3(
                                d2,
                                V2,
                                wa
                              );
                            }
                          }
                          break;
                        case 5:
                          Bg(d2, d2.return);
                          break;
                        case 22:
                          if (null !== d2.memoizedState) {
                            Wg(c2);
                            continue;
                          }
                      }
                      null !== w2 ? (w2.return = d2, S2 = w2) : Wg(c2);
                    }
                    t2 = t2.sibling;
                  }
                }
            }
            switch (h2 & 4102) {
              case 2:
                Og(b2);
                b2.flags &= -3;
                break;
              case 6:
                Og(b2);
                b2.flags &= -3;
                Rg(b2.alternate, b2);
                break;
              case 4096:
                b2.flags &= -4097;
                break;
              case 4100:
                b2.flags &= -4097;
                Rg(b2.alternate, b2);
                break;
              case 4:
                Rg(b2.alternate, b2);
            }
          } catch (wa) {
            T3(b2, b2.return, wa);
          }
          c2 = b2.sibling;
          if (null !== c2) {
            c2.return = b2.return;
            S2 = c2;
            break;
          }
          S2 = b2.return;
        }
      }
    }
    function Xg(a3, b2, c2) {
      S2 = a3;
      Yg(a3);
    }
    function Yg(a3, b2, c2) {
      for (var d2 = 0 !== (a3.mode & 1); null !== S2; ) {
        var e2 = S2, f2 = e2.child;
        if (22 === e2.tag && d2) {
          var g2 = null !== e2.memoizedState || yg;
          if (!g2) {
            var h2 = e2.alternate, k2 = null !== h2 && null !== h2.memoizedState || zg;
            h2 = yg;
            var l2 = zg;
            yg = g2;
            if ((zg = k2) && !l2) for (S2 = e2; null !== S2; ) g2 = S2, k2 = g2.child, 22 === g2.tag && null !== g2.memoizedState ? Zg(e2) : null !== k2 ? (k2.return = g2, S2 = k2) : Zg(e2);
            for (; null !== f2; ) S2 = f2, Yg(f2), f2 = f2.sibling;
            S2 = e2;
            yg = h2;
            zg = l2;
          }
          $g(a3);
        } else 0 !== (e2.subtreeFlags & 8772) && null !== f2 ? (f2.return = e2, S2 = f2) : $g(a3);
      }
    }
    function $g(a3) {
      for (; null !== S2; ) {
        var b2 = S2;
        if (0 !== (b2.flags & 8772)) {
          var c2 = b2.alternate;
          try {
            if (0 !== (b2.flags & 8772)) switch (b2.tag) {
              case 0:
              case 11:
              case 15:
                zg || Gg(5, b2);
                break;
              case 1:
                var d2 = b2.stateNode;
                if (b2.flags & 4 && !zg) if (null === c2) d2.componentDidMount();
                else {
                  var e2 = b2.elementType === b2.type ? c2.memoizedProps : ad(b2.type, c2.memoizedProps);
                  d2.componentDidUpdate(e2, c2.memoizedState, d2.__reactInternalSnapshotBeforeUpdate);
                }
                var f2 = b2.updateQueue;
                null !== f2 && wd(b2, f2, d2);
                break;
              case 3:
                var g2 = b2.updateQueue;
                if (null !== g2) {
                  c2 = null;
                  if (null !== b2.child) switch (b2.child.tag) {
                    case 5:
                      c2 = Fa(b2.child.stateNode);
                      break;
                    case 1:
                      c2 = b2.child.stateNode;
                  }
                  wd(b2, g2, c2);
                }
                break;
              case 5:
                var h2 = b2.stateNode;
                null === c2 && b2.flags & 4 && mb(h2, b2.type, b2.memoizedProps, b2);
                break;
              case 6:
                break;
              case 4:
                break;
              case 12:
                break;
              case 13:
                if (p2 && null === b2.memoizedState) {
                  var k2 = b2.alternate;
                  if (null !== k2) {
                    var l2 = k2.memoizedState;
                    if (null !== l2) {
                      var m2 = l2.dehydrated;
                      null !== m2 && Ub(m2);
                    }
                  }
                }
                break;
              case 19:
              case 17:
              case 21:
              case 22:
              case 23:
                break;
              default:
                throw Error(n2(163));
            }
            zg || b2.flags & 512 && Hg(b2);
          } catch (v5) {
            T3(b2, b2.return, v5);
          }
        }
        if (b2 === a3) {
          S2 = null;
          break;
        }
        c2 = b2.sibling;
        if (null !== c2) {
          c2.return = b2.return;
          S2 = c2;
          break;
        }
        S2 = b2.return;
      }
    }
    function Wg(a3) {
      for (; null !== S2; ) {
        var b2 = S2;
        if (b2 === a3) {
          S2 = null;
          break;
        }
        var c2 = b2.sibling;
        if (null !== c2) {
          c2.return = b2.return;
          S2 = c2;
          break;
        }
        S2 = b2.return;
      }
    }
    function Zg(a3) {
      for (; null !== S2; ) {
        var b2 = S2;
        try {
          switch (b2.tag) {
            case 0:
            case 11:
            case 15:
              var c2 = b2.return;
              try {
                Gg(4, b2);
              } catch (k2) {
                T3(b2, c2, k2);
              }
              break;
            case 1:
              var d2 = b2.stateNode;
              if ("function" === typeof d2.componentDidMount) {
                var e2 = b2.return;
                try {
                  d2.componentDidMount();
                } catch (k2) {
                  T3(b2, e2, k2);
                }
              }
              var f2 = b2.return;
              try {
                Hg(b2);
              } catch (k2) {
                T3(b2, f2, k2);
              }
              break;
            case 5:
              var g2 = b2.return;
              try {
                Hg(b2);
              } catch (k2) {
                T3(b2, g2, k2);
              }
          }
        } catch (k2) {
          T3(b2, b2.return, k2);
        }
        if (b2 === a3) {
          S2 = null;
          break;
        }
        var h2 = b2.sibling;
        if (null !== h2) {
          h2.return = b2.return;
          S2 = h2;
          break;
        }
        S2 = b2.return;
      }
    }
    var ah = 0, bh = 1, ch = 2, dh = 3, eh = 4;
    if ("function" === typeof Symbol && Symbol.for) {
      var fh = Symbol.for;
      ah = fh("selector.component");
      bh = fh("selector.has_pseudo_class");
      ch = fh("selector.role");
      dh = fh("selector.test_id");
      eh = fh("selector.text");
    }
    function gh(a3) {
      var b2 = Wa(a3);
      if (null != b2) {
        if ("string" !== typeof b2.memoizedProps["data-testname"]) throw Error(n2(364));
        return b2;
      }
      a3 = cb(a3);
      if (null === a3) throw Error(n2(362));
      return a3.stateNode.current;
    }
    function hh(a3, b2) {
      switch (b2.$$typeof) {
        case ah:
          if (a3.type === b2.value) return true;
          break;
        case bh:
          a: {
            b2 = b2.value;
            a3 = [a3, 0];
            for (var c2 = 0; c2 < a3.length; ) {
              var d2 = a3[c2++], e2 = a3[c2++], f2 = b2[e2];
              if (5 !== d2.tag || !fb(d2)) {
                for (; null != f2 && hh(d2, f2); ) e2++, f2 = b2[e2];
                if (e2 === b2.length) {
                  b2 = true;
                  break a;
                } else for (d2 = d2.child; null !== d2; ) a3.push(d2, e2), d2 = d2.sibling;
              }
            }
            b2 = false;
          }
          return b2;
        case ch:
          if (5 === a3.tag && gb(a3.stateNode, b2.value)) return true;
          break;
        case eh:
          if (5 === a3.tag || 6 === a3.tag) {
            if (a3 = eb(a3), null !== a3 && 0 <= a3.indexOf(b2.value)) return true;
          }
          break;
        case dh:
          if (5 === a3.tag && (a3 = a3.memoizedProps["data-testname"], "string" === typeof a3 && a3.toLowerCase() === b2.value.toLowerCase())) return true;
          break;
        default:
          throw Error(n2(365));
      }
      return false;
    }
    function ih(a3) {
      switch (a3.$$typeof) {
        case ah:
          return "<" + (va(a3.value) || "Unknown") + ">";
        case bh:
          return ":has(" + (ih(a3) || "") + ")";
        case ch:
          return '[role="' + a3.value + '"]';
        case eh:
          return '"' + a3.value + '"';
        case dh:
          return '[data-testname="' + a3.value + '"]';
        default:
          throw Error(n2(365));
      }
    }
    function jh(a3, b2) {
      var c2 = [];
      a3 = [a3, 0];
      for (var d2 = 0; d2 < a3.length; ) {
        var e2 = a3[d2++], f2 = a3[d2++], g2 = b2[f2];
        if (5 !== e2.tag || !fb(e2)) {
          for (; null != g2 && hh(e2, g2); ) f2++, g2 = b2[f2];
          if (f2 === b2.length) c2.push(e2);
          else for (e2 = e2.child; null !== e2; ) a3.push(e2, f2), e2 = e2.sibling;
        }
      }
      return c2;
    }
    function kh(a3, b2) {
      if (!bb) throw Error(n2(363));
      a3 = gh(a3);
      a3 = jh(a3, b2);
      b2 = [];
      a3 = Array.from(a3);
      for (var c2 = 0; c2 < a3.length; ) {
        var d2 = a3[c2++];
        if (5 === d2.tag) fb(d2) || b2.push(d2.stateNode);
        else for (d2 = d2.child; null !== d2; ) a3.push(d2), d2 = d2.sibling;
      }
      return b2;
    }
    var lh = Math.ceil, mh = ea2.ReactCurrentDispatcher, nh = ea2.ReactCurrentOwner, U2 = ea2.ReactCurrentBatchConfig, G2 = 0, F2 = null, W2 = null, X2 = 0, Wf = 0, eg = gc(0), Q2 = 0, oh = null, vd = 0, ph = 0, qh = 0, rh = null, Y2 = null, Vg = 0, Uf = Infinity;
    function sh() {
      Uf = E2() + 500;
    }
    var Bf = false, Cf = null, Ef = null, th = false, uh = null, vh = 0, wh = 0, xh = null, yh = -1, zh = 0;
    function H2() {
      return 0 !== (G2 & 6) ? E2() : -1 !== yh ? yh : yh = E2();
    }
    function zd(a3) {
      if (0 === (a3.mode & 1)) return 1;
      if (0 !== (G2 & 2) && 0 !== X2) return X2 & -X2;
      if (null !== Yc.transition) return 0 === zh && (a3 = tc, tc <<= 1, 0 === (tc & 4194240) && (tc = 64), zh = a3), zh;
      a3 = D2;
      return 0 !== a3 ? a3 : Ya();
    }
    function Ad(a3, b2, c2) {
      if (50 < wh) throw wh = 0, xh = null, Error(n2(185));
      var d2 = Ah(a3, b2);
      if (null === d2) return null;
      Bc(d2, b2, c2);
      if (0 === (G2 & 2) || d2 !== F2) d2 === F2 && (0 === (G2 & 2) && (ph |= b2), 4 === Q2 && Bh(d2, X2)), Z2(d2, c2), 1 === b2 && 0 === G2 && 0 === (a3.mode & 1) && (sh(), Tc && Xc());
      return d2;
    }
    function Ah(a3, b2) {
      a3.lanes |= b2;
      var c2 = a3.alternate;
      null !== c2 && (c2.lanes |= b2);
      c2 = a3;
      for (a3 = a3.return; null !== a3; ) a3.childLanes |= b2, c2 = a3.alternate, null !== c2 && (c2.childLanes |= b2), c2 = a3, a3 = a3.return;
      return 3 === c2.tag ? c2.stateNode : null;
    }
    function Z2(a3, b2) {
      var c2 = a3.callbackNode;
      yc(a3, b2);
      var d2 = wc(a3, a3 === F2 ? X2 : 0);
      if (0 === d2) null !== c2 && Gc(c2), a3.callbackNode = null, a3.callbackPriority = 0;
      else if (b2 = d2 & -d2, a3.callbackPriority !== b2) {
        null != c2 && Gc(c2);
        if (1 === b2) 0 === a3.tag ? Wc(Ch.bind(null, a3)) : Vc(Ch.bind(null, a3)), $a ? ab(function() {
          0 === G2 && Xc();
        }) : Fc(Jc, Xc), c2 = null;
        else {
          switch (Ec(d2)) {
            case 1:
              c2 = Jc;
              break;
            case 4:
              c2 = Kc;
              break;
            case 16:
              c2 = Lc;
              break;
            case 536870912:
              c2 = Mc;
              break;
            default:
              c2 = Lc;
          }
          c2 = Dh(c2, Eh.bind(null, a3));
        }
        a3.callbackPriority = b2;
        a3.callbackNode = c2;
      }
    }
    function Eh(a3, b2) {
      yh = -1;
      zh = 0;
      if (0 !== (G2 & 6)) throw Error(n2(327));
      var c2 = a3.callbackNode;
      if (Fh() && a3.callbackNode !== c2) return null;
      var d2 = wc(a3, a3 === F2 ? X2 : 0);
      if (0 === d2) return null;
      if (0 !== (d2 & 30) || 0 !== (d2 & a3.expiredLanes) || b2) b2 = Gh(a3, d2);
      else {
        b2 = d2;
        var e2 = G2;
        G2 |= 2;
        var f2 = Hh();
        if (F2 !== a3 || X2 !== b2) sh(), Ih(a3, b2);
        do
          try {
            Jh();
            break;
          } catch (h2) {
            Kh(a3, h2);
          }
        while (1);
        fd2();
        mh.current = f2;
        G2 = e2;
        null !== W2 ? b2 = 0 : (F2 = null, X2 = 0, b2 = Q2);
      }
      if (0 !== b2) {
        2 === b2 && (e2 = zc(a3), 0 !== e2 && (d2 = e2, b2 = Lh(a3, e2)));
        if (1 === b2) throw c2 = oh, Ih(a3, 0), Bh(a3, d2), Z2(a3, E2()), c2;
        if (6 === b2) Bh(a3, d2);
        else {
          e2 = a3.current.alternate;
          if (0 === (d2 & 30) && !Mh(e2) && (b2 = Gh(a3, d2), 2 === b2 && (f2 = zc(a3), 0 !== f2 && (d2 = f2, b2 = Lh(a3, f2))), 1 === b2)) throw c2 = oh, Ih(a3, 0), Bh(a3, d2), Z2(a3, E2()), c2;
          a3.finishedWork = e2;
          a3.finishedLanes = d2;
          switch (b2) {
            case 0:
            case 1:
              throw Error(n2(345));
            case 2:
              Nh(a3, Y2);
              break;
            case 3:
              Bh(a3, d2);
              if ((d2 & 130023424) === d2 && (b2 = Vg + 500 - E2(), 10 < b2)) {
                if (0 !== wc(a3, 0)) break;
                e2 = a3.suspendedLanes;
                if ((e2 & d2) !== d2) {
                  H2();
                  a3.pingedLanes |= a3.suspendedLanes & e2;
                  break;
                }
                a3.timeoutHandle = Qa(Nh.bind(null, a3, Y2), b2);
                break;
              }
              Nh(a3, Y2);
              break;
            case 4:
              Bh(a3, d2);
              if ((d2 & 4194240) === d2) break;
              b2 = a3.eventTimes;
              for (e2 = -1; 0 < d2; ) {
                var g2 = 31 - qc(d2);
                f2 = 1 << g2;
                g2 = b2[g2];
                g2 > e2 && (e2 = g2);
                d2 &= ~f2;
              }
              d2 = e2;
              d2 = E2() - d2;
              d2 = (120 > d2 ? 120 : 480 > d2 ? 480 : 1080 > d2 ? 1080 : 1920 > d2 ? 1920 : 3e3 > d2 ? 3e3 : 4320 > d2 ? 4320 : 1960 * lh(d2 / 1960)) - d2;
              if (10 < d2) {
                a3.timeoutHandle = Qa(Nh.bind(null, a3, Y2), d2);
                break;
              }
              Nh(a3, Y2);
              break;
            case 5:
              Nh(a3, Y2);
              break;
            default:
              throw Error(n2(329));
          }
        }
      }
      Z2(a3, E2());
      return a3.callbackNode === c2 ? Eh.bind(null, a3) : null;
    }
    function Lh(a3, b2) {
      var c2 = rh;
      a3.current.memoizedState.isDehydrated && (Ih(a3, b2).flags |= 256);
      a3 = Gh(a3, b2);
      2 !== a3 && (b2 = Y2, Y2 = c2, null !== b2 && Sf(b2));
      return a3;
    }
    function Sf(a3) {
      null === Y2 ? Y2 = a3 : Y2.push.apply(Y2, a3);
    }
    function Mh(a3) {
      for (var b2 = a3; ; ) {
        if (b2.flags & 16384) {
          var c2 = b2.updateQueue;
          if (null !== c2 && (c2 = c2.stores, null !== c2)) for (var d2 = 0; d2 < c2.length; d2++) {
            var e2 = c2[d2], f2 = e2.getSnapshot;
            e2 = e2.value;
            try {
              if (!Rc(f2(), e2)) return false;
            } catch (g2) {
              return false;
            }
          }
        }
        c2 = b2.child;
        if (b2.subtreeFlags & 16384 && null !== c2) c2.return = b2, b2 = c2;
        else {
          if (b2 === a3) break;
          for (; null === b2.sibling; ) {
            if (null === b2.return || b2.return === a3) return true;
            b2 = b2.return;
          }
          b2.sibling.return = b2.return;
          b2 = b2.sibling;
        }
      }
      return true;
    }
    function Bh(a3, b2) {
      b2 &= ~qh;
      b2 &= ~ph;
      a3.suspendedLanes |= b2;
      a3.pingedLanes &= ~b2;
      for (a3 = a3.expirationTimes; 0 < b2; ) {
        var c2 = 31 - qc(b2), d2 = 1 << c2;
        a3[c2] = -1;
        b2 &= ~d2;
      }
    }
    function Ch(a3) {
      if (0 !== (G2 & 6)) throw Error(n2(327));
      Fh();
      var b2 = wc(a3, 0);
      if (0 === (b2 & 1)) return Z2(a3, E2()), null;
      var c2 = Gh(a3, b2);
      if (0 !== a3.tag && 2 === c2) {
        var d2 = zc(a3);
        0 !== d2 && (b2 = d2, c2 = Lh(a3, d2));
      }
      if (1 === c2) throw c2 = oh, Ih(a3, 0), Bh(a3, b2), Z2(a3, E2()), c2;
      if (6 === c2) throw Error(n2(345));
      a3.finishedWork = a3.current.alternate;
      a3.finishedLanes = b2;
      Nh(a3, Y2);
      Z2(a3, E2());
      return null;
    }
    function Oh(a3) {
      null !== uh && 0 === uh.tag && 0 === (G2 & 6) && Fh();
      var b2 = G2;
      G2 |= 1;
      var c2 = U2.transition, d2 = D2;
      try {
        if (U2.transition = null, D2 = 1, a3) return a3();
      } finally {
        D2 = d2, U2.transition = c2, G2 = b2, 0 === (G2 & 6) && Xc();
      }
    }
    function Vf() {
      Wf = eg.current;
      x(eg);
    }
    function Ih(a3, b2) {
      a3.finishedWork = null;
      a3.finishedLanes = 0;
      var c2 = a3.timeoutHandle;
      c2 !== Sa && (a3.timeoutHandle = Sa, Ra(c2));
      if (null !== W2) for (c2 = W2.return; null !== c2; ) {
        var d2 = c2;
        Sd(d2);
        switch (d2.tag) {
          case 1:
            d2 = d2.type.childContextTypes;
            null !== d2 && void 0 !== d2 && kc();
            break;
          case 3:
            we2();
            x(B);
            x(A2);
            Be2();
            break;
          case 5:
            ye2(d2);
            break;
          case 4:
            we2();
            break;
          case 13:
            x(J2);
            break;
          case 19:
            x(J2);
            break;
          case 10:
            hd(d2.type._context);
            break;
          case 22:
          case 23:
            Vf();
        }
        c2 = c2.return;
      }
      F2 = a3;
      W2 = a3 = je2(a3.current, null);
      X2 = Wf = b2;
      Q2 = 0;
      oh = null;
      qh = ph = vd = 0;
      Y2 = rh = null;
      if (null !== md) {
        for (b2 = 0; b2 < md.length; b2++) if (c2 = md[b2], d2 = c2.interleaved, null !== d2) {
          c2.interleaved = null;
          var e2 = d2.next, f2 = c2.pending;
          if (null !== f2) {
            var g2 = f2.next;
            f2.next = e2;
            d2.next = g2;
          }
          c2.pending = d2;
        }
        md = null;
      }
      return a3;
    }
    function Kh(a3, b2) {
      do {
        var c2 = W2;
        try {
          fd2();
          Ce2.current = Oe2;
          if (Fe2) {
            for (var d2 = K2.memoizedState; null !== d2; ) {
              var e2 = d2.queue;
              null !== e2 && (e2.pending = null);
              d2 = d2.next;
            }
            Fe2 = false;
          }
          Ee2 = 0;
          M2 = L2 = K2 = null;
          Ge2 = false;
          He2 = 0;
          nh.current = null;
          if (null === c2 || null === c2.return) {
            Q2 = 1;
            oh = b2;
            W2 = null;
            break;
          }
          a: {
            var f2 = a3, g2 = c2.return, h2 = c2, k2 = b2;
            b2 = X2;
            h2.flags |= 32768;
            if (null !== k2 && "object" === typeof k2 && "function" === typeof k2.then) {
              var l2 = k2, m2 = h2, v5 = m2.tag;
              if (0 === (m2.mode & 1) && (0 === v5 || 11 === v5 || 15 === v5)) {
                var r2 = m2.alternate;
                r2 ? (m2.updateQueue = r2.updateQueue, m2.memoizedState = r2.memoizedState, m2.lanes = r2.lanes) : (m2.updateQueue = null, m2.memoizedState = null);
              }
              var z2 = Hf(g2);
              if (null !== z2) {
                z2.flags &= -257;
                If(z2, g2, h2, f2, b2);
                z2.mode & 1 && Ff(f2, l2, b2);
                b2 = z2;
                k2 = l2;
                var q3 = b2.updateQueue;
                if (null === q3) {
                  var N2 = /* @__PURE__ */ new Set();
                  N2.add(k2);
                  b2.updateQueue = N2;
                } else q3.add(k2);
                break a;
              } else {
                if (0 === (b2 & 1)) {
                  Ff(f2, l2, b2);
                  Tf();
                  break a;
                }
                k2 = Error(n2(426));
              }
            } else if (I2 && h2.mode & 1) {
              var da2 = Hf(g2);
              if (null !== da2) {
                0 === (da2.flags & 65536) && (da2.flags |= 256);
                If(da2, g2, h2, f2, b2);
                ee2(k2);
                break a;
              }
            }
            f2 = k2;
            4 !== Q2 && (Q2 = 2);
            null === rh ? rh = [f2] : rh.push(f2);
            k2 = xf(k2, h2);
            h2 = g2;
            do {
              switch (h2.tag) {
                case 3:
                  h2.flags |= 65536;
                  b2 &= -b2;
                  h2.lanes |= b2;
                  var t2 = Af(h2, k2, b2);
                  td2(h2, t2);
                  break a;
                case 1:
                  f2 = k2;
                  var w2 = h2.type, u2 = h2.stateNode;
                  if (0 === (h2.flags & 128) && ("function" === typeof w2.getDerivedStateFromError || null !== u2 && "function" === typeof u2.componentDidCatch && (null === Ef || !Ef.has(u2)))) {
                    h2.flags |= 65536;
                    b2 &= -b2;
                    h2.lanes |= b2;
                    var V2 = Df(h2, f2, b2);
                    td2(h2, V2);
                    break a;
                  }
              }
              h2 = h2.return;
            } while (null !== h2);
          }
          Ph(c2);
        } catch (wa) {
          b2 = wa;
          W2 === c2 && null !== c2 && (W2 = c2 = c2.return);
          continue;
        }
        break;
      } while (1);
    }
    function Hh() {
      var a3 = mh.current;
      mh.current = Oe2;
      return null === a3 ? Oe2 : a3;
    }
    function Tf() {
      if (0 === Q2 || 3 === Q2 || 2 === Q2) Q2 = 4;
      null === F2 || 0 === (vd & 268435455) && 0 === (ph & 268435455) || Bh(F2, X2);
    }
    function Gh(a3, b2) {
      var c2 = G2;
      G2 |= 2;
      var d2 = Hh();
      F2 === a3 && X2 === b2 || Ih(a3, b2);
      do
        try {
          Qh();
          break;
        } catch (e2) {
          Kh(a3, e2);
        }
      while (1);
      fd2();
      G2 = c2;
      mh.current = d2;
      if (null !== W2) throw Error(n2(261));
      F2 = null;
      X2 = 0;
      return Q2;
    }
    function Qh() {
      for (; null !== W2; ) Rh(W2);
    }
    function Jh() {
      for (; null !== W2 && !Hc(); ) Rh(W2);
    }
    function Rh(a3) {
      var b2 = Sh(a3.alternate, a3, Wf);
      a3.memoizedProps = a3.pendingProps;
      null === b2 ? Ph(a3) : W2 = b2;
      nh.current = null;
    }
    function Ph(a3) {
      var b2 = a3;
      do {
        var c2 = b2.alternate;
        a3 = b2.return;
        if (0 === (b2.flags & 32768)) {
          if (c2 = Rf(c2, b2, Wf), null !== c2) {
            W2 = c2;
            return;
          }
        } else {
          c2 = xg(c2, b2);
          if (null !== c2) {
            c2.flags &= 32767;
            W2 = c2;
            return;
          }
          if (null !== a3) a3.flags |= 32768, a3.subtreeFlags = 0, a3.deletions = null;
          else {
            Q2 = 6;
            W2 = null;
            return;
          }
        }
        b2 = b2.sibling;
        if (null !== b2) {
          W2 = b2;
          return;
        }
        W2 = b2 = a3;
      } while (null !== b2);
      0 === Q2 && (Q2 = 5);
    }
    function Nh(a3, b2) {
      var c2 = D2, d2 = U2.transition;
      try {
        U2.transition = null, D2 = 1, Th(a3, b2, c2);
      } finally {
        U2.transition = d2, D2 = c2;
      }
      return null;
    }
    function Th(a3, b2, c2) {
      do
        Fh();
      while (null !== uh);
      if (0 !== (G2 & 6)) throw Error(n2(327));
      var d2 = a3.finishedWork, e2 = a3.finishedLanes;
      if (null === d2) return null;
      a3.finishedWork = null;
      a3.finishedLanes = 0;
      if (d2 === a3.current) throw Error(n2(177));
      a3.callbackNode = null;
      a3.callbackPriority = 0;
      var f2 = d2.lanes | d2.childLanes;
      Cc(a3, f2);
      a3 === F2 && (W2 = F2 = null, X2 = 0);
      0 === (d2.subtreeFlags & 2064) && 0 === (d2.flags & 2064) || th || (th = true, Dh(Lc, function() {
        Fh();
        return null;
      }));
      f2 = 0 !== (d2.flags & 15990);
      if (0 !== (d2.subtreeFlags & 15990) || f2) {
        f2 = U2.transition;
        U2.transition = null;
        var g2 = D2;
        D2 = 1;
        var h2 = G2;
        G2 |= 4;
        nh.current = null;
        Eg(a3, d2);
        Ug(a3, d2);
        Ja(a3.containerInfo);
        a3.current = d2;
        Xg(d2);
        Ic();
        G2 = h2;
        D2 = g2;
        U2.transition = f2;
      } else a3.current = d2;
      th && (th = false, uh = a3, vh = e2);
      f2 = a3.pendingLanes;
      0 === f2 && (Ef = null);
      Pc(d2.stateNode);
      Z2(a3, E2());
      if (null !== b2) for (c2 = a3.onRecoverableError, d2 = 0; d2 < b2.length; d2++) c2(b2[d2]);
      if (Bf) throw Bf = false, a3 = Cf, Cf = null, a3;
      0 !== (vh & 1) && 0 !== a3.tag && Fh();
      f2 = a3.pendingLanes;
      0 !== (f2 & 1) ? a3 === xh ? wh++ : (wh = 0, xh = a3) : wh = 0;
      Xc();
      return null;
    }
    function Fh() {
      if (null !== uh) {
        var a3 = Ec(vh), b2 = U2.transition, c2 = D2;
        try {
          U2.transition = null;
          D2 = 16 > a3 ? 16 : a3;
          if (null === uh) var d2 = false;
          else {
            a3 = uh;
            uh = null;
            vh = 0;
            if (0 !== (G2 & 6)) throw Error(n2(331));
            var e2 = G2;
            G2 |= 4;
            for (S2 = a3.current; null !== S2; ) {
              var f2 = S2, g2 = f2.child;
              if (0 !== (S2.flags & 16)) {
                var h2 = f2.deletions;
                if (null !== h2) {
                  for (var k2 = 0; k2 < h2.length; k2++) {
                    var l2 = h2[k2];
                    for (S2 = l2; null !== S2; ) {
                      var m2 = S2;
                      switch (m2.tag) {
                        case 0:
                        case 11:
                        case 15:
                          Fg(8, m2, f2);
                      }
                      var v5 = m2.child;
                      if (null !== v5) v5.return = m2, S2 = v5;
                      else for (; null !== S2; ) {
                        m2 = S2;
                        var r2 = m2.sibling, z2 = m2.return;
                        Lg(m2);
                        if (m2 === l2) {
                          S2 = null;
                          break;
                        }
                        if (null !== r2) {
                          r2.return = z2;
                          S2 = r2;
                          break;
                        }
                        S2 = z2;
                      }
                    }
                  }
                  var q3 = f2.alternate;
                  if (null !== q3) {
                    var N2 = q3.child;
                    if (null !== N2) {
                      q3.child = null;
                      do {
                        var da2 = N2.sibling;
                        N2.sibling = null;
                        N2 = da2;
                      } while (null !== N2);
                    }
                  }
                  S2 = f2;
                }
              }
              if (0 !== (f2.subtreeFlags & 2064) && null !== g2) g2.return = f2, S2 = g2;
              else b: for (; null !== S2; ) {
                f2 = S2;
                if (0 !== (f2.flags & 2048)) switch (f2.tag) {
                  case 0:
                  case 11:
                  case 15:
                    Fg(9, f2, f2.return);
                }
                var t2 = f2.sibling;
                if (null !== t2) {
                  t2.return = f2.return;
                  S2 = t2;
                  break b;
                }
                S2 = f2.return;
              }
            }
            var w2 = a3.current;
            for (S2 = w2; null !== S2; ) {
              g2 = S2;
              var u2 = g2.child;
              if (0 !== (g2.subtreeFlags & 2064) && null !== u2) u2.return = g2, S2 = u2;
              else b: for (g2 = w2; null !== S2; ) {
                h2 = S2;
                if (0 !== (h2.flags & 2048)) try {
                  switch (h2.tag) {
                    case 0:
                    case 11:
                    case 15:
                      Gg(9, h2);
                  }
                } catch (wa) {
                  T3(h2, h2.return, wa);
                }
                if (h2 === g2) {
                  S2 = null;
                  break b;
                }
                var V2 = h2.sibling;
                if (null !== V2) {
                  V2.return = h2.return;
                  S2 = V2;
                  break b;
                }
                S2 = h2.return;
              }
            }
            G2 = e2;
            Xc();
            if (Oc && "function" === typeof Oc.onPostCommitFiberRoot) try {
              Oc.onPostCommitFiberRoot(Nc, a3);
            } catch (wa) {
            }
            d2 = true;
          }
          return d2;
        } finally {
          D2 = c2, U2.transition = b2;
        }
      }
      return false;
    }
    function Uh(a3, b2, c2) {
      b2 = xf(c2, b2);
      b2 = Af(a3, b2, 1);
      rd(a3, b2);
      b2 = H2();
      a3 = Ah(a3, 1);
      null !== a3 && (Bc(a3, 1, b2), Z2(a3, b2));
    }
    function T3(a3, b2, c2) {
      if (3 === a3.tag) Uh(a3, a3, c2);
      else for (; null !== b2; ) {
        if (3 === b2.tag) {
          Uh(b2, a3, c2);
          break;
        } else if (1 === b2.tag) {
          var d2 = b2.stateNode;
          if ("function" === typeof b2.type.getDerivedStateFromError || "function" === typeof d2.componentDidCatch && (null === Ef || !Ef.has(d2))) {
            a3 = xf(c2, a3);
            a3 = Df(b2, a3, 1);
            rd(b2, a3);
            a3 = H2();
            b2 = Ah(b2, 1);
            null !== b2 && (Bc(b2, 1, a3), Z2(b2, a3));
            break;
          }
        }
        b2 = b2.return;
      }
    }
    function Gf(a3, b2, c2) {
      var d2 = a3.pingCache;
      null !== d2 && d2.delete(b2);
      b2 = H2();
      a3.pingedLanes |= a3.suspendedLanes & c2;
      F2 === a3 && (X2 & c2) === c2 && (4 === Q2 || 3 === Q2 && (X2 & 130023424) === X2 && 500 > E2() - Vg ? Ih(a3, 0) : qh |= c2);
      Z2(a3, b2);
    }
    function Vh(a3, b2) {
      0 === b2 && (0 === (a3.mode & 1) ? b2 = 1 : (b2 = uc, uc <<= 1, 0 === (uc & 130023424) && (uc = 4194304)));
      var c2 = H2();
      a3 = Ah(a3, b2);
      null !== a3 && (Bc(a3, b2, c2), Z2(a3, c2));
    }
    function qg(a3) {
      var b2 = a3.memoizedState, c2 = 0;
      null !== b2 && (c2 = b2.retryLane);
      Vh(a3, c2);
    }
    function Tg(a3, b2) {
      var c2 = 0;
      switch (a3.tag) {
        case 13:
          var d2 = a3.stateNode;
          var e2 = a3.memoizedState;
          null !== e2 && (c2 = e2.retryLane);
          break;
        case 19:
          d2 = a3.stateNode;
          break;
        default:
          throw Error(n2(314));
      }
      null !== d2 && d2.delete(b2);
      Vh(a3, c2);
    }
    var Sh;
    Sh = function(a3, b2, c2) {
      if (null !== a3) if (a3.memoizedProps !== b2.pendingProps || B.current) kd = true;
      else {
        if (0 === (a3.lanes & c2) && 0 === (b2.flags & 128)) return kd = false, wg(a3, b2, c2);
        kd = 0 !== (a3.flags & 131072) ? true : false;
      }
      else kd = false, I2 && 0 !== (b2.flags & 1048576) && Qd(b2, Jd, b2.index);
      b2.lanes = 0;
      switch (b2.tag) {
        case 2:
          var d2 = b2.type;
          null !== a3 && (a3.alternate = null, b2.alternate = null, b2.flags |= 2);
          a3 = b2.pendingProps;
          var e2 = jc(b2, A2.current);
          jd(b2, c2);
          e2 = Ke2(null, b2, d2, a3, e2, c2);
          var f2 = Pe2();
          b2.flags |= 1;
          "object" === typeof e2 && null !== e2 && "function" === typeof e2.render && void 0 === e2.$$typeof ? (b2.tag = 1, b2.memoizedState = null, b2.updateQueue = null, C2(d2) ? (f2 = true, nc(b2)) : f2 = false, b2.memoizedState = null !== e2.state && void 0 !== e2.state ? e2.state : null, od(b2), e2.updater = Bd, b2.stateNode = e2, e2._reactInternals = b2, Fd(b2, d2, a3, c2), b2 = hg(null, b2, d2, true, f2, c2)) : (b2.tag = 0, I2 && f2 && Rd(b2), R2(null, b2, e2, c2), b2 = b2.child);
          return b2;
        case 16:
          d2 = b2.elementType;
          a: {
            null !== a3 && (a3.alternate = null, b2.alternate = null, b2.flags |= 2);
            a3 = b2.pendingProps;
            e2 = d2._init;
            d2 = e2(d2._payload);
            b2.type = d2;
            e2 = b2.tag = Wh(d2);
            a3 = ad(d2, a3);
            switch (e2) {
              case 0:
                b2 = cg(null, b2, d2, a3, c2);
                break a;
              case 1:
                b2 = gg(
                  null,
                  b2,
                  d2,
                  a3,
                  c2
                );
                break a;
              case 11:
                b2 = Yf(null, b2, d2, a3, c2);
                break a;
              case 14:
                b2 = $f(null, b2, d2, ad(d2.type, a3), c2);
                break a;
            }
            throw Error(n2(306, d2, ""));
          }
          return b2;
        case 0:
          return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : ad(d2, e2), cg(a3, b2, d2, e2, c2);
        case 1:
          return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : ad(d2, e2), gg(a3, b2, d2, e2, c2);
        case 3:
          a: {
            ig(b2);
            if (null === a3) throw Error(n2(387));
            d2 = b2.pendingProps;
            f2 = b2.memoizedState;
            e2 = f2.element;
            pd(a3, b2);
            ud(b2, d2, null, c2);
            var g2 = b2.memoizedState;
            d2 = g2.element;
            if (p2 && f2.isDehydrated) if (f2 = {
              element: d2,
              isDehydrated: false,
              cache: g2.cache,
              transitions: g2.transitions
            }, b2.updateQueue.baseState = f2, b2.memoizedState = f2, b2.flags & 256) {
              e2 = Error(n2(423));
              b2 = jg(a3, b2, d2, c2, e2);
              break a;
            } else if (d2 !== e2) {
              e2 = Error(n2(424));
              b2 = jg(a3, b2, d2, c2, e2);
              break a;
            } else for (p2 && (Ud = Nb(b2.stateNode.containerInfo), Td = b2, I2 = true, Wd = null, Vd = false), c2 = pe(b2, null, d2, c2), b2.child = c2; c2; ) c2.flags = c2.flags & -3 | 4096, c2 = c2.sibling;
            else {
              de2();
              if (d2 === e2) {
                b2 = Zf(a3, b2, c2);
                break a;
              }
              R2(a3, b2, d2, c2);
            }
            b2 = b2.child;
          }
          return b2;
        case 5:
          return xe2(b2), null === a3 && ae(b2), d2 = b2.type, e2 = b2.pendingProps, f2 = null !== a3 ? a3.memoizedProps : null, g2 = e2.children, Oa(d2, e2) ? g2 = null : null !== f2 && Oa(d2, f2) && (b2.flags |= 32), fg(a3, b2), R2(a3, b2, g2, c2), b2.child;
        case 6:
          return null === a3 && ae(b2), null;
        case 13:
          return mg(a3, b2, c2);
        case 4:
          return ve2(b2, b2.stateNode.containerInfo), d2 = b2.pendingProps, null === a3 ? b2.child = oe2(b2, null, d2, c2) : R2(a3, b2, d2, c2), b2.child;
        case 11:
          return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : ad(d2, e2), Yf(a3, b2, d2, e2, c2);
        case 7:
          return R2(a3, b2, b2.pendingProps, c2), b2.child;
        case 8:
          return R2(a3, b2, b2.pendingProps.children, c2), b2.child;
        case 12:
          return R2(a3, b2, b2.pendingProps.children, c2), b2.child;
        case 10:
          a: {
            d2 = b2.type._context;
            e2 = b2.pendingProps;
            f2 = b2.memoizedProps;
            g2 = e2.value;
            gd(b2, d2, g2);
            if (null !== f2) if (Rc(f2.value, g2)) {
              if (f2.children === e2.children && !B.current) {
                b2 = Zf(a3, b2, c2);
                break a;
              }
            } else for (f2 = b2.child, null !== f2 && (f2.return = b2); null !== f2; ) {
              var h2 = f2.dependencies;
              if (null !== h2) {
                g2 = f2.child;
                for (var k2 = h2.firstContext; null !== k2; ) {
                  if (k2.context === d2) {
                    if (1 === f2.tag) {
                      k2 = qd(-1, c2 & -c2);
                      k2.tag = 2;
                      var l2 = f2.updateQueue;
                      if (null !== l2) {
                        l2 = l2.shared;
                        var m2 = l2.pending;
                        null === m2 ? k2.next = k2 : (k2.next = m2.next, m2.next = k2);
                        l2.pending = k2;
                      }
                    }
                    f2.lanes |= c2;
                    k2 = f2.alternate;
                    null !== k2 && (k2.lanes |= c2);
                    id(f2.return, c2, b2);
                    h2.lanes |= c2;
                    break;
                  }
                  k2 = k2.next;
                }
              } else if (10 === f2.tag) g2 = f2.type === b2.type ? null : f2.child;
              else if (18 === f2.tag) {
                g2 = f2.return;
                if (null === g2) throw Error(n2(341));
                g2.lanes |= c2;
                h2 = g2.alternate;
                null !== h2 && (h2.lanes |= c2);
                id(g2, c2, b2);
                g2 = f2.sibling;
              } else g2 = f2.child;
              if (null !== g2) g2.return = f2;
              else for (g2 = f2; null !== g2; ) {
                if (g2 === b2) {
                  g2 = null;
                  break;
                }
                f2 = g2.sibling;
                if (null !== f2) {
                  f2.return = g2.return;
                  g2 = f2;
                  break;
                }
                g2 = g2.return;
              }
              f2 = g2;
            }
            R2(a3, b2, e2.children, c2);
            b2 = b2.child;
          }
          return b2;
        case 9:
          return e2 = b2.type, d2 = b2.pendingProps.children, jd(b2, c2), e2 = ld(e2), d2 = d2(e2), b2.flags |= 1, R2(a3, b2, d2, c2), b2.child;
        case 14:
          return d2 = b2.type, e2 = ad(d2, b2.pendingProps), e2 = ad(d2.type, e2), $f(a3, b2, d2, e2, c2);
        case 15:
          return bg(a3, b2, b2.type, b2.pendingProps, c2);
        case 17:
          return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : ad(d2, e2), null !== a3 && (a3.alternate = null, b2.alternate = null, b2.flags |= 2), b2.tag = 1, C2(d2) ? (a3 = true, nc(b2)) : a3 = false, jd(b2, c2), Dd(b2, d2, e2), Fd(b2, d2, e2, c2), hg(null, b2, d2, true, a3, c2);
        case 19:
          return vg(a3, b2, c2);
        case 22:
          return dg(a3, b2, c2);
      }
      throw Error(n2(156, b2.tag));
    };
    function Dh(a3, b2) {
      return Fc(a3, b2);
    }
    function Xh(a3, b2, c2, d2) {
      this.tag = a3;
      this.key = c2;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.ref = null;
      this.pendingProps = b2;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = d2;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
    }
    function Yd(a3, b2, c2, d2) {
      return new Xh(a3, b2, c2, d2);
    }
    function ag(a3) {
      a3 = a3.prototype;
      return !(!a3 || !a3.isReactComponent);
    }
    function Wh(a3) {
      if ("function" === typeof a3) return ag(a3) ? 1 : 0;
      if (void 0 !== a3 && null !== a3) {
        a3 = a3.$$typeof;
        if (a3 === na) return 11;
        if (a3 === qa) return 14;
      }
      return 2;
    }
    function je2(a3, b2) {
      var c2 = a3.alternate;
      null === c2 ? (c2 = Yd(a3.tag, b2, a3.key, a3.mode), c2.elementType = a3.elementType, c2.type = a3.type, c2.stateNode = a3.stateNode, c2.alternate = a3, a3.alternate = c2) : (c2.pendingProps = b2, c2.type = a3.type, c2.flags = 0, c2.subtreeFlags = 0, c2.deletions = null);
      c2.flags = a3.flags & 14680064;
      c2.childLanes = a3.childLanes;
      c2.lanes = a3.lanes;
      c2.child = a3.child;
      c2.memoizedProps = a3.memoizedProps;
      c2.memoizedState = a3.memoizedState;
      c2.updateQueue = a3.updateQueue;
      b2 = a3.dependencies;
      c2.dependencies = null === b2 ? null : { lanes: b2.lanes, firstContext: b2.firstContext };
      c2.sibling = a3.sibling;
      c2.index = a3.index;
      c2.ref = a3.ref;
      return c2;
    }
    function le2(a3, b2, c2, d2, e2, f2) {
      var g2 = 2;
      d2 = a3;
      if ("function" === typeof a3) ag(a3) && (g2 = 1);
      else if ("string" === typeof a3) g2 = 5;
      else a: switch (a3) {
        case ia:
          return ne2(c2.children, e2, f2, b2);
        case ja:
          g2 = 8;
          e2 |= 8;
          break;
        case ka:
          return a3 = Yd(12, c2, b2, e2 | 2), a3.elementType = ka, a3.lanes = f2, a3;
        case oa:
          return a3 = Yd(13, c2, b2, e2), a3.elementType = oa, a3.lanes = f2, a3;
        case pa2:
          return a3 = Yd(19, c2, b2, e2), a3.elementType = pa2, a3.lanes = f2, a3;
        case sa:
          return ng(c2, e2, f2, b2);
        default:
          if ("object" === typeof a3 && null !== a3) switch (a3.$$typeof) {
            case la2:
              g2 = 10;
              break a;
            case ma:
              g2 = 9;
              break a;
            case na:
              g2 = 11;
              break a;
            case qa:
              g2 = 14;
              break a;
            case ra:
              g2 = 16;
              d2 = null;
              break a;
          }
          throw Error(n2(130, null == a3 ? a3 : typeof a3, ""));
      }
      b2 = Yd(g2, c2, b2, e2);
      b2.elementType = a3;
      b2.type = d2;
      b2.lanes = f2;
      return b2;
    }
    function ne2(a3, b2, c2, d2) {
      a3 = Yd(7, a3, d2, b2);
      a3.lanes = c2;
      return a3;
    }
    function ng(a3, b2, c2, d2) {
      a3 = Yd(22, a3, d2, b2);
      a3.elementType = sa;
      a3.lanes = c2;
      a3.stateNode = {};
      return a3;
    }
    function ke2(a3, b2, c2) {
      a3 = Yd(6, a3, null, b2);
      a3.lanes = c2;
      return a3;
    }
    function me2(a3, b2, c2) {
      b2 = Yd(4, null !== a3.children ? a3.children : [], a3.key, b2);
      b2.lanes = c2;
      b2.stateNode = { containerInfo: a3.containerInfo, pendingChildren: null, implementation: a3.implementation };
      return b2;
    }
    function Yh(a3, b2, c2, d2, e2) {
      this.tag = b2;
      this.containerInfo = a3;
      this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = Sa;
      this.callbackNode = this.pendingContext = this.context = null;
      this.callbackPriority = 0;
      this.eventTimes = Ac(0);
      this.expirationTimes = Ac(-1);
      this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = Ac(0);
      this.identifierPrefix = d2;
      this.onRecoverableError = e2;
      p2 && (this.mutableSourceEagerHydrationData = null);
    }
    function Zh(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
      a3 = new Yh(a3, b2, c2, h2, k2);
      1 === b2 ? (b2 = 1, true === f2 && (b2 |= 8)) : b2 = 0;
      f2 = Yd(3, null, null, b2);
      a3.current = f2;
      f2.stateNode = a3;
      f2.memoizedState = { element: d2, isDehydrated: c2, cache: null, transitions: null };
      od(f2);
      return a3;
    }
    function $h(a3) {
      if (!a3) return hc;
      a3 = a3._reactInternals;
      a: {
        if (ya(a3) !== a3 || 1 !== a3.tag) throw Error(n2(170));
        var b2 = a3;
        do {
          switch (b2.tag) {
            case 3:
              b2 = b2.stateNode.context;
              break a;
            case 1:
              if (C2(b2.type)) {
                b2 = b2.stateNode.__reactInternalMemoizedMergedChildContext;
                break a;
              }
          }
          b2 = b2.return;
        } while (null !== b2);
        throw Error(n2(171));
      }
      if (1 === a3.tag) {
        var c2 = a3.type;
        if (C2(c2)) return mc(a3, c2, b2);
      }
      return b2;
    }
    function ai(a3) {
      var b2 = a3._reactInternals;
      if (void 0 === b2) {
        if ("function" === typeof a3.render) throw Error(n2(188));
        a3 = Object.keys(a3).join(",");
        throw Error(n2(268, a3));
      }
      a3 = Ba(b2);
      return null === a3 ? null : a3.stateNode;
    }
    function bi(a3, b2) {
      a3 = a3.memoizedState;
      if (null !== a3 && null !== a3.dehydrated) {
        var c2 = a3.retryLane;
        a3.retryLane = 0 !== c2 && c2 < b2 ? c2 : b2;
      }
    }
    function ci(a3, b2) {
      bi(a3, b2);
      (a3 = a3.alternate) && bi(a3, b2);
    }
    function di(a3) {
      a3 = Ba(a3);
      return null === a3 ? null : a3.stateNode;
    }
    function ei() {
      return null;
    }
    exports$1.attemptContinuousHydration = function(a3) {
      if (13 === a3.tag) {
        var b2 = H2();
        Ad(a3, 134217728, b2);
        ci(a3, 134217728);
      }
    };
    exports$1.attemptHydrationAtCurrentPriority = function(a3) {
      if (13 === a3.tag) {
        var b2 = H2(), c2 = zd(a3);
        Ad(a3, c2, b2);
        ci(a3, c2);
      }
    };
    exports$1.attemptSynchronousHydration = function(a3) {
      switch (a3.tag) {
        case 3:
          var b2 = a3.stateNode;
          if (b2.current.memoizedState.isDehydrated) {
            var c2 = vc(b2.pendingLanes);
            0 !== c2 && (Dc(b2, c2 | 1), Z2(b2, E2()), 0 === (G2 & 6) && (sh(), Xc()));
          }
          break;
        case 13:
          var d2 = H2();
          Oh(function() {
            return Ad(a3, 1, d2);
          });
          ci(a3, 1);
      }
    };
    exports$1.batchedUpdates = function(a3, b2) {
      var c2 = G2;
      G2 |= 1;
      try {
        return a3(b2);
      } finally {
        G2 = c2, 0 === G2 && (sh(), Tc && Xc());
      }
    };
    exports$1.createComponentSelector = function(a3) {
      return { $$typeof: ah, value: a3 };
    };
    exports$1.createContainer = function(a3, b2, c2, d2, e2, f2, g2) {
      return Zh(a3, b2, false, null, c2, d2, e2, f2, g2);
    };
    exports$1.createHasPseudoClassSelector = function(a3) {
      return { $$typeof: bh, value: a3 };
    };
    exports$1.createHydrationContainer = function(a3, b2, c2, d2, e2, f2, g2, h2, k2) {
      a3 = Zh(c2, d2, true, a3, e2, f2, g2, h2, k2);
      a3.context = $h(null);
      c2 = a3.current;
      d2 = H2();
      e2 = zd(c2);
      f2 = qd(d2, e2);
      f2.callback = void 0 !== b2 && null !== b2 ? b2 : null;
      rd(c2, f2);
      a3.current.lanes = e2;
      Bc(a3, e2, d2);
      Z2(a3, d2);
      return a3;
    };
    exports$1.createPortal = function(a3, b2, c2) {
      var d2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      return { $$typeof: ha, key: null == d2 ? null : "" + d2, children: a3, containerInfo: b2, implementation: c2 };
    };
    exports$1.createRoleSelector = function(a3) {
      return { $$typeof: ch, value: a3 };
    };
    exports$1.createTestNameSelector = function(a3) {
      return { $$typeof: dh, value: a3 };
    };
    exports$1.createTextSelector = function(a3) {
      return { $$typeof: eh, value: a3 };
    };
    exports$1.deferredUpdates = function(a3) {
      var b2 = D2, c2 = U2.transition;
      try {
        return U2.transition = null, D2 = 16, a3();
      } finally {
        D2 = b2, U2.transition = c2;
      }
    };
    exports$1.discreteUpdates = function(a3, b2, c2, d2, e2) {
      var f2 = D2, g2 = U2.transition;
      try {
        return U2.transition = null, D2 = 1, a3(b2, c2, d2, e2);
      } finally {
        D2 = f2, U2.transition = g2, 0 === G2 && sh();
      }
    };
    exports$1.findAllNodes = kh;
    exports$1.findBoundingRects = function(a3, b2) {
      if (!bb) throw Error(n2(363));
      b2 = kh(a3, b2);
      a3 = [];
      for (var c2 = 0; c2 < b2.length; c2++) a3.push(db(b2[c2]));
      for (b2 = a3.length - 1; 0 < b2; b2--) {
        c2 = a3[b2];
        for (var d2 = c2.x, e2 = d2 + c2.width, f2 = c2.y, g2 = f2 + c2.height, h2 = b2 - 1; 0 <= h2; h2--) if (b2 !== h2) {
          var k2 = a3[h2], l2 = k2.x, m2 = l2 + k2.width, v5 = k2.y, r2 = v5 + k2.height;
          if (d2 >= l2 && f2 >= v5 && e2 <= m2 && g2 <= r2) {
            a3.splice(b2, 1);
            break;
          } else if (!(d2 !== l2 || c2.width !== k2.width || r2 < f2 || v5 > g2)) {
            v5 > f2 && (k2.height += v5 - f2, k2.y = f2);
            r2 < g2 && (k2.height = g2 - v5);
            a3.splice(b2, 1);
            break;
          } else if (!(f2 !== v5 || c2.height !== k2.height || m2 < d2 || l2 > e2)) {
            l2 > d2 && (k2.width += l2 - d2, k2.x = d2);
            m2 < e2 && (k2.width = e2 - l2);
            a3.splice(b2, 1);
            break;
          }
        }
      }
      return a3;
    };
    exports$1.findHostInstance = ai;
    exports$1.findHostInstanceWithNoPortals = function(a3) {
      a3 = Aa(a3);
      a3 = null !== a3 ? Da(a3) : null;
      return null === a3 ? null : a3.stateNode;
    };
    exports$1.findHostInstanceWithWarning = function(a3) {
      return ai(a3);
    };
    exports$1.flushControlled = function(a3) {
      var b2 = G2;
      G2 |= 1;
      var c2 = U2.transition, d2 = D2;
      try {
        U2.transition = null, D2 = 1, a3();
      } finally {
        D2 = d2, U2.transition = c2, G2 = b2, 0 === G2 && (sh(), Xc());
      }
    };
    exports$1.flushPassiveEffects = Fh;
    exports$1.flushSync = Oh;
    exports$1.focusWithin = function(a3, b2) {
      if (!bb) throw Error(n2(363));
      a3 = gh(a3);
      b2 = jh(a3, b2);
      b2 = Array.from(b2);
      for (a3 = 0; a3 < b2.length; ) {
        var c2 = b2[a3++];
        if (!fb(c2)) {
          if (5 === c2.tag && hb(c2.stateNode)) return true;
          for (c2 = c2.child; null !== c2; ) b2.push(c2), c2 = c2.sibling;
        }
      }
      return false;
    };
    exports$1.getCurrentUpdatePriority = function() {
      return D2;
    };
    exports$1.getFindAllNodesFailureDescription = function(a3, b2) {
      if (!bb) throw Error(n2(363));
      var c2 = 0, d2 = [];
      a3 = [gh(a3), 0];
      for (var e2 = 0; e2 < a3.length; ) {
        var f2 = a3[e2++], g2 = a3[e2++], h2 = b2[g2];
        if (5 !== f2.tag || !fb(f2)) {
          if (hh(f2, h2) && (d2.push(ih(h2)), g2++, g2 > c2 && (c2 = g2)), g2 < b2.length) for (f2 = f2.child; null !== f2; ) a3.push(f2, g2), f2 = f2.sibling;
        }
      }
      if (c2 < b2.length) {
        for (a3 = []; c2 < b2.length; c2++) a3.push(ih(b2[c2]));
        return "findAllNodes was able to match part of the selector:\n  " + (d2.join(" > ") + "\n\nNo matching component was found for:\n  ") + a3.join(" > ");
      }
      return null;
    };
    exports$1.getPublicRootInstance = function(a3) {
      a3 = a3.current;
      if (!a3.child) return null;
      switch (a3.child.tag) {
        case 5:
          return Fa(a3.child.stateNode);
        default:
          return a3.child.stateNode;
      }
    };
    exports$1.injectIntoDevTools = function(a3) {
      a3 = { bundleType: a3.bundleType, version: a3.version, rendererPackageName: a3.rendererPackageName, rendererConfig: a3.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setErrorHandler: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ea2.ReactCurrentDispatcher, findHostInstanceByFiber: di, findFiberByHostInstance: a3.findFiberByHostInstance || ei, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, reconcilerVersion: "18.0.0-fc46dba67-20220329" };
      if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) a3 = false;
      else {
        var b2 = __REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (b2.isDisabled || !b2.supportsFiber) a3 = true;
        else {
          try {
            Nc = b2.inject(a3), Oc = b2;
          } catch (c2) {
          }
          a3 = b2.checkDCE ? true : false;
        }
      }
      return a3;
    };
    exports$1.isAlreadyRendering = function() {
      return false;
    };
    exports$1.observeVisibleRects = function(a3, b2, c2, d2) {
      if (!bb) throw Error(n2(363));
      a3 = kh(a3, b2);
      var e2 = ib(a3, c2, d2).disconnect;
      return { disconnect: function() {
        e2();
      } };
    };
    exports$1.registerMutableSourceForHydration = function(a3, b2) {
      var c2 = b2._getVersion;
      c2 = c2(b2._source);
      null == a3.mutableSourceEagerHydrationData ? a3.mutableSourceEagerHydrationData = [b2, c2] : a3.mutableSourceEagerHydrationData.push(b2, c2);
    };
    exports$1.runWithPriority = function(a3, b2) {
      var c2 = D2;
      try {
        return D2 = a3, b2();
      } finally {
        D2 = c2;
      }
    };
    exports$1.shouldError = function() {
      return null;
    };
    exports$1.shouldSuspend = function() {
      return false;
    };
    exports$1.updateContainer = function(a3, b2, c2, d2) {
      var e2 = b2.current, f2 = H2(), g2 = zd(e2);
      c2 = $h(c2);
      null === b2.context ? b2.context = c2 : b2.pendingContext = c2;
      b2 = qd(f2, g2);
      b2.payload = { element: a3 };
      d2 = void 0 === d2 ? null : d2;
      null !== d2 && (b2.callback = d2);
      rd(e2, b2);
      a3 = Ad(e2, g2, f2);
      null !== a3 && sd(a3, e2, g2);
      return g2;
    };
    return exports$1;
  };
  return reactReconciler_production_min;
}
var hasRequiredReactReconciler;
function requireReactReconciler() {
  if (hasRequiredReactReconciler) return reactReconciler.exports;
  hasRequiredReactReconciler = 1;
  {
    reactReconciler.exports = requireReactReconciler_production_min();
  }
  return reactReconciler.exports;
}
var reactReconcilerExports = requireReactReconciler();
const Reconciler = /* @__PURE__ */ getDefaultExportFromCjs(reactReconcilerExports);
var schedulerExports = requireScheduler();
const catalogue = {};
const extend = (objects) => void Object.assign(catalogue, objects);
function createRenderer(_roots, _getEventPriority) {
  function createInstance(type, {
    args = [],
    attach: attach2,
    ...props
  }, root) {
    let name = `${type[0].toUpperCase()}${type.slice(1)}`;
    let instance;
    if (type === "primitive") {
      if (props.object === void 0) throw new Error("R3F: Primitives without 'object' are invalid!");
      const object = props.object;
      instance = prepare(object, {
        type,
        root,
        attach: attach2,
        primitive: true
      });
    } else {
      const target = catalogue[name];
      if (!target) {
        throw new Error(`R3F: ${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);
      }
      if (!Array.isArray(args)) throw new Error("R3F: The args prop must be an array!");
      instance = prepare(new target(...args), {
        type,
        root,
        attach: attach2,
        // Save args in case we need to reconstruct later for HMR
        memoizedProps: {
          args
        }
      });
    }
    if (instance.__r3f.attach === void 0) {
      if (instance.isBufferGeometry) instance.__r3f.attach = "geometry";
      else if (instance.isMaterial) instance.__r3f.attach = "material";
    }
    if (name !== "inject") applyProps$1(instance, props);
    return instance;
  }
  function appendChild(parentInstance, child) {
    let added = false;
    if (child) {
      var _child$__r3f, _parentInstance$__r3f;
      if ((_child$__r3f = child.__r3f) != null && _child$__r3f.attach) {
        attach(parentInstance, child, child.__r3f.attach);
      } else if (child.isObject3D && parentInstance.isObject3D) {
        parentInstance.add(child);
        added = true;
      }
      if (!added) (_parentInstance$__r3f = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f.objects.push(child);
      if (!child.__r3f) prepare(child, {});
      child.__r3f.parent = parentInstance;
      updateInstance(child);
      invalidateInstance(child);
    }
  }
  function insertBefore(parentInstance, child, beforeChild) {
    let added = false;
    if (child) {
      var _child$__r3f2, _parentInstance$__r3f2;
      if ((_child$__r3f2 = child.__r3f) != null && _child$__r3f2.attach) {
        attach(parentInstance, child, child.__r3f.attach);
      } else if (child.isObject3D && parentInstance.isObject3D) {
        child.parent = parentInstance;
        child.dispatchEvent({
          type: "added"
        });
        parentInstance.dispatchEvent({
          type: "childadded",
          child
        });
        const restSiblings = parentInstance.children.filter((sibling) => sibling !== child);
        const index = restSiblings.indexOf(beforeChild);
        parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)];
        added = true;
      }
      if (!added) (_parentInstance$__r3f2 = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f2.objects.push(child);
      if (!child.__r3f) prepare(child, {});
      child.__r3f.parent = parentInstance;
      updateInstance(child);
      invalidateInstance(child);
    }
  }
  function removeRecursive(array, parent, dispose2 = false) {
    if (array) [...array].forEach((child) => removeChild(parent, child, dispose2));
  }
  function removeChild(parentInstance, child, dispose2) {
    if (child) {
      var _parentInstance$__r3f3, _child$__r3f3, _child$__r3f5;
      if (child.__r3f) child.__r3f.parent = null;
      if ((_parentInstance$__r3f3 = parentInstance.__r3f) != null && _parentInstance$__r3f3.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter((x) => x !== child);
      if ((_child$__r3f3 = child.__r3f) != null && _child$__r3f3.attach) {
        detach(parentInstance, child, child.__r3f.attach);
      } else if (child.isObject3D && parentInstance.isObject3D) {
        var _child$__r3f4;
        parentInstance.remove(child);
        if ((_child$__r3f4 = child.__r3f) != null && _child$__r3f4.root) {
          removeInteractivity(findInitialRoot(child), child);
        }
      }
      const isPrimitive = (_child$__r3f5 = child.__r3f) == null ? void 0 : _child$__r3f5.primitive;
      const shouldDispose = !isPrimitive && (dispose2 === void 0 ? child.dispose !== null : dispose2);
      if (!isPrimitive) {
        var _child$__r3f6;
        removeRecursive((_child$__r3f6 = child.__r3f) == null ? void 0 : _child$__r3f6.objects, child, shouldDispose);
        removeRecursive(child.children, child, shouldDispose);
      }
      delete child.__r3f;
      if (shouldDispose && child.dispose && child.type !== "Scene") {
        const callback = () => {
          try {
            child.dispose();
          } catch (e2) {
          }
        };
        if (typeof IS_REACT_ACT_ENVIRONMENT === "undefined") {
          schedulerExports.unstable_scheduleCallback(schedulerExports.unstable_IdlePriority, callback);
        } else {
          callback();
        }
      }
      invalidateInstance(parentInstance);
    }
  }
  function switchInstance(instance, type, newProps, fiber) {
    var _instance$__r3f;
    const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent;
    if (!parent) return;
    const newInstance = createInstance(type, newProps, instance.__r3f.root);
    if (instance.children) {
      for (const child of instance.children) {
        if (child.__r3f) appendChild(newInstance, child);
      }
      instance.children = instance.children.filter((child) => !child.__r3f);
    }
    instance.__r3f.objects.forEach((child) => appendChild(newInstance, child));
    instance.__r3f.objects = [];
    if (!instance.__r3f.autoRemovedBeforeAppend) {
      removeChild(parent, instance);
    }
    if (newInstance.parent) {
      newInstance.__r3f.autoRemovedBeforeAppend = true;
    }
    appendChild(parent, newInstance);
    if (newInstance.raycast && newInstance.__r3f.eventCount) {
      const rootState = findInitialRoot(newInstance).getState();
      rootState.internal.interaction.push(newInstance);
    }
    [fiber, fiber.alternate].forEach((fiber2) => {
      if (fiber2 !== null) {
        fiber2.stateNode = newInstance;
        if (fiber2.ref) {
          if (typeof fiber2.ref === "function") fiber2.ref(newInstance);
          else fiber2.ref.current = newInstance;
        }
      }
    });
  }
  const handleTextInstance = () => {
  };
  const reconciler2 = Reconciler({
    createInstance,
    removeChild,
    appendChild,
    appendInitialChild: appendChild,
    insertBefore,
    supportsMutation: true,
    isPrimaryRenderer: false,
    supportsPersistence: false,
    supportsHydration: false,
    noTimeout: -1,
    appendChildToContainer: (container, child) => {
      if (!child) return;
      const scene = container.getState().scene;
      if (!scene.__r3f) return;
      scene.__r3f.root = container;
      appendChild(scene, child);
    },
    removeChildFromContainer: (container, child) => {
      if (!child) return;
      removeChild(container.getState().scene, child);
    },
    insertInContainerBefore: (container, child, beforeChild) => {
      if (!child || !beforeChild) return;
      const scene = container.getState().scene;
      if (!scene.__r3f) return;
      insertBefore(scene, child, beforeChild);
    },
    getRootHostContext: () => null,
    getChildHostContext: (parentHostContext) => parentHostContext,
    finalizeInitialChildren(instance) {
      var _instance$__r3f2;
      const localState = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {};
      return Boolean(localState.handlers);
    },
    prepareUpdate(instance, _type, oldProps, newProps) {
      var _instance$__r3f3;
      const localState = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
      if (localState.primitive && newProps.object && newProps.object !== instance) {
        return [true];
      } else {
        const {
          args: argsNew = [],
          children: cN,
          ...restNew
        } = newProps;
        const {
          args: argsOld = [],
          children: cO,
          ...restOld
        } = oldProps;
        if (!Array.isArray(argsNew)) throw new Error("R3F: the args prop must be an array!");
        if (argsNew.some((value, index) => value !== argsOld[index])) return [true];
        const diff = diffProps(instance, restNew, restOld, true);
        if (diff.changes.length) return [false, diff];
        return null;
      }
    },
    commitUpdate(instance, [reconstruct, diff], type, _oldProps, newProps, fiber) {
      if (reconstruct) switchInstance(instance, type, newProps, fiber);
      else applyProps$1(instance, diff);
    },
    commitMount(instance, _type, _props, _int) {
      var _instance$__r3f4;
      const localState = (_instance$__r3f4 = instance.__r3f) != null ? _instance$__r3f4 : {};
      if (instance.raycast && localState.handlers && localState.eventCount) {
        findInitialRoot(instance).getState().internal.interaction.push(instance);
      }
    },
    getPublicInstance: (instance) => instance,
    prepareForCommit: () => null,
    preparePortalMount: (container) => prepare(container.getState().scene),
    resetAfterCommit: () => {
    },
    shouldSetTextContent: () => false,
    clearContainer: () => false,
    hideInstance(instance) {
      var _instance$__r3f5;
      const {
        attach: type,
        parent
      } = (_instance$__r3f5 = instance.__r3f) != null ? _instance$__r3f5 : {};
      if (type && parent) detach(parent, instance, type);
      if (instance.isObject3D) instance.visible = false;
      invalidateInstance(instance);
    },
    unhideInstance(instance, props) {
      var _instance$__r3f6;
      const {
        attach: type,
        parent
      } = (_instance$__r3f6 = instance.__r3f) != null ? _instance$__r3f6 : {};
      if (type && parent) attach(parent, instance, type);
      if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true;
      invalidateInstance(instance);
    },
    createTextInstance: handleTextInstance,
    hideTextInstance: handleTextInstance,
    unhideTextInstance: handleTextInstance,
    // https://github.com/pmndrs/react-three-fiber/pull/2360#discussion_r916356874
    // @ts-expect-error
    getCurrentEventPriority: () => _getEventPriority ? _getEventPriority() : constantsExports.DefaultEventPriority,
    beforeActiveInstanceBlur: () => {
    },
    afterActiveInstanceBlur: () => {
    },
    detachDeletedInstance: () => {
    },
    now: typeof performance !== "undefined" && is.fun(performance.now) ? performance.now : is.fun(Date.now) ? Date.now : () => 0,
    // https://github.com/pmndrs/react-three-fiber/pull/2360#discussion_r920883503
    scheduleTimeout: is.fun(setTimeout) ? setTimeout : void 0,
    cancelTimeout: is.fun(clearTimeout) ? clearTimeout : void 0
  });
  return {
    reconciler: reconciler2,
    applyProps: applyProps$1
  };
}
var _window$document, _window$navigator;
const hasColorSpace$1 = (object) => "colorSpace" in object || "outputColorSpace" in object;
const getColorManagement = () => {
  var _ColorManagement;
  return (_ColorManagement = catalogue.ColorManagement) != null ? _ColorManagement : null;
};
const isOrthographicCamera = (def) => def && def.isOrthographicCamera;
const isRef$1 = (obj) => obj && obj.hasOwnProperty("current");
const useIsomorphicLayoutEffect = typeof window !== "undefined" && ((_window$document = window.document) != null && _window$document.createElement || ((_window$navigator = window.navigator) == null ? void 0 : _window$navigator.product) === "ReactNative") ? reactExports.useLayoutEffect : reactExports.useEffect;
function useMutableCallback(fn2) {
  const ref = reactExports.useRef(fn2);
  useIsomorphicLayoutEffect(() => void (ref.current = fn2), [fn2]);
  return ref;
}
function Block({
  set
}) {
  useIsomorphicLayoutEffect(() => {
    set(new Promise(() => null));
    return () => set(false);
  }, [set]);
  return null;
}
class ErrorBoundary extends reactExports.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      error: false
    };
  }
  componentDidCatch(err) {
    this.props.set(err);
  }
  render() {
    return this.state.error ? null : this.props.children;
  }
}
ErrorBoundary.getDerivedStateFromError = () => ({
  error: true
});
const DEFAULT = "__default";
const DEFAULTS = /* @__PURE__ */ new Map();
const isDiffSet = (def) => def && !!def.memoized && !!def.changes;
function calculateDpr(dpr) {
  var _window$devicePixelRa;
  const target = typeof window !== "undefined" ? (_window$devicePixelRa = window.devicePixelRatio) != null ? _window$devicePixelRa : 2 : 1;
  return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr;
}
const getRootState = (obj) => {
  var _r3f;
  return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState();
};
function findInitialRoot(child) {
  let root = child.__r3f.root;
  while (root.getState().previousRoot) root = root.getState().previousRoot;
  return root;
}
const is = {
  obj: (a3) => a3 === Object(a3) && !is.arr(a3) && typeof a3 !== "function",
  fun: (a3) => typeof a3 === "function",
  str: (a3) => typeof a3 === "string",
  num: (a3) => typeof a3 === "number",
  boo: (a3) => typeof a3 === "boolean",
  und: (a3) => a3 === void 0,
  arr: (a3) => Array.isArray(a3),
  equ(a3, b2, {
    arrays = "shallow",
    objects = "reference",
    strict = true
  } = {}) {
    if (typeof a3 !== typeof b2 || !!a3 !== !!b2) return false;
    if (is.str(a3) || is.num(a3) || is.boo(a3)) return a3 === b2;
    const isObj = is.obj(a3);
    if (isObj && objects === "reference") return a3 === b2;
    const isArr = is.arr(a3);
    if (isArr && arrays === "reference") return a3 === b2;
    if ((isArr || isObj) && a3 === b2) return true;
    let i2;
    for (i2 in a3) if (!(i2 in b2)) return false;
    if (isObj && arrays === "shallow" && objects === "shallow") {
      for (i2 in strict ? b2 : a3) if (!is.equ(a3[i2], b2[i2], {
        strict,
        objects: "reference"
      })) return false;
    } else {
      for (i2 in strict ? b2 : a3) if (a3[i2] !== b2[i2]) return false;
    }
    if (is.und(i2)) {
      if (isArr && a3.length === 0 && b2.length === 0) return true;
      if (isObj && Object.keys(a3).length === 0 && Object.keys(b2).length === 0) return true;
      if (a3 !== b2) return false;
    }
    return true;
  }
};
function buildGraph(object) {
  const data = {
    nodes: {},
    materials: {}
  };
  if (object) {
    object.traverse((obj) => {
      if (obj.name) data.nodes[obj.name] = obj;
      if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
    });
  }
  return data;
}
function dispose(obj) {
  if (obj.dispose && obj.type !== "Scene") obj.dispose();
  for (const p2 in obj) {
    p2.dispose == null ? void 0 : p2.dispose();
    delete obj[p2];
  }
}
function prepare(object, state) {
  const instance = object;
  instance.__r3f = {
    type: "",
    root: null,
    previousAttach: null,
    memoizedProps: {},
    eventCount: 0,
    handlers: {},
    objects: [],
    parent: null,
    ...state
  };
  return object;
}
function resolve(instance, key) {
  let target = instance;
  if (key.includes("-")) {
    const entries = key.split("-");
    const last = entries.pop();
    target = entries.reduce((acc, key2) => acc[key2], instance);
    return {
      target,
      key: last
    };
  } else return {
    target,
    key
  };
}
const INDEX_REGEX = /-\d+$/;
function attach(parent, child, type) {
  if (is.str(type)) {
    if (INDEX_REGEX.test(type)) {
      const root = type.replace(INDEX_REGEX, "");
      const {
        target: target2,
        key: key2
      } = resolve(parent, root);
      if (!Array.isArray(target2[key2])) target2[key2] = [];
    }
    const {
      target,
      key
    } = resolve(parent, type);
    child.__r3f.previousAttach = target[key];
    target[key] = child;
  } else child.__r3f.previousAttach = type(parent, child);
}
function detach(parent, child, type) {
  var _child$__r3f, _child$__r3f2;
  if (is.str(type)) {
    const {
      target,
      key
    } = resolve(parent, type);
    const previous = child.__r3f.previousAttach;
    if (previous === void 0) delete target[key];
    else target[key] = previous;
  } else (_child$__r3f = child.__r3f) == null ? void 0 : _child$__r3f.previousAttach == null ? void 0 : _child$__r3f.previousAttach(parent, child);
  (_child$__r3f2 = child.__r3f) == null ? true : delete _child$__r3f2.previousAttach;
}
function diffProps(instance, {
  children: cN,
  key: kN,
  ref: rN,
  ...props
}, {
  children: cP,
  key: kP,
  ref: rP,
  ...previous
} = {}, remove = false) {
  const localState = instance.__r3f;
  const entries = Object.entries(props);
  const changes = [];
  if (remove) {
    const previousKeys = Object.keys(previous);
    for (let i2 = 0; i2 < previousKeys.length; i2++) {
      if (!props.hasOwnProperty(previousKeys[i2])) entries.unshift([previousKeys[i2], DEFAULT + "remove"]);
    }
  }
  entries.forEach(([key, value]) => {
    var _instance$__r3f;
    if ((_instance$__r3f = instance.__r3f) != null && _instance$__r3f.primitive && key === "object") return;
    if (is.equ(value, previous[key])) return;
    if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]);
    let entries2 = [];
    if (key.includes("-")) entries2 = key.split("-");
    changes.push([key, value, false, entries2]);
    for (const prop in props) {
      const value2 = props[prop];
      if (prop.startsWith(`${key}-`)) changes.push([prop, value2, false, prop.split("-")]);
    }
  });
  const memoized = {
    ...props
  };
  if (localState != null && localState.memoizedProps && localState != null && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args;
  if (localState != null && localState.memoizedProps && localState != null && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach;
  return {
    memoized,
    changes
  };
}
function applyProps$1(instance, data) {
  var _instance$__r3f2;
  const localState = instance.__r3f;
  const root = localState == null ? void 0 : localState.root;
  const rootState = root == null ? void 0 : root.getState == null ? void 0 : root.getState();
  const {
    memoized,
    changes
  } = isDiffSet(data) ? data : diffProps(instance, data);
  const prevHandlers = localState == null ? void 0 : localState.eventCount;
  if (instance.__r3f) instance.__r3f.memoizedProps = memoized;
  for (let i2 = 0; i2 < changes.length; i2++) {
    let [key, value, isEvent, keys] = changes[i2];
    if (hasColorSpace$1(instance)) {
      const sRGBEncoding2 = 3001;
      const SRGBColorSpace2 = "srgb";
      const LinearSRGBColorSpace2 = "srgb-linear";
      if (key === "encoding") {
        key = "colorSpace";
        value = value === sRGBEncoding2 ? SRGBColorSpace2 : LinearSRGBColorSpace2;
      } else if (key === "outputEncoding") {
        key = "outputColorSpace";
        value = value === sRGBEncoding2 ? SRGBColorSpace2 : LinearSRGBColorSpace2;
      }
    }
    let currentInstance = instance;
    let targetProp = currentInstance[key];
    if (keys.length) {
      targetProp = keys.reduce((acc, key2) => acc[key2], instance);
      if (!(targetProp && targetProp.set)) {
        const [name, ...reverseEntries] = keys.reverse();
        currentInstance = reverseEntries.reverse().reduce((acc, key2) => acc[key2], instance);
        key = name;
      }
    }
    if (value === DEFAULT + "remove") {
      if (currentInstance.constructor) {
        let ctor = DEFAULTS.get(currentInstance.constructor);
        if (!ctor) {
          ctor = new currentInstance.constructor();
          DEFAULTS.set(currentInstance.constructor, ctor);
        }
        value = ctor[key];
      } else {
        value = 0;
      }
    }
    if (isEvent && localState) {
      if (value) localState.handlers[key] = value;
      else delete localState.handlers[key];
      localState.eventCount = Object.keys(localState.handlers).length;
    } else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof Layers)) {
      if (Array.isArray(value)) {
        if (targetProp.fromArray) targetProp.fromArray(value);
        else targetProp.set(...value);
      } else if (targetProp.copy && value && value.constructor && // Some environments may break strict identity checks by duplicating versions of three.js.
      // Loosen to unminified names, ignoring descendents.
      // https://github.com/pmndrs/react-three-fiber/issues/2856
      // TODO: fix upstream and remove in v9
      targetProp.constructor === value.constructor) {
        targetProp.copy(value);
      } else if (value !== void 0) {
        var _targetProp;
        const isColor = (_targetProp = targetProp) == null ? void 0 : _targetProp.isColor;
        if (!isColor && targetProp.setScalar) targetProp.setScalar(value);
        else if (targetProp instanceof Layers && value instanceof Layers) targetProp.mask = value.mask;
        else targetProp.set(value);
        if (!getColorManagement() && rootState && !rootState.linear && isColor) targetProp.convertSRGBToLinear();
      }
    } else {
      var _currentInstance$key;
      currentInstance[key] = value;
      if ((_currentInstance$key = currentInstance[key]) != null && _currentInstance$key.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
      currentInstance[key].format === RGBAFormat && currentInstance[key].type === UnsignedByteType && rootState) {
        const texture = currentInstance[key];
        if (hasColorSpace$1(texture) && hasColorSpace$1(rootState.gl)) texture.colorSpace = rootState.gl.outputColorSpace;
        else texture.encoding = rootState.gl.outputEncoding;
      }
    }
    invalidateInstance(instance);
  }
  if (localState && localState.parent && instance.raycast && prevHandlers !== localState.eventCount) {
    const internal = findInitialRoot(instance).getState().internal;
    const index = internal.interaction.indexOf(instance);
    if (index > -1) internal.interaction.splice(index, 1);
    if (localState.eventCount) internal.interaction.push(instance);
  }
  const isCircular = changes.length === 1 && changes[0][0] === "onUpdate";
  if (!isCircular && changes.length && (_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.parent) updateInstance(instance);
  return instance;
}
function invalidateInstance(instance) {
  var _instance$__r3f3, _instance$__r3f3$root;
  const state = (_instance$__r3f3 = instance.__r3f) == null ? void 0 : (_instance$__r3f3$root = _instance$__r3f3.root) == null ? void 0 : _instance$__r3f3$root.getState == null ? void 0 : _instance$__r3f3$root.getState();
  if (state && state.internal.frames === 0) state.invalidate();
}
function updateInstance(instance) {
  instance.onUpdate == null ? void 0 : instance.onUpdate(instance);
}
function updateCamera(camera, size) {
  if (!camera.manual) {
    if (isOrthographicCamera(camera)) {
      camera.left = size.width / -2;
      camera.right = size.width / 2;
      camera.top = size.height / 2;
      camera.bottom = size.height / -2;
    } else {
      camera.aspect = size.width / size.height;
    }
    camera.updateProjectionMatrix();
    camera.updateMatrixWorld();
  }
}
function makeId(event) {
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
}
function getEventPriority() {
  var _globalScope$event;
  const globalScope = typeof self !== "undefined" && self || typeof window !== "undefined" && window;
  if (!globalScope) return constantsExports.DefaultEventPriority;
  const name = (_globalScope$event = globalScope.event) == null ? void 0 : _globalScope$event.type;
  switch (name) {
    case "click":
    case "contextmenu":
    case "dblclick":
    case "pointercancel":
    case "pointerdown":
    case "pointerup":
      return constantsExports.DiscreteEventPriority;
    case "pointermove":
    case "pointerout":
    case "pointerover":
    case "pointerenter":
    case "pointerleave":
    case "wheel":
      return constantsExports.ContinuousEventPriority;
    default:
      return constantsExports.DefaultEventPriority;
  }
}
function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
  const captureData = captures.get(obj);
  if (captureData) {
    captures.delete(obj);
    if (captures.size === 0) {
      capturedMap.delete(pointerId);
      captureData.target.releasePointerCapture(pointerId);
    }
  }
}
function removeInteractivity(store, object) {
  const {
    internal
  } = store.getState();
  internal.interaction = internal.interaction.filter((o4) => o4 !== object);
  internal.initialHits = internal.initialHits.filter((o4) => o4 !== object);
  internal.hovered.forEach((value, key) => {
    if (value.eventObject === object || value.object === object) {
      internal.hovered.delete(key);
    }
  });
  internal.capturedMap.forEach((captures, pointerId) => {
    releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
  });
}
function createEvents(store) {
  function calculateDistance(event) {
    const {
      internal
    } = store.getState();
    const dx = event.offsetX - internal.initialClick[0];
    const dy = event.offsetY - internal.initialClick[1];
    return Math.round(Math.sqrt(dx * dx + dy * dy));
  }
  function filterPointerEvents(objects) {
    return objects.filter((obj) => ["Move", "Over", "Enter", "Out", "Leave"].some((name) => {
      var _r3f;
      return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers["onPointer" + name];
    }));
  }
  function intersect2(event, filter) {
    const state = store.getState();
    const duplicates = /* @__PURE__ */ new Set();
    const intersections = [];
    const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction;
    for (let i2 = 0; i2 < eventsObjects.length; i2++) {
      const state2 = getRootState(eventsObjects[i2]);
      if (state2) {
        state2.raycaster.camera = void 0;
      }
    }
    if (!state.previousRoot) {
      state.events.compute == null ? void 0 : state.events.compute(event, state);
    }
    function handleRaycast(obj) {
      const state2 = getRootState(obj);
      if (!state2 || !state2.events.enabled || state2.raycaster.camera === null) return [];
      if (state2.raycaster.camera === void 0) {
        var _state$previousRoot;
        state2.events.compute == null ? void 0 : state2.events.compute(event, state2, (_state$previousRoot = state2.previousRoot) == null ? void 0 : _state$previousRoot.getState());
        if (state2.raycaster.camera === void 0) state2.raycaster.camera = null;
      }
      return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
    }
    let hits = eventsObjects.flatMap(handleRaycast).sort((a3, b2) => {
      const aState = getRootState(a3.object);
      const bState = getRootState(b2.object);
      if (!aState || !bState) return a3.distance - b2.distance;
      return bState.events.priority - aState.events.priority || a3.distance - b2.distance;
    }).filter((item) => {
      const id = makeId(item);
      if (duplicates.has(id)) return false;
      duplicates.add(id);
      return true;
    });
    if (state.events.filter) hits = state.events.filter(hits, state);
    for (const hit of hits) {
      let eventObject = hit.object;
      while (eventObject) {
        var _r3f2;
        if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({
          ...hit,
          eventObject
        });
        eventObject = eventObject.parent;
      }
    }
    if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
      for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) {
        if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
      }
    }
    return intersections;
  }
  function handleIntersects(intersections, event, delta, callback) {
    const rootState = store.getState();
    if (intersections.length) {
      const localState = {
        stopped: false
      };
      for (const hit of intersections) {
        const state = getRootState(hit.object) || rootState;
        const {
          raycaster,
          pointer,
          camera,
          internal
        } = state;
        const unprojectedPoint = new Vector3(pointer.x, pointer.y, 0).unproject(camera);
        const hasPointerCapture = (id) => {
          var _internal$capturedMap, _internal$capturedMap2;
          return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
        };
        const setPointerCapture = (id) => {
          const captureData = {
            intersection: hit,
            target: event.target
          };
          if (internal.capturedMap.has(id)) {
            internal.capturedMap.get(id).set(hit.eventObject, captureData);
          } else {
            internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
          }
          event.target.setPointerCapture(id);
        };
        const releasePointerCapture = (id) => {
          const captures = internal.capturedMap.get(id);
          if (captures) {
            releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
          }
        };
        let extractEventProps = {};
        for (let prop in event) {
          let property = event[prop];
          if (typeof property !== "function") extractEventProps[prop] = property;
        }
        let raycastEvent = {
          ...hit,
          ...extractEventProps,
          pointer,
          intersections,
          stopped: localState.stopped,
          delta,
          unprojectedPoint,
          ray: raycaster.ray,
          camera,
          // Hijack stopPropagation, which just sets a flag
          stopPropagation() {
            const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
            if (
              // ...if this pointer hasn't been captured
              !capturesForPointer || // ... or if the hit object is capturing the pointer
              capturesForPointer.has(hit.eventObject)
            ) {
              raycastEvent.stopped = localState.stopped = true;
              if (internal.hovered.size && Array.from(internal.hovered.values()).find((i2) => i2.eventObject === hit.eventObject)) {
                const higher = intersections.slice(0, intersections.indexOf(hit));
                cancelPointer([...higher, hit]);
              }
            }
          },
          // there should be a distinction between target and currentTarget
          target: {
            hasPointerCapture,
            setPointerCapture,
            releasePointerCapture
          },
          currentTarget: {
            hasPointerCapture,
            setPointerCapture,
            releasePointerCapture
          },
          nativeEvent: event
        };
        callback(raycastEvent);
        if (localState.stopped === true) break;
      }
    }
    return intersections;
  }
  function cancelPointer(intersections) {
    const {
      internal
    } = store.getState();
    for (const hoveredObj of internal.hovered.values()) {
      if (!intersections.length || !intersections.find((hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
        const eventObject = hoveredObj.eventObject;
        const instance = eventObject.__r3f;
        const handlers = instance == null ? void 0 : instance.handlers;
        internal.hovered.delete(makeId(hoveredObj));
        if (instance != null && instance.eventCount) {
          const data = {
            ...hoveredObj,
            intersections
          };
          handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
          handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
        }
      }
    }
  }
  function pointerMissed(event, objects) {
    for (let i2 = 0; i2 < objects.length; i2++) {
      const instance = objects[i2].__r3f;
      instance == null ? void 0 : instance.handlers.onPointerMissed == null ? void 0 : instance.handlers.onPointerMissed(event);
    }
  }
  function handlePointer(name) {
    switch (name) {
      case "onPointerLeave":
      case "onPointerCancel":
        return () => cancelPointer([]);
      case "onLostPointerCapture":
        return (event) => {
          const {
            internal
          } = store.getState();
          if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
            requestAnimationFrame(() => {
              if (internal.capturedMap.has(event.pointerId)) {
                internal.capturedMap.delete(event.pointerId);
                cancelPointer([]);
              }
            });
          }
        };
    }
    return function handleEvent(event) {
      const {
        onPointerMissed,
        internal
      } = store.getState();
      internal.lastEvent.current = event;
      const isPointerMove = name === "onPointerMove";
      const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
      const filter = isPointerMove ? filterPointerEvents : void 0;
      const hits = intersect2(event, filter);
      const delta = isClickEvent ? calculateDistance(event) : 0;
      if (name === "onPointerDown") {
        internal.initialClick = [event.offsetX, event.offsetY];
        internal.initialHits = hits.map((hit) => hit.eventObject);
      }
      if (isClickEvent && !hits.length) {
        if (delta <= 2) {
          pointerMissed(event, internal.interaction);
          if (onPointerMissed) onPointerMissed(event);
        }
      }
      if (isPointerMove) cancelPointer(hits);
      function onIntersect(data) {
        const eventObject = data.eventObject;
        const instance = eventObject.__r3f;
        const handlers = instance == null ? void 0 : instance.handlers;
        if (!(instance != null && instance.eventCount)) return;
        if (isPointerMove) {
          if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
            const id = makeId(data);
            const hoveredItem = internal.hovered.get(id);
            if (!hoveredItem) {
              internal.hovered.set(id, data);
              handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
              handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
            } else if (hoveredItem.stopped) {
              data.stopPropagation();
            }
          }
          handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
        } else {
          const handler = handlers[name];
          if (handler) {
            if (!isClickEvent || internal.initialHits.includes(eventObject)) {
              pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
              handler(data);
            }
          } else {
            if (isClickEvent && internal.initialHits.includes(eventObject)) {
              pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
            }
          }
        }
      }
      handleIntersects(hits, event, delta, onIntersect);
    };
  }
  return {
    handlePointer
  };
}
const privateKeys = ["set", "get", "setSize", "setFrameloop", "setDpr", "events", "invalidate", "advance", "size", "viewport"];
const isRenderer = (def) => !!(def != null && def.render);
const context$1 = /* @__PURE__ */ reactExports.createContext(null);
const createStore = (invalidate2, advance2) => {
  const rootState = create$1((set, get) => {
    const position = new Vector3();
    const defaultTarget = new Vector3();
    const tempTarget = new Vector3();
    function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
      const {
        width,
        height,
        top,
        left
      } = size;
      const aspect2 = width / height;
      if (target.isVector3) tempTarget.copy(target);
      else tempTarget.set(...target);
      const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
      if (isOrthographicCamera(camera)) {
        return {
          width: width / camera.zoom,
          height: height / camera.zoom,
          top,
          left,
          factor: 1,
          distance,
          aspect: aspect2
        };
      } else {
        const fov2 = camera.fov * Math.PI / 180;
        const h2 = 2 * Math.tan(fov2 / 2) * distance;
        const w2 = h2 * (width / height);
        return {
          width: w2,
          height: h2,
          top,
          left,
          factor: width / w2,
          distance,
          aspect: aspect2
        };
      }
    }
    let performanceTimeout = void 0;
    const setPerformanceCurrent = (current) => set((state2) => ({
      performance: {
        ...state2.performance,
        current
      }
    }));
    const pointer = new Vector2();
    const rootState2 = {
      set,
      get,
      // Mock objects that have to be configured
      gl: null,
      camera: null,
      raycaster: null,
      events: {
        priority: 1,
        enabled: true,
        connected: false
      },
      xr: null,
      scene: null,
      invalidate: (frames = 1) => invalidate2(get(), frames),
      advance: (timestamp, runGlobalEffects) => advance2(timestamp, runGlobalEffects, get()),
      legacy: false,
      linear: false,
      flat: false,
      controls: null,
      clock: new Clock(),
      pointer,
      mouse: pointer,
      frameloop: "always",
      onPointerMissed: void 0,
      performance: {
        current: 1,
        min: 0.5,
        max: 1,
        debounce: 200,
        regress: () => {
          const state2 = get();
          if (performanceTimeout) clearTimeout(performanceTimeout);
          if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
          performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state2.performance.debounce);
        }
      },
      size: {
        width: 0,
        height: 0,
        top: 0,
        left: 0,
        updateStyle: false
      },
      viewport: {
        initialDpr: 0,
        dpr: 0,
        width: 0,
        height: 0,
        top: 0,
        left: 0,
        aspect: 0,
        distance: 0,
        factor: 0,
        getCurrentViewport
      },
      setEvents: (events) => set((state2) => ({
        ...state2,
        events: {
          ...state2.events,
          ...events
        }
      })),
      setSize: (width, height, updateStyle, top, left) => {
        const camera = get().camera;
        const size = {
          width,
          height,
          top: top || 0,
          left: left || 0,
          updateStyle
        };
        set((state2) => ({
          size,
          viewport: {
            ...state2.viewport,
            ...getCurrentViewport(camera, defaultTarget, size)
          }
        }));
      },
      setDpr: (dpr) => set((state2) => {
        const resolved = calculateDpr(dpr);
        return {
          viewport: {
            ...state2.viewport,
            dpr: resolved,
            initialDpr: state2.viewport.initialDpr || resolved
          }
        };
      }),
      setFrameloop: (frameloop = "always") => {
        const clock = get().clock;
        clock.stop();
        clock.elapsedTime = 0;
        if (frameloop !== "never") {
          clock.start();
          clock.elapsedTime = 0;
        }
        set(() => ({
          frameloop
        }));
      },
      previousRoot: void 0,
      internal: {
        active: false,
        priority: 0,
        frames: 0,
        lastEvent: /* @__PURE__ */ reactExports.createRef(),
        interaction: [],
        hovered: /* @__PURE__ */ new Map(),
        subscribers: [],
        initialClick: [0, 0],
        initialHits: [],
        capturedMap: /* @__PURE__ */ new Map(),
        subscribe: (ref, priority, store) => {
          const internal = get().internal;
          internal.priority = internal.priority + (priority > 0 ? 1 : 0);
          internal.subscribers.push({
            ref,
            priority,
            store
          });
          internal.subscribers = internal.subscribers.sort((a3, b2) => a3.priority - b2.priority);
          return () => {
            const internal2 = get().internal;
            if (internal2 != null && internal2.subscribers) {
              internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
              internal2.subscribers = internal2.subscribers.filter((s2) => s2.ref !== ref);
            }
          };
        }
      }
    };
    return rootState2;
  });
  const state = rootState.getState();
  let oldSize = state.size;
  let oldDpr = state.viewport.dpr;
  let oldCamera = state.camera;
  rootState.subscribe(() => {
    const {
      camera,
      size,
      viewport,
      gl,
      set
    } = rootState.getState();
    if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
      var _size$updateStyle;
      oldSize = size;
      oldDpr = viewport.dpr;
      updateCamera(camera, size);
      gl.setPixelRatio(viewport.dpr);
      const updateStyle = (_size$updateStyle = size.updateStyle) != null ? _size$updateStyle : typeof HTMLCanvasElement !== "undefined" && gl.domElement instanceof HTMLCanvasElement;
      gl.setSize(size.width, size.height, updateStyle);
    }
    if (camera !== oldCamera) {
      oldCamera = camera;
      set((state2) => ({
        viewport: {
          ...state2.viewport,
          ...state2.viewport.getCurrentViewport(camera)
        }
      }));
    }
  });
  rootState.subscribe((state2) => invalidate2(state2));
  return rootState;
};
let i$2;
let globalEffects = /* @__PURE__ */ new Set();
let globalAfterEffects = /* @__PURE__ */ new Set();
let globalTailEffects = /* @__PURE__ */ new Set();
function run(effects, timestamp) {
  if (!effects.size) return;
  for (const {
    callback
  } of effects.values()) {
    callback(timestamp);
  }
}
function flushGlobalEffects(type, timestamp) {
  switch (type) {
    case "before":
      return run(globalEffects, timestamp);
    case "after":
      return run(globalAfterEffects, timestamp);
    case "tail":
      return run(globalTailEffects, timestamp);
  }
}
let subscribers;
let subscription;
function render$1(timestamp, state, frame) {
  let delta = state.clock.getDelta();
  if (state.frameloop === "never" && typeof timestamp === "number") {
    delta = timestamp - state.clock.elapsedTime;
    state.clock.oldTime = state.clock.elapsedTime;
    state.clock.elapsedTime = timestamp;
  }
  subscribers = state.internal.subscribers;
  for (i$2 = 0; i$2 < subscribers.length; i$2++) {
    subscription = subscribers[i$2];
    subscription.ref.current(subscription.store.getState(), delta, frame);
  }
  if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera);
  state.internal.frames = Math.max(0, state.internal.frames - 1);
  return state.frameloop === "always" ? 1 : state.internal.frames;
}
function createLoop(roots2) {
  let running = false;
  let useFrameInProgress = false;
  let repeat;
  let frame;
  let state;
  function loop(timestamp) {
    frame = requestAnimationFrame(loop);
    running = true;
    repeat = 0;
    flushGlobalEffects("before", timestamp);
    useFrameInProgress = true;
    for (const root of roots2.values()) {
      var _state$gl$xr;
      state = root.store.getState();
      if (state.internal.active && (state.frameloop === "always" || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) {
        repeat += render$1(timestamp, state);
      }
    }
    useFrameInProgress = false;
    flushGlobalEffects("after", timestamp);
    if (repeat === 0) {
      flushGlobalEffects("tail", timestamp);
      running = false;
      return cancelAnimationFrame(frame);
    }
  }
  function invalidate2(state2, frames = 1) {
    var _state$gl$xr2;
    if (!state2) return roots2.forEach((root) => invalidate2(root.store.getState(), frames));
    if ((_state$gl$xr2 = state2.gl.xr) != null && _state$gl$xr2.isPresenting || !state2.internal.active || state2.frameloop === "never") return;
    if (frames > 1) {
      state2.internal.frames = Math.min(60, state2.internal.frames + frames);
    } else {
      if (useFrameInProgress) {
        state2.internal.frames = 2;
      } else {
        state2.internal.frames = 1;
      }
    }
    if (!running) {
      running = true;
      requestAnimationFrame(loop);
    }
  }
  function advance2(timestamp, runGlobalEffects = true, state2, frame2) {
    if (runGlobalEffects) flushGlobalEffects("before", timestamp);
    if (!state2) for (const root of roots2.values()) render$1(timestamp, root.store.getState());
    else render$1(timestamp, state2, frame2);
    if (runGlobalEffects) flushGlobalEffects("after", timestamp);
  }
  return {
    loop,
    invalidate: invalidate2,
    advance: advance2
  };
}
function useStore() {
  const store = reactExports.useContext(context$1);
  if (!store) throw new Error("R3F: Hooks can only be used within the Canvas component!");
  return store;
}
function useThree(selector = (state) => state, equalityFn) {
  return useStore()(selector, equalityFn);
}
function useFrame(callback, renderPriority = 0) {
  const store = useStore();
  const subscribe = store.getState().internal.subscribe;
  const ref = useMutableCallback(callback);
  useIsomorphicLayoutEffect(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]);
  return null;
}
const memoizedLoaders = /* @__PURE__ */ new WeakMap();
function loadingFn(extensions, onProgress) {
  return function(Proto, ...input) {
    let loader2 = memoizedLoaders.get(Proto);
    if (!loader2) {
      loader2 = new Proto();
      memoizedLoaders.set(Proto, loader2);
    }
    if (extensions) extensions(loader2);
    return Promise.all(input.map((input2) => new Promise((res, reject) => loader2.load(input2, (data) => {
      if (data.scene) Object.assign(data, buildGraph(data.scene));
      res(data);
    }, onProgress, (error2) => reject(new Error(`Could not load ${input2}: ${error2 == null ? void 0 : error2.message}`))))));
  };
}
function useLoader(Proto, input, extensions, onProgress) {
  const keys = Array.isArray(input) ? input : [input];
  const results = suspend(loadingFn(extensions, onProgress), [Proto, ...keys], {
    equal: is.equ
  });
  return Array.isArray(input) ? results : results[0];
}
useLoader.preload = function(Proto, input, extensions) {
  const keys = Array.isArray(input) ? input : [input];
  return preload(loadingFn(extensions), [Proto, ...keys]);
};
useLoader.clear = function(Proto, input) {
  const keys = Array.isArray(input) ? input : [input];
  return clear([Proto, ...keys]);
};
const roots = /* @__PURE__ */ new Map();
const {
  invalidate,
  advance
} = createLoop(roots);
const {
  reconciler,
  applyProps
} = createRenderer(roots, getEventPriority);
const shallowLoose = {
  objects: "shallow",
  strict: false
};
const createRendererInstance = (gl, canvas) => {
  const customRenderer = typeof gl === "function" ? gl(canvas) : gl;
  if (isRenderer(customRenderer)) return customRenderer;
  else return new WebGLRenderer({
    powerPreference: "high-performance",
    canvas,
    antialias: true,
    alpha: true,
    ...gl
  });
};
function computeInitialSize(canvas, defaultSize) {
  const defaultStyle = typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement;
  if (defaultSize) {
    const {
      width,
      height,
      top,
      left,
      updateStyle = defaultStyle
    } = defaultSize;
    return {
      width,
      height,
      top,
      left,
      updateStyle
    };
  } else if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement && canvas.parentElement) {
    const {
      width,
      height,
      top,
      left
    } = canvas.parentElement.getBoundingClientRect();
    return {
      width,
      height,
      top,
      left,
      updateStyle: defaultStyle
    };
  } else if (typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas) {
    return {
      width: canvas.width,
      height: canvas.height,
      top: 0,
      left: 0,
      updateStyle: defaultStyle
    };
  }
  return {
    width: 0,
    height: 0,
    top: 0,
    left: 0
  };
}
function createRoot(canvas) {
  const prevRoot = roots.get(canvas);
  const prevFiber = prevRoot == null ? void 0 : prevRoot.fiber;
  const prevStore = prevRoot == null ? void 0 : prevRoot.store;
  if (prevRoot) console.warn("R3F.createRoot should only be called once!");
  const logRecoverableError = typeof reportError === "function" ? (
    // In modern browsers, reportError will dispatch an error event,
    // emulating an uncaught JavaScript error.
    reportError
  ) : (
    // In older browsers and test environments, fallback to console.error.
    console.error
  );
  const store = prevStore || createStore(invalidate, advance);
  const fiber = prevFiber || reconciler.createContainer(store, constantsExports.ConcurrentRoot, null, false, null, "", logRecoverableError, null);
  if (!prevRoot) roots.set(canvas, {
    fiber,
    store
  });
  let onCreated;
  let configured = false;
  let lastCamera;
  return {
    configure(props = {}) {
      let {
        gl: glConfig,
        size: propsSize,
        scene: sceneOptions,
        events,
        onCreated: onCreatedCallback,
        shadows = false,
        linear = false,
        flat = false,
        legacy = false,
        orthographic = false,
        frameloop = "always",
        dpr = [1, 2],
        performance: performance2,
        raycaster: raycastOptions,
        camera: cameraOptions,
        onPointerMissed
      } = props;
      let state = store.getState();
      let gl = state.gl;
      if (!state.gl) state.set({
        gl: gl = createRendererInstance(glConfig, canvas)
      });
      let raycaster = state.raycaster;
      if (!raycaster) state.set({
        raycaster: raycaster = new Raycaster()
      });
      const {
        params,
        ...options
      } = raycastOptions || {};
      if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster, {
        ...options
      });
      if (!is.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, {
        params: {
          ...raycaster.params,
          ...params
        }
      });
      if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
        lastCamera = cameraOptions;
        const isCamera = cameraOptions instanceof Camera;
        const camera = isCamera ? cameraOptions : orthographic ? new OrthographicCamera(0, 0, 0, 0, 0.1, 1e3) : new PerspectiveCamera(75, 0, 0.1, 1e3);
        if (!isCamera) {
          camera.position.z = 5;
          if (cameraOptions) {
            applyProps(camera, cameraOptions);
            if ("aspect" in cameraOptions || "left" in cameraOptions || "right" in cameraOptions || "bottom" in cameraOptions || "top" in cameraOptions) {
              camera.manual = true;
              camera.updateProjectionMatrix();
            }
          }
          if (!state.camera && !(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
        }
        state.set({
          camera
        });
        raycaster.camera = camera;
      }
      if (!state.scene) {
        let scene;
        if (sceneOptions != null && sceneOptions.isScene) {
          scene = sceneOptions;
        } else {
          scene = new Scene();
          if (sceneOptions) applyProps(scene, sceneOptions);
        }
        state.set({
          scene: prepare(scene)
        });
      }
      if (!state.xr) {
        var _gl$xr;
        const handleXRFrame = (timestamp, frame) => {
          const state2 = store.getState();
          if (state2.frameloop === "never") return;
          advance(timestamp, true, state2, frame);
        };
        const handleSessionChange = () => {
          const state2 = store.getState();
          state2.gl.xr.enabled = state2.gl.xr.isPresenting;
          state2.gl.xr.setAnimationLoop(state2.gl.xr.isPresenting ? handleXRFrame : null);
          if (!state2.gl.xr.isPresenting) invalidate(state2);
        };
        const xr = {
          connect() {
            const gl2 = store.getState().gl;
            gl2.xr.addEventListener("sessionstart", handleSessionChange);
            gl2.xr.addEventListener("sessionend", handleSessionChange);
          },
          disconnect() {
            const gl2 = store.getState().gl;
            gl2.xr.removeEventListener("sessionstart", handleSessionChange);
            gl2.xr.removeEventListener("sessionend", handleSessionChange);
          }
        };
        if (typeof ((_gl$xr = gl.xr) == null ? void 0 : _gl$xr.addEventListener) === "function") xr.connect();
        state.set({
          xr
        });
      }
      if (gl.shadowMap) {
        const oldEnabled = gl.shadowMap.enabled;
        const oldType = gl.shadowMap.type;
        gl.shadowMap.enabled = !!shadows;
        if (is.boo(shadows)) {
          gl.shadowMap.type = PCFSoftShadowMap;
        } else if (is.str(shadows)) {
          var _types$shadows;
          const types = {
            basic: BasicShadowMap,
            percentage: PCFShadowMap,
            soft: PCFSoftShadowMap,
            variance: VSMShadowMap
          };
          gl.shadowMap.type = (_types$shadows = types[shadows]) != null ? _types$shadows : PCFSoftShadowMap;
        } else if (is.obj(shadows)) {
          Object.assign(gl.shadowMap, shadows);
        }
        if (oldEnabled !== gl.shadowMap.enabled || oldType !== gl.shadowMap.type) gl.shadowMap.needsUpdate = true;
      }
      const ColorManagement2 = getColorManagement();
      if (ColorManagement2) {
        if ("enabled" in ColorManagement2) ColorManagement2.enabled = !legacy;
        else if ("legacyMode" in ColorManagement2) ColorManagement2.legacyMode = legacy;
      }
      if (!configured) {
        const LinearEncoding2 = 3e3;
        const sRGBEncoding2 = 3001;
        applyProps(gl, {
          outputEncoding: linear ? LinearEncoding2 : sRGBEncoding2,
          toneMapping: flat ? NoToneMapping : ACESFilmicToneMapping
        });
      }
      if (state.legacy !== legacy) state.set(() => ({
        legacy
      }));
      if (state.linear !== linear) state.set(() => ({
        linear
      }));
      if (state.flat !== flat) state.set(() => ({
        flat
      }));
      if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig);
      if (events && !state.events.handlers) state.set({
        events: events(store)
      });
      const size = computeInitialSize(canvas, propsSize);
      if (!is.equ(size, state.size, shallowLoose)) {
        state.setSize(size.width, size.height, size.updateStyle, size.top, size.left);
      }
      if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr);
      if (state.frameloop !== frameloop) state.setFrameloop(frameloop);
      if (!state.onPointerMissed) state.set({
        onPointerMissed
      });
      if (performance2 && !is.equ(performance2, state.performance, shallowLoose)) state.set((state2) => ({
        performance: {
          ...state2.performance,
          ...performance2
        }
      }));
      onCreated = onCreatedCallback;
      configured = true;
      return this;
    },
    render(children) {
      if (!configured) this.configure();
      reconciler.updateContainer(/* @__PURE__ */ jsxRuntimeExports.jsx(Provider, {
        store,
        children,
        onCreated,
        rootElement: canvas
      }), fiber, null, () => void 0);
      return store;
    },
    unmount() {
      unmountComponentAtNode(canvas);
    }
  };
}
function Provider({
  store,
  children,
  onCreated,
  rootElement
}) {
  useIsomorphicLayoutEffect(() => {
    const state = store.getState();
    state.set((state2) => ({
      internal: {
        ...state2.internal,
        active: true
      }
    }));
    if (onCreated) onCreated(state);
    if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement);
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(context$1.Provider, {
    value: store,
    children
  });
}
function unmountComponentAtNode(canvas, callback) {
  const root = roots.get(canvas);
  const fiber = root == null ? void 0 : root.fiber;
  if (fiber) {
    const state = root == null ? void 0 : root.store.getState();
    if (state) state.internal.active = false;
    reconciler.updateContainer(null, fiber, null, () => {
      if (state) {
        setTimeout(() => {
          try {
            var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3;
            state.events.disconnect == null ? void 0 : state.events.disconnect();
            (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose();
            (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss();
            if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect();
            dispose(state);
            roots.delete(canvas);
            if (callback) ;
          } catch (e2) {
          }
        }, 500);
      }
    });
  }
}
function createPortal(children, container, state) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Portal, {
    children,
    container,
    state
  }, container.uuid);
}
function Portal({
  state = {},
  children,
  container
}) {
  const {
    events,
    size,
    ...rest
  } = state;
  const previousRoot = useStore();
  const [raycaster] = reactExports.useState(() => new Raycaster());
  const [pointer] = reactExports.useState(() => new Vector2());
  const inject = reactExports.useCallback(
    (rootState, injectState) => {
      const intersect2 = {
        ...rootState
      };
      Object.keys(rootState).forEach((key) => {
        if (
          // Some props should be off-limits
          privateKeys.includes(key) || // Otherwise filter out the props that are different and let the inject layer take precedence
          // Unless the inject layer props is undefined, then we keep the root layer
          rootState[key] !== injectState[key] && injectState[key]
        ) {
          delete intersect2[key];
        }
      });
      let viewport = void 0;
      if (injectState && size) {
        const camera = injectState.camera;
        viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), size);
        if (camera !== rootState.camera) updateCamera(camera, size);
      }
      return {
        // The intersect consists of the previous root state
        ...intersect2,
        // Portals have their own scene, which forms the root, a raycaster and a pointer
        scene: container,
        raycaster,
        pointer,
        mouse: pointer,
        // Their previous root is the layer before it
        previousRoot,
        // Events, size and viewport can be overridden by the inject layer
        events: {
          ...rootState.events,
          ...injectState == null ? void 0 : injectState.events,
          ...events
        },
        size: {
          ...rootState.size,
          ...size
        },
        viewport: {
          ...rootState.viewport,
          ...viewport
        },
        ...rest
      };
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [state]
  );
  const [usePortalStore] = reactExports.useState(() => {
    const previousState = previousRoot.getState();
    const store = create$1((set, get) => ({
      ...previousState,
      scene: container,
      raycaster,
      pointer,
      mouse: pointer,
      previousRoot,
      events: {
        ...previousState.events,
        ...events
      },
      size: {
        ...previousState.size,
        ...size
      },
      ...rest,
      // Set and get refer to this root-state
      set,
      get,
      // Layers are allowed to override events
      setEvents: (events2) => set((state2) => ({
        ...state2,
        events: {
          ...state2.events,
          ...events2
        }
      }))
    }));
    return store;
  });
  reactExports.useEffect(() => {
    const unsub = previousRoot.subscribe((prev) => usePortalStore.setState((state2) => inject(prev, state2)));
    return () => {
      unsub();
    };
  }, [inject]);
  reactExports.useEffect(() => {
    usePortalStore.setState((injectState) => inject(previousRoot.getState(), injectState));
  }, [inject]);
  reactExports.useEffect(() => {
    return () => {
      usePortalStore.destroy();
    };
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {
    children: reconciler.createPortal(/* @__PURE__ */ jsxRuntimeExports.jsx(context$1.Provider, {
      value: usePortalStore,
      children
    }), usePortalStore, null)
  });
}
reconciler.injectIntoDevTools({
  bundleType: 0,
  rendererPackageName: "@react-three/fiber",
  version: reactExports.version
});
const DOM_EVENTS = {
  onClick: ["click", false],
  onContextMenu: ["contextmenu", false],
  onDoubleClick: ["dblclick", false],
  onWheel: ["wheel", true],
  onPointerDown: ["pointerdown", true],
  onPointerUp: ["pointerup", true],
  onPointerLeave: ["pointerleave", true],
  onPointerMove: ["pointermove", true],
  onPointerCancel: ["pointercancel", true],
  onLostPointerCapture: ["lostpointercapture", true]
};
function createPointerEvents(store) {
  const {
    handlePointer
  } = createEvents(store);
  return {
    priority: 1,
    enabled: true,
    compute(event, state, previous) {
      state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
      state.raycaster.setFromCamera(state.pointer, state.camera);
    },
    connected: void 0,
    handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({
      ...acc,
      [key]: handlePointer(key)
    }), {}),
    update: () => {
      var _internal$lastEvent;
      const {
        events,
        internal
      } = store.getState();
      if ((_internal$lastEvent = internal.lastEvent) != null && _internal$lastEvent.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
    },
    connect: (target) => {
      var _events$handlers;
      const {
        set,
        events
      } = store.getState();
      events.disconnect == null ? void 0 : events.disconnect();
      set((state) => ({
        events: {
          ...state.events,
          connected: target
        }
      }));
      Object.entries((_events$handlers = events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => {
        const [eventName, passive] = DOM_EVENTS[name];
        target.addEventListener(eventName, event, {
          passive
        });
      });
    },
    disconnect: () => {
      const {
        set,
        events
      } = store.getState();
      if (events.connected) {
        var _events$handlers2;
        Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => {
          if (events && events.connected instanceof HTMLElement) {
            const [eventName] = DOM_EVENTS[name];
            events.connected.removeEventListener(eventName, event);
          }
        });
        set((state) => ({
          events: {
            ...state.events,
            connected: void 0
          }
        }));
      }
    }
  };
}
function g$1(n2, t2) {
  let o4;
  return (...i2) => {
    window.clearTimeout(o4), o4 = window.setTimeout(() => n2(...i2), t2);
  };
}
function j({ debounce: n2, scroll: t2, polyfill: o4, offsetSize: i2 } = { debounce: 0, scroll: false, offsetSize: false }) {
  const a3 = o4 || (typeof window == "undefined" ? class {
  } : window.ResizeObserver);
  if (!a3) throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");
  const [c2, h2] = reactExports.useState({ left: 0, top: 0, width: 0, height: 0, bottom: 0, right: 0, x: 0, y: 0 }), e2 = reactExports.useRef({ element: null, scrollContainers: null, resizeObserver: null, lastBounds: c2, orientationHandler: null }), d2 = n2 ? typeof n2 == "number" ? n2 : n2.scroll : null, f2 = n2 ? typeof n2 == "number" ? n2 : n2.resize : null, w2 = reactExports.useRef(false);
  reactExports.useEffect(() => (w2.current = true, () => void (w2.current = false)));
  const [z2, m2, s2] = reactExports.useMemo(() => {
    const r2 = () => {
      if (!e2.current.element) return;
      const { left: y2, top: C2, width: H2, height: O2, bottom: S2, right: x, x: B, y: R2 } = e2.current.element.getBoundingClientRect(), l2 = { left: y2, top: C2, width: H2, height: O2, bottom: S2, right: x, x: B, y: R2 };
      e2.current.element instanceof HTMLElement && i2 && (l2.height = e2.current.element.offsetHeight, l2.width = e2.current.element.offsetWidth), Object.freeze(l2), w2.current && !D(e2.current.lastBounds, l2) && h2(e2.current.lastBounds = l2);
    };
    return [r2, f2 ? g$1(r2, f2) : r2, d2 ? g$1(r2, d2) : r2];
  }, [h2, i2, d2, f2]);
  function v5() {
    e2.current.scrollContainers && (e2.current.scrollContainers.forEach((r2) => r2.removeEventListener("scroll", s2, true)), e2.current.scrollContainers = null), e2.current.resizeObserver && (e2.current.resizeObserver.disconnect(), e2.current.resizeObserver = null), e2.current.orientationHandler && ("orientation" in screen && "removeEventListener" in screen.orientation ? screen.orientation.removeEventListener("change", e2.current.orientationHandler) : "onorientationchange" in window && window.removeEventListener("orientationchange", e2.current.orientationHandler));
  }
  function b2() {
    e2.current.element && (e2.current.resizeObserver = new a3(s2), e2.current.resizeObserver.observe(e2.current.element), t2 && e2.current.scrollContainers && e2.current.scrollContainers.forEach((r2) => r2.addEventListener("scroll", s2, { capture: true, passive: true })), e2.current.orientationHandler = () => {
      s2();
    }, "orientation" in screen && "addEventListener" in screen.orientation ? screen.orientation.addEventListener("change", e2.current.orientationHandler) : "onorientationchange" in window && window.addEventListener("orientationchange", e2.current.orientationHandler));
  }
  const L2 = (r2) => {
    !r2 || r2 === e2.current.element || (v5(), e2.current.element = r2, e2.current.scrollContainers = E(r2), b2());
  };
  return X(s2, !!t2), W(m2), reactExports.useEffect(() => {
    v5(), b2();
  }, [t2, s2, m2]), reactExports.useEffect(() => v5, []), [L2, c2, z2];
}
function W(n2) {
  reactExports.useEffect(() => {
    const t2 = n2;
    return window.addEventListener("resize", t2), () => void window.removeEventListener("resize", t2);
  }, [n2]);
}
function X(n2, t2) {
  reactExports.useEffect(() => {
    if (t2) {
      const o4 = n2;
      return window.addEventListener("scroll", o4, { capture: true, passive: true }), () => void window.removeEventListener("scroll", o4, true);
    }
  }, [n2, t2]);
}
function E(n2) {
  const t2 = [];
  if (!n2 || n2 === document.body) return t2;
  const { overflow: o4, overflowX: i2, overflowY: a3 } = window.getComputedStyle(n2);
  return [o4, i2, a3].some((c2) => c2 === "auto" || c2 === "scroll") && t2.push(n2), [...t2, ...E(n2.parentElement)];
}
const k = ["x", "y", "top", "bottom", "left", "right", "width", "height"], D = (n2, t2) => k.every((o4) => n2[o4] === t2[o4]);
var __defProp$2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a3, b2) => {
  for (var prop in b2 || (b2 = {}))
    if (__hasOwnProp.call(b2, prop))
      __defNormalProp$2(a3, prop, b2[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b2)) {
      if (__propIsEnum.call(b2, prop))
        __defNormalProp$2(a3, prop, b2[prop]);
    }
  return a3;
};
var __spreadProps = (a3, b2) => __defProps(a3, __getOwnPropDescs(b2));
var _a$1, _b$1;
typeof window !== "undefined" && (((_a$1 = window.document) == null ? void 0 : _a$1.createElement) || ((_b$1 = window.navigator) == null ? void 0 : _b$1.product) === "ReactNative") ? reactExports.useLayoutEffect : reactExports.useEffect;
function traverseFiber(fiber, ascending, selector) {
  if (!fiber)
    return;
  if (selector(fiber) === true)
    return fiber;
  let child = fiber.child;
  while (child) {
    const match = traverseFiber(child, ascending, selector);
    if (match)
      return match;
    child = child.sibling;
  }
}
function wrapContext(context2) {
  try {
    return Object.defineProperties(context2, {
      _currentRenderer: {
        get() {
          return null;
        },
        set() {
        }
      },
      _currentRenderer2: {
        get() {
          return null;
        },
        set() {
        }
      }
    });
  } catch (_2) {
    return context2;
  }
}
const error = console.error;
console.error = function() {
  const message = [...arguments].join("");
  if ((message == null ? void 0 : message.startsWith("Warning:")) && message.includes("useContext")) {
    console.error = error;
    return;
  }
  return error.apply(this, arguments);
};
const FiberContext = wrapContext(reactExports.createContext(null));
class FiberProvider extends reactExports.Component {
  render() {
    return /* @__PURE__ */ reactExports.createElement(FiberContext.Provider, {
      value: this._reactInternals
    }, this.props.children);
  }
}
function useFiber() {
  const root = reactExports.useContext(FiberContext);
  if (root === null)
    throw new Error("its-fine: useFiber must be called within a <FiberProvider />!");
  const id = reactExports.useId();
  const fiber = reactExports.useMemo(() => {
    for (const maybeFiber of [root, root == null ? void 0 : root.alternate]) {
      if (!maybeFiber)
        continue;
      const fiber2 = traverseFiber(maybeFiber, false, (node) => {
        let state = node.memoizedState;
        while (state) {
          if (state.memoizedState === id)
            return true;
          state = state.next;
        }
      });
      if (fiber2)
        return fiber2;
    }
  }, [root, id]);
  return fiber;
}
function useContextMap() {
  const fiber = useFiber();
  const [contextMap] = reactExports.useState(() => /* @__PURE__ */ new Map());
  contextMap.clear();
  let node = fiber;
  while (node) {
    if (node.type && typeof node.type === "object") {
      const enableRenderableContext = node.type._context === void 0 && node.type.Provider === node.type;
      const context2 = enableRenderableContext ? node.type : node.type._context;
      if (context2 && context2 !== FiberContext && !contextMap.has(context2)) {
        contextMap.set(context2, reactExports.useContext(wrapContext(context2)));
      }
    }
    node = node.return;
  }
  return contextMap;
}
function useContextBridge() {
  const contextMap = useContextMap();
  return reactExports.useMemo(
    () => Array.from(contextMap.keys()).reduce(
      (Prev, context2) => (props) => /* @__PURE__ */ reactExports.createElement(Prev, null, /* @__PURE__ */ reactExports.createElement(context2.Provider, __spreadProps(__spreadValues({}, props), {
        value: contextMap.get(context2)
      }))),
      (props) => /* @__PURE__ */ reactExports.createElement(FiberProvider, __spreadValues({}, props))
    ),
    [contextMap]
  );
}
const CanvasImpl = /* @__PURE__ */ reactExports.forwardRef(function Canvas({
  children,
  fallback,
  resize,
  style,
  gl,
  events = createPointerEvents,
  eventSource,
  eventPrefix,
  shadows,
  linear,
  flat,
  legacy,
  orthographic,
  frameloop,
  dpr,
  performance: performance2,
  raycaster,
  camera,
  scene,
  onPointerMissed,
  onCreated,
  ...props
}, forwardedRef) {
  reactExports.useMemo(() => extend(THREE), []);
  const Bridge = useContextBridge();
  const [containerRef, containerRect] = j({
    scroll: true,
    debounce: {
      scroll: 50,
      resize: 0
    },
    ...resize
  });
  const canvasRef = reactExports.useRef(null);
  const divRef = reactExports.useRef(null);
  reactExports.useImperativeHandle(forwardedRef, () => canvasRef.current);
  const handlePointerMissed = useMutableCallback(onPointerMissed);
  const [block, setBlock] = reactExports.useState(false);
  const [error2, setError] = reactExports.useState(false);
  if (block) throw block;
  if (error2) throw error2;
  const root = reactExports.useRef(null);
  useIsomorphicLayoutEffect(() => {
    const canvas = canvasRef.current;
    if (containerRect.width > 0 && containerRect.height > 0 && canvas) {
      if (!root.current) root.current = createRoot(canvas);
      root.current.configure({
        gl,
        events,
        shadows,
        linear,
        flat,
        legacy,
        orthographic,
        frameloop,
        dpr,
        performance: performance2,
        raycaster,
        camera,
        scene,
        size: containerRect,
        // Pass mutable reference to onPointerMissed so it's free to update
        onPointerMissed: (...args) => handlePointerMissed.current == null ? void 0 : handlePointerMissed.current(...args),
        onCreated: (state) => {
          state.events.connect == null ? void 0 : state.events.connect(eventSource ? isRef$1(eventSource) ? eventSource.current : eventSource : divRef.current);
          if (eventPrefix) {
            state.setEvents({
              compute: (event, state2) => {
                const x = event[eventPrefix + "X"];
                const y2 = event[eventPrefix + "Y"];
                state2.pointer.set(x / state2.size.width * 2 - 1, -(y2 / state2.size.height) * 2 + 1);
                state2.raycaster.setFromCamera(state2.pointer, state2.camera);
              }
            });
          }
          onCreated == null ? void 0 : onCreated(state);
        }
      });
      root.current.render(/* @__PURE__ */ jsxRuntimeExports.jsx(Bridge, {
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(ErrorBoundary, {
          set: setError,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, {
            fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(Block, {
              set: setBlock
            }),
            children: children != null ? children : null
          })
        })
      }));
    }
  });
  reactExports.useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) return () => unmountComponentAtNode(canvas);
  }, []);
  const pointerEvents = eventSource ? "none" : "auto";
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", {
    ref: divRef,
    style: {
      position: "relative",
      width: "100%",
      height: "100%",
      overflow: "hidden",
      pointerEvents,
      ...style
    },
    ...props,
    children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", {
      ref: containerRef,
      style: {
        width: "100%",
        height: "100%"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx("canvas", {
        ref: canvasRef,
        style: {
          display: "block"
        },
        children: fallback
      })
    })
  });
});
const Canvas2 = /* @__PURE__ */ reactExports.forwardRef(function CanvasWrapper(props, ref) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(FiberProvider, {
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(CanvasImpl, {
      ...props,
      ref
    })
  });
});
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function(n2) {
    for (var e2 = 1; e2 < arguments.length; e2++) {
      var t2 = arguments[e2];
      for (var r2 in t2) ({}).hasOwnProperty.call(t2, r2) && (n2[r2] = t2[r2]);
    }
    return n2;
  }, _extends.apply(null, arguments);
}
var client = {};
var hasRequiredClient;
function requireClient() {
  if (hasRequiredClient) return client;
  hasRequiredClient = 1;
  var m2 = requireReactDom();
  {
    client.createRoot = m2.createRoot;
    client.hydrateRoot = m2.hydrateRoot;
  }
  return client;
}
var clientExports = requireClient();
const v1 = /* @__PURE__ */ new Vector3();
const v2 = /* @__PURE__ */ new Vector3();
const v3 = /* @__PURE__ */ new Vector3();
const v4 = /* @__PURE__ */ new Vector2();
function defaultCalculatePosition(el, camera, size) {
  const objectPos = v1.setFromMatrixPosition(el.matrixWorld);
  objectPos.project(camera);
  const widthHalf = size.width / 2;
  const heightHalf = size.height / 2;
  return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf];
}
function isObjectBehindCamera(el, camera) {
  const objectPos = v1.setFromMatrixPosition(el.matrixWorld);
  const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld);
  const deltaCamObj = objectPos.sub(cameraPos);
  const camDir = camera.getWorldDirection(v3);
  return deltaCamObj.angleTo(camDir) > Math.PI / 2;
}
function isObjectVisible(el, camera, raycaster, occlude) {
  const elPos = v1.setFromMatrixPosition(el.matrixWorld);
  const screenPos = elPos.clone();
  screenPos.project(camera);
  v4.set(screenPos.x, screenPos.y);
  raycaster.setFromCamera(v4, camera);
  const intersects2 = raycaster.intersectObjects(occlude, true);
  if (intersects2.length) {
    const intersectionDistance = intersects2[0].distance;
    const pointDistance = elPos.distanceTo(raycaster.ray.origin);
    return pointDistance < intersectionDistance;
  }
  return true;
}
function objectScale(el, camera) {
  if (camera instanceof OrthographicCamera) {
    return camera.zoom;
  } else if (camera instanceof PerspectiveCamera) {
    const objectPos = v1.setFromMatrixPosition(el.matrixWorld);
    const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld);
    const vFOV = camera.fov * Math.PI / 180;
    const dist = objectPos.distanceTo(cameraPos);
    const scaleFOV = 2 * Math.tan(vFOV / 2) * dist;
    return 1 / scaleFOV;
  } else {
    return 1;
  }
}
function objectZIndex(el, camera, zIndexRange) {
  if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) {
    const objectPos = v1.setFromMatrixPosition(el.matrixWorld);
    const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld);
    const dist = objectPos.distanceTo(cameraPos);
    const A2 = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near);
    const B = zIndexRange[1] - A2 * camera.far;
    return Math.round(A2 * dist + B);
  }
  return void 0;
}
const epsilon = (value) => Math.abs(value) < 1e-10 ? 0 : value;
function getCSSMatrix(matrix, multipliers, prepend = "") {
  let matrix3d = "matrix3d(";
  for (let i2 = 0; i2 !== 16; i2++) {
    matrix3d += epsilon(multipliers[i2] * matrix.elements[i2]) + (i2 !== 15 ? "," : ")");
  }
  return prepend + matrix3d;
}
const getCameraCSSMatrix = /* @__PURE__ */ ((multipliers) => {
  return (matrix) => getCSSMatrix(matrix, multipliers);
})([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]);
const getObjectCSSMatrix = /* @__PURE__ */ ((scaleMultipliers) => {
  return (matrix, factor) => getCSSMatrix(matrix, scaleMultipliers(factor), "translate(-50%,-50%)");
})((f2) => [1 / f2, 1 / f2, 1 / f2, 1, -1 / f2, -1 / f2, -1 / f2, -1, 1 / f2, 1 / f2, 1 / f2, 1, 1, 1, 1, 1]);
function isRefObject(ref) {
  return ref && typeof ref === "object" && "current" in ref;
}
const Html = /* @__PURE__ */ reactExports.forwardRef(({
  children,
  eps = 1e-3,
  style,
  className,
  prepend,
  center,
  fullscreen,
  portal,
  distanceFactor,
  sprite = false,
  transform = false,
  occlude,
  onOcclude,
  castShadow,
  receiveShadow,
  material,
  geometry,
  zIndexRange = [16777271, 0],
  calculatePosition = defaultCalculatePosition,
  as = "div",
  wrapperClass,
  pointerEvents = "auto",
  ...props
}, ref) => {
  const {
    gl,
    camera,
    scene,
    size,
    raycaster,
    events,
    viewport
  } = useThree();
  const [el] = reactExports.useState(() => document.createElement(as));
  const root = reactExports.useRef();
  const group = reactExports.useRef(null);
  const oldZoom = reactExports.useRef(0);
  const oldPosition = reactExports.useRef([0, 0]);
  const transformOuterRef = reactExports.useRef(null);
  const transformInnerRef = reactExports.useRef(null);
  const target = (portal == null ? void 0 : portal.current) || events.connected || gl.domElement.parentNode;
  const occlusionMeshRef = reactExports.useRef(null);
  const isMeshSizeSet = reactExports.useRef(false);
  const isRayCastOcclusion = reactExports.useMemo(() => {
    return occlude && occlude !== "blending" || Array.isArray(occlude) && occlude.length && isRefObject(occlude[0]);
  }, [occlude]);
  reactExports.useLayoutEffect(() => {
    const el2 = gl.domElement;
    if (occlude && occlude === "blending") {
      el2.style.zIndex = `${Math.floor(zIndexRange[0] / 2)}`;
      el2.style.position = "absolute";
      el2.style.pointerEvents = "none";
    } else {
      el2.style.zIndex = null;
      el2.style.position = null;
      el2.style.pointerEvents = null;
    }
  }, [occlude]);
  reactExports.useLayoutEffect(() => {
    if (group.current) {
      const currentRoot = root.current = clientExports.createRoot(el);
      scene.updateMatrixWorld();
      if (transform) {
        el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`;
      } else {
        const vec = calculatePosition(group.current, camera, size);
        el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`;
      }
      if (target) {
        if (prepend) target.prepend(el);
        else target.appendChild(el);
      }
      return () => {
        if (target) target.removeChild(el);
        currentRoot.unmount();
      };
    }
  }, [target, transform]);
  reactExports.useLayoutEffect(() => {
    if (wrapperClass) el.className = wrapperClass;
  }, [wrapperClass]);
  const styles = reactExports.useMemo(() => {
    if (transform) {
      return {
        position: "absolute",
        top: 0,
        left: 0,
        width: size.width,
        height: size.height,
        transformStyle: "preserve-3d",
        pointerEvents: "none"
      };
    } else {
      return {
        position: "absolute",
        transform: center ? "translate3d(-50%,-50%,0)" : "none",
        ...fullscreen && {
          top: -size.height / 2,
          left: -size.width / 2,
          width: size.width,
          height: size.height
        },
        ...style
      };
    }
  }, [style, center, fullscreen, size, transform]);
  const transformInnerStyles = reactExports.useMemo(() => ({
    position: "absolute",
    pointerEvents
  }), [pointerEvents]);
  reactExports.useLayoutEffect(() => {
    isMeshSizeSet.current = false;
    if (transform) {
      var _root$current;
      (_root$current = root.current) == null || _root$current.render(/* @__PURE__ */ reactExports.createElement("div", {
        ref: transformOuterRef,
        style: styles
      }, /* @__PURE__ */ reactExports.createElement("div", {
        ref: transformInnerRef,
        style: transformInnerStyles
      }, /* @__PURE__ */ reactExports.createElement("div", {
        ref,
        className,
        style,
        children
      }))));
    } else {
      var _root$current2;
      (_root$current2 = root.current) == null || _root$current2.render(/* @__PURE__ */ reactExports.createElement("div", {
        ref,
        style: styles,
        className,
        children
      }));
    }
  });
  const visible = reactExports.useRef(true);
  useFrame((gl2) => {
    if (group.current) {
      camera.updateMatrixWorld();
      group.current.updateWorldMatrix(true, false);
      const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size);
      if (transform || Math.abs(oldZoom.current - camera.zoom) > eps || Math.abs(oldPosition.current[0] - vec[0]) > eps || Math.abs(oldPosition.current[1] - vec[1]) > eps) {
        const isBehindCamera = isObjectBehindCamera(group.current, camera);
        let raytraceTarget = false;
        if (isRayCastOcclusion) {
          if (Array.isArray(occlude)) {
            raytraceTarget = occlude.map((item) => item.current);
          } else if (occlude !== "blending") {
            raytraceTarget = [scene];
          }
        }
        const previouslyVisible = visible.current;
        if (raytraceTarget) {
          const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget);
          visible.current = isvisible && !isBehindCamera;
        } else {
          visible.current = !isBehindCamera;
        }
        if (previouslyVisible !== visible.current) {
          if (onOcclude) onOcclude(!visible.current);
          else el.style.display = visible.current ? "block" : "none";
        }
        const halfRange = Math.floor(zIndexRange[0] / 2);
        const zRange = occlude ? isRayCastOcclusion ? [zIndexRange[0], halfRange] : [halfRange - 1, 0] : zIndexRange;
        el.style.zIndex = `${objectZIndex(group.current, camera, zRange)}`;
        if (transform) {
          const [widthHalf, heightHalf] = [size.width / 2, size.height / 2];
          const fov2 = camera.projectionMatrix.elements[5] * heightHalf;
          const {
            isOrthographicCamera: isOrthographicCamera2,
            top,
            left,
            bottom,
            right
          } = camera;
          const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse);
          const cameraTransform = isOrthographicCamera2 ? `scale(${fov2})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov2}px)`;
          let matrix = group.current.matrixWorld;
          if (sprite) {
            matrix = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix).scale(group.current.scale);
            matrix.elements[3] = matrix.elements[7] = matrix.elements[11] = 0;
            matrix.elements[15] = 1;
          }
          el.style.width = size.width + "px";
          el.style.height = size.height + "px";
          el.style.perspective = isOrthographicCamera2 ? "" : `${fov2}px`;
          if (transformOuterRef.current && transformInnerRef.current) {
            transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`;
            transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix, 1 / ((distanceFactor || 10) / 400));
          }
        } else {
          const scale = distanceFactor === void 0 ? 1 : objectScale(group.current, camera) * distanceFactor;
          el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale})`;
        }
        oldPosition.current = vec;
        oldZoom.current = camera.zoom;
      }
    }
    if (!isRayCastOcclusion && occlusionMeshRef.current && !isMeshSizeSet.current) {
      if (transform) {
        if (transformOuterRef.current) {
          const el2 = transformOuterRef.current.children[0];
          if (el2 != null && el2.clientWidth && el2 != null && el2.clientHeight) {
            const {
              isOrthographicCamera: isOrthographicCamera2
            } = camera;
            if (isOrthographicCamera2 || geometry) {
              if (props.scale) {
                if (!Array.isArray(props.scale)) {
                  occlusionMeshRef.current.scale.setScalar(1 / props.scale);
                } else if (props.scale instanceof Vector3) {
                  occlusionMeshRef.current.scale.copy(props.scale.clone().divideScalar(1));
                } else {
                  occlusionMeshRef.current.scale.set(1 / props.scale[0], 1 / props.scale[1], 1 / props.scale[2]);
                }
              }
            } else {
              const ratio = (distanceFactor || 10) / 400;
              const w2 = el2.clientWidth * ratio;
              const h2 = el2.clientHeight * ratio;
              occlusionMeshRef.current.scale.set(w2, h2, 1);
            }
            isMeshSizeSet.current = true;
          }
        }
      } else {
        const ele = el.children[0];
        if (ele != null && ele.clientWidth && ele != null && ele.clientHeight) {
          const ratio = 1 / viewport.factor;
          const w2 = ele.clientWidth * ratio;
          const h2 = ele.clientHeight * ratio;
          occlusionMeshRef.current.scale.set(w2, h2, 1);
          isMeshSizeSet.current = true;
        }
        occlusionMeshRef.current.lookAt(gl2.camera.position);
      }
    }
  });
  const shaders = reactExports.useMemo(() => ({
    vertexShader: !transform ? (
      /* glsl */
      `
          /*
            This shader is from the THREE's SpriteMaterial.
            We need to turn the backing plane into a Sprite
            (make it always face the camera) if "transfrom"
            is false.
          */
          #include <common>

          void main() {
            vec2 center = vec2(0., 1.);
            float rotation = 0.0;

            // This is somewhat arbitrary, but it seems to work well
            // Need to figure out how to derive this dynamically if it even matters
            float size = 0.03;

            vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
            vec2 scale;
            scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
            scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );

            bool isPerspective = isPerspectiveMatrix( projectionMatrix );
            if ( isPerspective ) scale *= - mvPosition.z;

            vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale * size;
            vec2 rotatedPosition;
            rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
            rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
            mvPosition.xy += rotatedPosition;

            gl_Position = projectionMatrix * mvPosition;
          }
      `
    ) : void 0,
    fragmentShader: (
      /* glsl */
      `
        void main() {
          gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
        }
      `
    )
  }), [transform]);
  return /* @__PURE__ */ reactExports.createElement("group", _extends({}, props, {
    ref: group
  }), occlude && !isRayCastOcclusion && /* @__PURE__ */ reactExports.createElement("mesh", {
    castShadow,
    receiveShadow,
    ref: occlusionMeshRef
  }, geometry || /* @__PURE__ */ reactExports.createElement("planeGeometry", null), material || /* @__PURE__ */ reactExports.createElement("shaderMaterial", {
    side: DoubleSide,
    vertexShader: shaders.vertexShader,
    fragmentShader: shaders.fragmentShader
  })));
});
const version$1 = /* @__PURE__ */ (() => parseInt(REVISION.replace(/\D+/g, "")))();
const UV1 = version$1 >= 125 ? "uv1" : "uv2";
function toCreasedNormals(geometry, creaseAngle = Math.PI / 3) {
  const creaseDot = Math.cos(creaseAngle);
  const hashMultiplier = (1 + 1e-10) * 100;
  const verts = [new Vector3(), new Vector3(), new Vector3()];
  const tempVec1 = new Vector3();
  const tempVec2 = new Vector3();
  const tempNorm = new Vector3();
  const tempNorm2 = new Vector3();
  function hashVertex(v5) {
    const x = ~~(v5.x * hashMultiplier);
    const y2 = ~~(v5.y * hashMultiplier);
    const z2 = ~~(v5.z * hashMultiplier);
    return `${x},${y2},${z2}`;
  }
  const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
  const posAttr = resultGeometry.attributes.position;
  const vertexMap = {};
  for (let i2 = 0, l2 = posAttr.count / 3; i2 < l2; i2++) {
    const i3 = 3 * i2;
    const a3 = verts[0].fromBufferAttribute(posAttr, i3 + 0);
    const b2 = verts[1].fromBufferAttribute(posAttr, i3 + 1);
    const c2 = verts[2].fromBufferAttribute(posAttr, i3 + 2);
    tempVec1.subVectors(c2, b2);
    tempVec2.subVectors(a3, b2);
    const normal = new Vector3().crossVectors(tempVec1, tempVec2).normalize();
    for (let n2 = 0; n2 < 3; n2++) {
      const vert = verts[n2];
      const hash = hashVertex(vert);
      if (!(hash in vertexMap)) {
        vertexMap[hash] = [];
      }
      vertexMap[hash].push(normal);
    }
  }
  const normalArray = new Float32Array(posAttr.count * 3);
  const normAttr = new BufferAttribute(normalArray, 3, false);
  for (let i2 = 0, l2 = posAttr.count / 3; i2 < l2; i2++) {
    const i3 = 3 * i2;
    const a3 = verts[0].fromBufferAttribute(posAttr, i3 + 0);
    const b2 = verts[1].fromBufferAttribute(posAttr, i3 + 1);
    const c2 = verts[2].fromBufferAttribute(posAttr, i3 + 2);
    tempVec1.subVectors(c2, b2);
    tempVec2.subVectors(a3, b2);
    tempNorm.crossVectors(tempVec1, tempVec2).normalize();
    for (let n2 = 0; n2 < 3; n2++) {
      const vert = verts[n2];
      const hash = hashVertex(vert);
      const otherNormals = vertexMap[hash];
      tempNorm2.set(0, 0, 0);
      for (let k2 = 0, lk = otherNormals.length; k2 < lk; k2++) {
        const otherNorm = otherNormals[k2];
        if (tempNorm.dot(otherNorm) > creaseDot) {
          tempNorm2.add(otherNorm);
        }
      }
      tempNorm2.normalize();
      normAttr.setXYZ(i3 + n2, tempNorm2.x, tempNorm2.y, tempNorm2.z);
    }
  }
  resultGeometry.setAttribute("normal", normAttr);
  return resultGeometry;
}
var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
var fleb = new u8([
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  1,
  1,
  1,
  1,
  2,
  2,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  0,
  /* unused */
  0,
  0,
  /* impossible */
  0
]);
var fdeb = new u8([
  0,
  0,
  0,
  0,
  1,
  1,
  2,
  2,
  3,
  3,
  4,
  4,
  5,
  5,
  6,
  6,
  7,
  7,
  8,
  8,
  9,
  9,
  10,
  10,
  11,
  11,
  12,
  12,
  13,
  13,
  /* unused */
  0,
  0
]);
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
var freb = function(eb, start) {
  var b2 = new u16(31);
  for (var i2 = 0; i2 < 31; ++i2) {
    b2[i2] = start += 1 << eb[i2 - 1];
  }
  var r2 = new u32(b2[30]);
  for (var i2 = 1; i2 < 30; ++i2) {
    for (var j2 = b2[i2]; j2 < b2[i2 + 1]; ++j2) {
      r2[j2] = j2 - b2[i2] << 5 | i2;
    }
  }
  return [b2, r2];
};
var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b[0];
var rev = new u16(32768);
for (var i$1 = 0; i$1 < 32768; ++i$1) {
  var x = (i$1 & 43690) >>> 1 | (i$1 & 21845) << 1;
  x = (x & 52428) >>> 2 | (x & 13107) << 2;
  x = (x & 61680) >>> 4 | (x & 3855) << 4;
  rev[i$1] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1;
}
var hMap = (function(cd, mb, r2) {
  var s2 = cd.length;
  var i2 = 0;
  var l2 = new u16(mb);
  for (; i2 < s2; ++i2)
    ++l2[cd[i2] - 1];
  var le2 = new u16(mb);
  for (i2 = 0; i2 < mb; ++i2) {
    le2[i2] = le2[i2 - 1] + l2[i2 - 1] << 1;
  }
  var co;
  if (r2) {
    co = new u16(1 << mb);
    var rvb = 15 - mb;
    for (i2 = 0; i2 < s2; ++i2) {
      if (cd[i2]) {
        var sv = i2 << 4 | cd[i2];
        var r_1 = mb - cd[i2];
        var v5 = le2[cd[i2] - 1]++ << r_1;
        for (var m2 = v5 | (1 << r_1) - 1; v5 <= m2; ++v5) {
          co[rev[v5] >>> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s2);
    for (i2 = 0; i2 < s2; ++i2) {
      if (cd[i2]) {
        co[i2] = rev[le2[cd[i2] - 1]++] >>> 15 - cd[i2];
      }
    }
  }
  return co;
});
var flt = new u8(288);
for (var i$1 = 0; i$1 < 144; ++i$1)
  flt[i$1] = 8;
for (var i$1 = 144; i$1 < 256; ++i$1)
  flt[i$1] = 9;
for (var i$1 = 256; i$1 < 280; ++i$1)
  flt[i$1] = 7;
for (var i$1 = 280; i$1 < 288; ++i$1)
  flt[i$1] = 8;
var fdt = new u8(32);
for (var i$1 = 0; i$1 < 32; ++i$1)
  fdt[i$1] = 5;
var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
var max = function(a3) {
  var m2 = a3[0];
  for (var i2 = 1; i2 < a3.length; ++i2) {
    if (a3[i2] > m2)
      m2 = a3[i2];
  }
  return m2;
};
var bits = function(d2, p2, m2) {
  var o4 = p2 / 8 | 0;
  return (d2[o4] | d2[o4 + 1] << 8) >> (p2 & 7) & m2;
};
var bits16 = function(d2, p2) {
  var o4 = p2 / 8 | 0;
  return (d2[o4] | d2[o4 + 1] << 8 | d2[o4 + 2] << 16) >> (p2 & 7);
};
var shft = function(p2) {
  return (p2 / 8 | 0) + (p2 & 7 && 1);
};
var slc = function(v5, s2, e2) {
  if (e2 == null || e2 > v5.length)
    e2 = v5.length;
  var n2 = new (v5 instanceof u16 ? u16 : v5 instanceof u32 ? u32 : u8)(e2 - s2);
  n2.set(v5.subarray(s2, e2));
  return n2;
};
var inflt = function(dat, buf, st) {
  var sl = dat.length;
  if (!sl || st && !st.l && sl < 5)
    return buf || new u8(0);
  var noBuf = !buf || st;
  var noSt = !st || st.i;
  if (!st)
    st = {};
  if (!buf)
    buf = new u8(sl * 3);
  var cbuf = function(l3) {
    var bl = buf.length;
    if (l3 > bl) {
      var nbuf = new u8(Math.max(bl * 2, l3));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  var final = st.f || 0, pos = st.p || 0, bt2 = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
  var tbts = sl * 8;
  do {
    if (!lm) {
      st.f = final = bits(dat, pos, 1);
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        var s2 = shft(pos) + 4, l2 = dat[s2 - 4] | dat[s2 - 3] << 8, t2 = s2 + l2;
        if (t2 > sl) {
          if (noSt)
            throw "unexpected EOF";
          break;
        }
        if (noBuf)
          cbuf(bt2 + l2);
        buf.set(dat.subarray(s2, t2), bt2);
        st.b = bt2 += l2, st.p = pos = t2 * 8;
        continue;
      } else if (type == 1)
        lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
      else if (type == 2) {
        var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        var ldt = new u8(tl);
        var clt = new u8(19);
        for (var i2 = 0; i2 < hcLen; ++i2) {
          clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
        }
        pos += hcLen * 3;
        var clb = max(clt), clbmsk = (1 << clb) - 1;
        var clm = hMap(clt, clb, 1);
        for (var i2 = 0; i2 < tl; ) {
          var r2 = clm[bits(dat, pos, clbmsk)];
          pos += r2 & 15;
          var s2 = r2 >>> 4;
          if (s2 < 16) {
            ldt[i2++] = s2;
          } else {
            var c2 = 0, n2 = 0;
            if (s2 == 16)
              n2 = 3 + bits(dat, pos, 3), pos += 2, c2 = ldt[i2 - 1];
            else if (s2 == 17)
              n2 = 3 + bits(dat, pos, 7), pos += 3;
            else if (s2 == 18)
              n2 = 11 + bits(dat, pos, 127), pos += 7;
            while (n2--)
              ldt[i2++] = c2;
          }
        }
        var lt2 = ldt.subarray(0, hLit), dt2 = ldt.subarray(hLit);
        lbt = max(lt2);
        dbt = max(dt2);
        lm = hMap(lt2, lbt, 1);
        dm = hMap(dt2, dbt, 1);
      } else
        throw "invalid block type";
      if (pos > tbts) {
        if (noSt)
          throw "unexpected EOF";
        break;
      }
    }
    if (noBuf)
      cbuf(bt2 + 131072);
    var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
    var lpos = pos;
    for (; ; lpos = pos) {
      var c2 = lm[bits16(dat, pos) & lms], sym = c2 >>> 4;
      pos += c2 & 15;
      if (pos > tbts) {
        if (noSt)
          throw "unexpected EOF";
        break;
      }
      if (!c2)
        throw "invalid length/literal";
      if (sym < 256)
        buf[bt2++] = sym;
      else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add = sym - 254;
        if (sym > 264) {
          var i2 = sym - 257, b2 = fleb[i2];
          add = bits(dat, pos, (1 << b2) - 1) + fl[i2];
          pos += b2;
        }
        var d2 = dm[bits16(dat, pos) & dms], dsym = d2 >>> 4;
        if (!d2)
          throw "invalid distance";
        pos += d2 & 15;
        var dt2 = fd[dsym];
        if (dsym > 3) {
          var b2 = fdeb[dsym];
          dt2 += bits16(dat, pos) & (1 << b2) - 1, pos += b2;
        }
        if (pos > tbts) {
          if (noSt)
            throw "unexpected EOF";
          break;
        }
        if (noBuf)
          cbuf(bt2 + 131072);
        var end = bt2 + add;
        for (; bt2 < end; bt2 += 4) {
          buf[bt2] = buf[bt2 - dt2];
          buf[bt2 + 1] = buf[bt2 + 1 - dt2];
          buf[bt2 + 2] = buf[bt2 + 2 - dt2];
          buf[bt2 + 3] = buf[bt2 + 3 - dt2];
        }
        bt2 = end;
      }
    }
    st.l = lm, st.p = lpos, st.b = bt2;
    if (lm)
      final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  return bt2 == buf.length ? buf : slc(buf, 0, bt2);
};
var et = /* @__PURE__ */ new u8(0);
var zlv = function(d2) {
  if ((d2[0] & 15) != 8 || d2[0] >>> 4 > 7 || (d2[0] << 8 | d2[1]) % 31)
    throw "invalid zlib data";
  if (d2[1] & 32)
    throw "invalid zlib data: preset dictionaries not supported";
};
function unzlibSync(data, out) {
  return inflt((zlv(data), data.subarray(2, -4)), out);
}
var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
var tds = 0;
try {
  td.decode(et, { stream: true });
  tds = 1;
} catch (e2) {
}
const isCubeTexture = (def) => def && def.isCubeTexture;
class GroundProjectedEnv extends Mesh {
  constructor(texture, options) {
    var _a2, _b2;
    const isCubeMap = isCubeTexture(texture);
    const w2 = (_b2 = isCubeMap ? (_a2 = texture.image[0]) == null ? void 0 : _a2.width : texture.image.width) != null ? _b2 : 1024;
    const cubeSize = w2 / 4;
    const _lodMax = Math.floor(Math.log2(cubeSize));
    const _cubeSize = Math.pow(2, _lodMax);
    const width = 3 * Math.max(_cubeSize, 16 * 7);
    const height = 4 * _cubeSize;
    const defines = [
      isCubeMap ? "#define ENVMAP_TYPE_CUBE" : "",
      `#define CUBEUV_TEXEL_WIDTH ${1 / width}`,
      `#define CUBEUV_TEXEL_HEIGHT ${1 / height}`,
      `#define CUBEUV_MAX_MIP ${_lodMax}.0`
    ];
    const vertexShader2 = (
      /* glsl */
      `
        varying vec3 vWorldPosition;
        void main() 
        {
            vec4 worldPosition = ( modelMatrix * vec4( position, 1.0 ) );
            vWorldPosition = worldPosition.xyz;
            
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
        }
        `
    );
    const fragmentShader2 = defines.join("\n") + /* glsl */
    `
        #define ENVMAP_TYPE_CUBE_UV
        varying vec3 vWorldPosition;
        uniform float radius;
        uniform float height;
        uniform float angle;
        #ifdef ENVMAP_TYPE_CUBE
            uniform samplerCube map;
        #else
            uniform sampler2D map;
        #endif
        // From: https://www.shadertoy.com/view/4tsBD7
        float diskIntersectWithBackFaceCulling( vec3 ro, vec3 rd, vec3 c, vec3 n, float r ) 
        {
            float d = dot ( rd, n );
            
            if( d > 0.0 ) { return 1e6; }
            
            vec3  o = ro - c;
            float t = - dot( n, o ) / d;
            vec3  q = o + rd * t;
            
            return ( dot( q, q ) < r * r ) ? t : 1e6;
        }
        // From: https://www.iquilezles.org/www/articles/intersectors/intersectors.htm
        float sphereIntersect( vec3 ro, vec3 rd, vec3 ce, float ra ) 
        {
            vec3 oc = ro - ce;
            float b = dot( oc, rd );
            float c = dot( oc, oc ) - ra * ra;
            float h = b * b - c;
            
            if( h < 0.0 ) { return -1.0; }
            
            h = sqrt( h );
            
            return - b + h;
        }
        vec3 project() 
        {
            vec3 p = normalize( vWorldPosition );
            vec3 camPos = cameraPosition;
            camPos.y -= height;
            float intersection = sphereIntersect( camPos, p, vec3( 0.0 ), radius );
            if( intersection > 0.0 ) {
                
                vec3 h = vec3( 0.0, - height, 0.0 );
                float intersection2 = diskIntersectWithBackFaceCulling( camPos, p, h, vec3( 0.0, 1.0, 0.0 ), radius );
                p = ( camPos + min( intersection, intersection2 ) * p ) / radius;
            } else {
                p = vec3( 0.0, 1.0, 0.0 );
            }
            return p;
        }
        #include <common>
        #include <cube_uv_reflection_fragment>
        void main() 
        {
            vec3 projectedWorldPosition = project();
            
            #ifdef ENVMAP_TYPE_CUBE
                vec3 outcolor = textureCube( map, projectedWorldPosition ).rgb;
            #else
                vec3 direction = normalize( projectedWorldPosition );
                vec2 uv = equirectUv( direction );
                vec3 outcolor = texture2D( map, uv ).rgb;
            #endif
            gl_FragColor = vec4( outcolor, 1.0 );
            #include <tonemapping_fragment>
            #include <${version$1 >= 154 ? "colorspace_fragment" : "encodings_fragment"}>
        }
        `;
    const uniforms = {
      map: { value: texture },
      height: { value: (options == null ? void 0 : options.height) || 15 },
      radius: { value: (options == null ? void 0 : options.radius) || 100 }
    };
    const geometry = new IcosahedronGeometry(1, 16);
    const material = new ShaderMaterial({
      uniforms,
      fragmentShader: fragmentShader2,
      vertexShader: vertexShader2,
      side: DoubleSide
    });
    super(geometry, material);
  }
  set radius(radius) {
    this.material.uniforms.radius.value = radius;
  }
  get radius() {
    return this.material.uniforms.radius.value;
  }
  set height(height) {
    this.material.uniforms.height.value = height;
  }
  get height() {
    return this.material.uniforms.height.value;
  }
}
var __defProp$1 = Object.defineProperty;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField$1 = (obj, key, value) => {
  __defNormalProp$1(obj, key + "", value);
  return value;
};
class EventDispatcher2 {
  constructor() {
    __publicField$1(this, "_listeners");
  }
  /**
   * Adds a listener to an event type.
   * @param type The type of event to listen to.
   * @param listener The function that gets called when the event is fired.
   */
  addEventListener(type, listener) {
    if (this._listeners === void 0)
      this._listeners = {};
    const listeners = this._listeners;
    if (listeners[type] === void 0) {
      listeners[type] = [];
    }
    if (listeners[type].indexOf(listener) === -1) {
      listeners[type].push(listener);
    }
  }
  /**
      * Checks if listener is added to an event type.
      * @param type The type of event to listen to.
      * @param listener The function that gets called when the event is fired.
      */
  hasEventListener(type, listener) {
    if (this._listeners === void 0)
      return false;
    const listeners = this._listeners;
    return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1;
  }
  /**
      * Removes a listener from an event type.
      * @param type The type of the listener that gets removed.
      * @param listener The listener function that gets removed.
      */
  removeEventListener(type, listener) {
    if (this._listeners === void 0)
      return;
    const listeners = this._listeners;
    const listenerArray = listeners[type];
    if (listenerArray !== void 0) {
      const index = listenerArray.indexOf(listener);
      if (index !== -1) {
        listenerArray.splice(index, 1);
      }
    }
  }
  /**
      * Fire an event type.
      * @param event The event that gets fired.
      */
  dispatchEvent(event) {
    if (this._listeners === void 0)
      return;
    const listeners = this._listeners;
    const listenerArray = listeners[event.type];
    if (listenerArray !== void 0) {
      event.target = this;
      const array = listenerArray.slice(0);
      for (let i2 = 0, l2 = array.length; i2 < l2; i2++) {
        array[i2].call(this, event);
      }
      event.target = null;
    }
  }
}
var __defProp2 = Object.defineProperty;
var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField2 = (obj, key, value) => {
  __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
const _ray$1 = /* @__PURE__ */ new Ray();
const _plane = /* @__PURE__ */ new Plane();
const TILT_LIMIT = Math.cos(70 * (Math.PI / 180));
const moduloWrapAround = (offset, capacity) => (offset % capacity + capacity) % capacity;
let OrbitControls$1 = class OrbitControls extends EventDispatcher2 {
  constructor(object, domElement) {
    super();
    __publicField2(this, "object");
    __publicField2(this, "domElement");
    __publicField2(this, "enabled", true);
    __publicField2(this, "target", new Vector3());
    __publicField2(this, "minDistance", 0);
    __publicField2(this, "maxDistance", Infinity);
    __publicField2(this, "minZoom", 0);
    __publicField2(this, "maxZoom", Infinity);
    __publicField2(this, "minPolarAngle", 0);
    __publicField2(this, "maxPolarAngle", Math.PI);
    __publicField2(this, "minAzimuthAngle", -Infinity);
    __publicField2(this, "maxAzimuthAngle", Infinity);
    __publicField2(this, "enableDamping", false);
    __publicField2(this, "dampingFactor", 0.05);
    __publicField2(this, "enableZoom", true);
    __publicField2(this, "zoomSpeed", 1);
    __publicField2(this, "enableRotate", true);
    __publicField2(this, "rotateSpeed", 1);
    __publicField2(this, "enablePan", true);
    __publicField2(this, "panSpeed", 1);
    __publicField2(this, "screenSpacePanning", true);
    __publicField2(this, "keyPanSpeed", 7);
    __publicField2(this, "zoomToCursor", false);
    __publicField2(this, "autoRotate", false);
    __publicField2(this, "autoRotateSpeed", 2);
    __publicField2(this, "reverseOrbit", false);
    __publicField2(this, "reverseHorizontalOrbit", false);
    __publicField2(this, "reverseVerticalOrbit", false);
    __publicField2(this, "keys", { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" });
    __publicField2(this, "mouseButtons", {
      LEFT: MOUSE.ROTATE,
      MIDDLE: MOUSE.DOLLY,
      RIGHT: MOUSE.PAN
    });
    __publicField2(this, "touches", { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN });
    __publicField2(this, "target0");
    __publicField2(this, "position0");
    __publicField2(this, "zoom0");
    __publicField2(this, "_domElementKeyEvents", null);
    __publicField2(this, "getPolarAngle");
    __publicField2(this, "getAzimuthalAngle");
    __publicField2(this, "setPolarAngle");
    __publicField2(this, "setAzimuthalAngle");
    __publicField2(this, "getDistance");
    __publicField2(this, "getZoomScale");
    __publicField2(this, "listenToKeyEvents");
    __publicField2(this, "stopListenToKeyEvents");
    __publicField2(this, "saveState");
    __publicField2(this, "reset");
    __publicField2(this, "update");
    __publicField2(this, "connect");
    __publicField2(this, "dispose");
    __publicField2(this, "dollyIn");
    __publicField2(this, "dollyOut");
    __publicField2(this, "getScale");
    __publicField2(this, "setScale");
    this.object = object;
    this.domElement = domElement;
    this.target0 = this.target.clone();
    this.position0 = this.object.position.clone();
    this.zoom0 = this.object.zoom;
    this.getPolarAngle = () => spherical.phi;
    this.getAzimuthalAngle = () => spherical.theta;
    this.setPolarAngle = (value) => {
      let phi = moduloWrapAround(value, 2 * Math.PI);
      let currentPhi = spherical.phi;
      if (currentPhi < 0)
        currentPhi += 2 * Math.PI;
      if (phi < 0)
        phi += 2 * Math.PI;
      let phiDist = Math.abs(phi - currentPhi);
      if (2 * Math.PI - phiDist < phiDist) {
        if (phi < currentPhi) {
          phi += 2 * Math.PI;
        } else {
          currentPhi += 2 * Math.PI;
        }
      }
      sphericalDelta.phi = phi - currentPhi;
      scope.update();
    };
    this.setAzimuthalAngle = (value) => {
      let theta = moduloWrapAround(value, 2 * Math.PI);
      let currentTheta = spherical.theta;
      if (currentTheta < 0)
        currentTheta += 2 * Math.PI;
      if (theta < 0)
        theta += 2 * Math.PI;
      let thetaDist = Math.abs(theta - currentTheta);
      if (2 * Math.PI - thetaDist < thetaDist) {
        if (theta < currentTheta) {
          theta += 2 * Math.PI;
        } else {
          currentTheta += 2 * Math.PI;
        }
      }
      sphericalDelta.theta = theta - currentTheta;
      scope.update();
    };
    this.getDistance = () => scope.object.position.distanceTo(scope.target);
    this.listenToKeyEvents = (domElement2) => {
      domElement2.addEventListener("keydown", onKeyDown);
      this._domElementKeyEvents = domElement2;
    };
    this.stopListenToKeyEvents = () => {
      this._domElementKeyEvents.removeEventListener("keydown", onKeyDown);
      this._domElementKeyEvents = null;
    };
    this.saveState = () => {
      scope.target0.copy(scope.target);
      scope.position0.copy(scope.object.position);
      scope.zoom0 = scope.object.zoom;
    };
    this.reset = () => {
      scope.target.copy(scope.target0);
      scope.object.position.copy(scope.position0);
      scope.object.zoom = scope.zoom0;
      scope.object.updateProjectionMatrix();
      scope.dispatchEvent(changeEvent);
      scope.update();
      state = STATE.NONE;
    };
    this.update = (() => {
      const offset = new Vector3();
      const up = new Vector3(0, 1, 0);
      const quat = new Quaternion().setFromUnitVectors(object.up, up);
      const quatInverse = quat.clone().invert();
      const lastPosition = new Vector3();
      const lastQuaternion = new Quaternion();
      const twoPI = 2 * Math.PI;
      return function update() {
        const position = scope.object.position;
        quat.setFromUnitVectors(object.up, up);
        quatInverse.copy(quat).invert();
        offset.copy(position).sub(scope.target);
        offset.applyQuaternion(quat);
        spherical.setFromVector3(offset);
        if (scope.autoRotate && state === STATE.NONE) {
          rotateLeft(getAutoRotationAngle());
        }
        if (scope.enableDamping) {
          spherical.theta += sphericalDelta.theta * scope.dampingFactor;
          spherical.phi += sphericalDelta.phi * scope.dampingFactor;
        } else {
          spherical.theta += sphericalDelta.theta;
          spherical.phi += sphericalDelta.phi;
        }
        let min = scope.minAzimuthAngle;
        let max2 = scope.maxAzimuthAngle;
        if (isFinite(min) && isFinite(max2)) {
          if (min < -Math.PI)
            min += twoPI;
          else if (min > Math.PI)
            min -= twoPI;
          if (max2 < -Math.PI)
            max2 += twoPI;
          else if (max2 > Math.PI)
            max2 -= twoPI;
          if (min <= max2) {
            spherical.theta = Math.max(min, Math.min(max2, spherical.theta));
          } else {
            spherical.theta = spherical.theta > (min + max2) / 2 ? Math.max(min, spherical.theta) : Math.min(max2, spherical.theta);
          }
        }
        spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
        spherical.makeSafe();
        if (scope.enableDamping === true) {
          scope.target.addScaledVector(panOffset, scope.dampingFactor);
        } else {
          scope.target.add(panOffset);
        }
        if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) {
          spherical.radius = clampDistance(spherical.radius);
        } else {
          spherical.radius = clampDistance(spherical.radius * scale);
        }
        offset.setFromSpherical(spherical);
        offset.applyQuaternion(quatInverse);
        position.copy(scope.target).add(offset);
        if (!scope.object.matrixAutoUpdate)
          scope.object.updateMatrix();
        scope.object.lookAt(scope.target);
        if (scope.enableDamping === true) {
          sphericalDelta.theta *= 1 - scope.dampingFactor;
          sphericalDelta.phi *= 1 - scope.dampingFactor;
          panOffset.multiplyScalar(1 - scope.dampingFactor);
        } else {
          sphericalDelta.set(0, 0, 0);
          panOffset.set(0, 0, 0);
        }
        let zoomChanged = false;
        if (scope.zoomToCursor && performCursorZoom) {
          let newRadius = null;
          if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) {
            const prevRadius = offset.length();
            newRadius = clampDistance(prevRadius * scale);
            const radiusDelta = prevRadius - newRadius;
            scope.object.position.addScaledVector(dollyDirection, radiusDelta);
            scope.object.updateMatrixWorld();
          } else if (scope.object.isOrthographicCamera) {
            const mouseBefore = new Vector3(mouse.x, mouse.y, 0);
            mouseBefore.unproject(scope.object);
            scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale));
            scope.object.updateProjectionMatrix();
            zoomChanged = true;
            const mouseAfter = new Vector3(mouse.x, mouse.y, 0);
            mouseAfter.unproject(scope.object);
            scope.object.position.sub(mouseAfter).add(mouseBefore);
            scope.object.updateMatrixWorld();
            newRadius = offset.length();
          } else {
            console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.");
            scope.zoomToCursor = false;
          }
          if (newRadius !== null) {
            if (scope.screenSpacePanning) {
              scope.target.set(0, 0, -1).transformDirection(scope.object.matrix).multiplyScalar(newRadius).add(scope.object.position);
            } else {
              _ray$1.origin.copy(scope.object.position);
              _ray$1.direction.set(0, 0, -1).transformDirection(scope.object.matrix);
              if (Math.abs(scope.object.up.dot(_ray$1.direction)) < TILT_LIMIT) {
                object.lookAt(scope.target);
              } else {
                _plane.setFromNormalAndCoplanarPoint(scope.object.up, scope.target);
                _ray$1.intersectPlane(_plane, scope.target);
              }
            }
          }
        } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) {
          zoomChanged = scale !== 1;
          if (zoomChanged) {
            scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale));
            scope.object.updateProjectionMatrix();
          }
        }
        scale = 1;
        performCursorZoom = false;
        if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
          scope.dispatchEvent(changeEvent);
          lastPosition.copy(scope.object.position);
          lastQuaternion.copy(scope.object.quaternion);
          zoomChanged = false;
          return true;
        }
        return false;
      };
    })();
    this.connect = (domElement2) => {
      scope.domElement = domElement2;
      scope.domElement.style.touchAction = "none";
      scope.domElement.addEventListener("contextmenu", onContextMenu);
      scope.domElement.addEventListener("pointerdown", onPointerDown);
      scope.domElement.addEventListener("pointercancel", onPointerUp);
      scope.domElement.addEventListener("wheel", onMouseWheel);
    };
    this.dispose = () => {
      var _a2, _b2, _c, _d, _e2, _f;
      if (scope.domElement) {
        scope.domElement.style.touchAction = "auto";
      }
      (_a2 = scope.domElement) == null ? void 0 : _a2.removeEventListener("contextmenu", onContextMenu);
      (_b2 = scope.domElement) == null ? void 0 : _b2.removeEventListener("pointerdown", onPointerDown);
      (_c = scope.domElement) == null ? void 0 : _c.removeEventListener("pointercancel", onPointerUp);
      (_d = scope.domElement) == null ? void 0 : _d.removeEventListener("wheel", onMouseWheel);
      (_e2 = scope.domElement) == null ? void 0 : _e2.ownerDocument.removeEventListener("pointermove", onPointerMove);
      (_f = scope.domElement) == null ? void 0 : _f.ownerDocument.removeEventListener("pointerup", onPointerUp);
      if (scope._domElementKeyEvents !== null) {
        scope._domElementKeyEvents.removeEventListener("keydown", onKeyDown);
      }
    };
    const scope = this;
    const changeEvent = { type: "change" };
    const startEvent = { type: "start" };
    const endEvent = { type: "end" };
    const STATE = {
      NONE: -1,
      ROTATE: 0,
      DOLLY: 1,
      PAN: 2,
      TOUCH_ROTATE: 3,
      TOUCH_PAN: 4,
      TOUCH_DOLLY_PAN: 5,
      TOUCH_DOLLY_ROTATE: 6
    };
    let state = STATE.NONE;
    const EPS = 1e-6;
    const spherical = new Spherical();
    const sphericalDelta = new Spherical();
    let scale = 1;
    const panOffset = new Vector3();
    const rotateStart = new Vector2();
    const rotateEnd = new Vector2();
    const rotateDelta = new Vector2();
    const panStart = new Vector2();
    const panEnd = new Vector2();
    const panDelta = new Vector2();
    const dollyStart = new Vector2();
    const dollyEnd = new Vector2();
    const dollyDelta = new Vector2();
    const dollyDirection = new Vector3();
    const mouse = new Vector2();
    let performCursorZoom = false;
    const pointers = [];
    const pointerPositions = {};
    function getAutoRotationAngle() {
      return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
    }
    function getZoomScale() {
      return Math.pow(0.95, scope.zoomSpeed);
    }
    function rotateLeft(angle) {
      if (scope.reverseOrbit || scope.reverseHorizontalOrbit) {
        sphericalDelta.theta += angle;
      } else {
        sphericalDelta.theta -= angle;
      }
    }
    function rotateUp(angle) {
      if (scope.reverseOrbit || scope.reverseVerticalOrbit) {
        sphericalDelta.phi += angle;
      } else {
        sphericalDelta.phi -= angle;
      }
    }
    const panLeft = (() => {
      const v5 = new Vector3();
      return function panLeft2(distance, objectMatrix) {
        v5.setFromMatrixColumn(objectMatrix, 0);
        v5.multiplyScalar(-distance);
        panOffset.add(v5);
      };
    })();
    const panUp = (() => {
      const v5 = new Vector3();
      return function panUp2(distance, objectMatrix) {
        if (scope.screenSpacePanning === true) {
          v5.setFromMatrixColumn(objectMatrix, 1);
        } else {
          v5.setFromMatrixColumn(objectMatrix, 0);
          v5.crossVectors(scope.object.up, v5);
        }
        v5.multiplyScalar(distance);
        panOffset.add(v5);
      };
    })();
    const pan = (() => {
      const offset = new Vector3();
      return function pan2(deltaX, deltaY) {
        const element = scope.domElement;
        if (element && scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) {
          const position = scope.object.position;
          offset.copy(position).sub(scope.target);
          let targetDistance = offset.length();
          targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180);
          panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
          panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
        } else if (element && scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) {
          panLeft(
            deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth,
            scope.object.matrix
          );
          panUp(
            deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight,
            scope.object.matrix
          );
        } else {
          console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
          scope.enablePan = false;
        }
      };
    })();
    function setScale(newScale) {
      if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera || scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) {
        scale = newScale;
      } else {
        console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
        scope.enableZoom = false;
      }
    }
    function dollyOut(dollyScale) {
      setScale(scale / dollyScale);
    }
    function dollyIn(dollyScale) {
      setScale(scale * dollyScale);
    }
    function updateMouseParameters(event) {
      if (!scope.zoomToCursor || !scope.domElement) {
        return;
      }
      performCursorZoom = true;
      const rect = scope.domElement.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y2 = event.clientY - rect.top;
      const w2 = rect.width;
      const h2 = rect.height;
      mouse.x = x / w2 * 2 - 1;
      mouse.y = -(y2 / h2) * 2 + 1;
      dollyDirection.set(mouse.x, mouse.y, 1).unproject(scope.object).sub(scope.object.position).normalize();
    }
    function clampDistance(dist) {
      return Math.max(scope.minDistance, Math.min(scope.maxDistance, dist));
    }
    function handleMouseDownRotate(event) {
      rotateStart.set(event.clientX, event.clientY);
    }
    function handleMouseDownDolly(event) {
      updateMouseParameters(event);
      dollyStart.set(event.clientX, event.clientY);
    }
    function handleMouseDownPan(event) {
      panStart.set(event.clientX, event.clientY);
    }
    function handleMouseMoveRotate(event) {
      rotateEnd.set(event.clientX, event.clientY);
      rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
      const element = scope.domElement;
      if (element) {
        rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight);
        rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
      }
      rotateStart.copy(rotateEnd);
      scope.update();
    }
    function handleMouseMoveDolly(event) {
      dollyEnd.set(event.clientX, event.clientY);
      dollyDelta.subVectors(dollyEnd, dollyStart);
      if (dollyDelta.y > 0) {
        dollyOut(getZoomScale());
      } else if (dollyDelta.y < 0) {
        dollyIn(getZoomScale());
      }
      dollyStart.copy(dollyEnd);
      scope.update();
    }
    function handleMouseMovePan(event) {
      panEnd.set(event.clientX, event.clientY);
      panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
      pan(panDelta.x, panDelta.y);
      panStart.copy(panEnd);
      scope.update();
    }
    function handleMouseWheel(event) {
      updateMouseParameters(event);
      if (event.deltaY < 0) {
        dollyIn(getZoomScale());
      } else if (event.deltaY > 0) {
        dollyOut(getZoomScale());
      }
      scope.update();
    }
    function handleKeyDown(event) {
      let needsUpdate = false;
      switch (event.code) {
        case scope.keys.UP:
          pan(0, scope.keyPanSpeed);
          needsUpdate = true;
          break;
        case scope.keys.BOTTOM:
          pan(0, -scope.keyPanSpeed);
          needsUpdate = true;
          break;
        case scope.keys.LEFT:
          pan(scope.keyPanSpeed, 0);
          needsUpdate = true;
          break;
        case scope.keys.RIGHT:
          pan(-scope.keyPanSpeed, 0);
          needsUpdate = true;
          break;
      }
      if (needsUpdate) {
        event.preventDefault();
        scope.update();
      }
    }
    function handleTouchStartRotate() {
      if (pointers.length == 1) {
        rotateStart.set(pointers[0].pageX, pointers[0].pageY);
      } else {
        const x = 0.5 * (pointers[0].pageX + pointers[1].pageX);
        const y2 = 0.5 * (pointers[0].pageY + pointers[1].pageY);
        rotateStart.set(x, y2);
      }
    }
    function handleTouchStartPan() {
      if (pointers.length == 1) {
        panStart.set(pointers[0].pageX, pointers[0].pageY);
      } else {
        const x = 0.5 * (pointers[0].pageX + pointers[1].pageX);
        const y2 = 0.5 * (pointers[0].pageY + pointers[1].pageY);
        panStart.set(x, y2);
      }
    }
    function handleTouchStartDolly() {
      const dx = pointers[0].pageX - pointers[1].pageX;
      const dy = pointers[0].pageY - pointers[1].pageY;
      const distance = Math.sqrt(dx * dx + dy * dy);
      dollyStart.set(0, distance);
    }
    function handleTouchStartDollyPan() {
      if (scope.enableZoom)
        handleTouchStartDolly();
      if (scope.enablePan)
        handleTouchStartPan();
    }
    function handleTouchStartDollyRotate() {
      if (scope.enableZoom)
        handleTouchStartDolly();
      if (scope.enableRotate)
        handleTouchStartRotate();
    }
    function handleTouchMoveRotate(event) {
      if (pointers.length == 1) {
        rotateEnd.set(event.pageX, event.pageY);
      } else {
        const position = getSecondPointerPosition(event);
        const x = 0.5 * (event.pageX + position.x);
        const y2 = 0.5 * (event.pageY + position.y);
        rotateEnd.set(x, y2);
      }
      rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
      const element = scope.domElement;
      if (element) {
        rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight);
        rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
      }
      rotateStart.copy(rotateEnd);
    }
    function handleTouchMovePan(event) {
      if (pointers.length == 1) {
        panEnd.set(event.pageX, event.pageY);
      } else {
        const position = getSecondPointerPosition(event);
        const x = 0.5 * (event.pageX + position.x);
        const y2 = 0.5 * (event.pageY + position.y);
        panEnd.set(x, y2);
      }
      panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
      pan(panDelta.x, panDelta.y);
      panStart.copy(panEnd);
    }
    function handleTouchMoveDolly(event) {
      const position = getSecondPointerPosition(event);
      const dx = event.pageX - position.x;
      const dy = event.pageY - position.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      dollyEnd.set(0, distance);
      dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
      dollyOut(dollyDelta.y);
      dollyStart.copy(dollyEnd);
    }
    function handleTouchMoveDollyPan(event) {
      if (scope.enableZoom)
        handleTouchMoveDolly(event);
      if (scope.enablePan)
        handleTouchMovePan(event);
    }
    function handleTouchMoveDollyRotate(event) {
      if (scope.enableZoom)
        handleTouchMoveDolly(event);
      if (scope.enableRotate)
        handleTouchMoveRotate(event);
    }
    function onPointerDown(event) {
      var _a2, _b2;
      if (scope.enabled === false)
        return;
      if (pointers.length === 0) {
        (_a2 = scope.domElement) == null ? void 0 : _a2.ownerDocument.addEventListener("pointermove", onPointerMove);
        (_b2 = scope.domElement) == null ? void 0 : _b2.ownerDocument.addEventListener("pointerup", onPointerUp);
      }
      addPointer(event);
      if (event.pointerType === "touch") {
        onTouchStart(event);
      } else {
        onMouseDown(event);
      }
    }
    function onPointerMove(event) {
      if (scope.enabled === false)
        return;
      if (event.pointerType === "touch") {
        onTouchMove(event);
      } else {
        onMouseMove(event);
      }
    }
    function onPointerUp(event) {
      var _a2, _b2, _c;
      removePointer(event);
      if (pointers.length === 0) {
        (_a2 = scope.domElement) == null ? void 0 : _a2.releasePointerCapture(event.pointerId);
        (_b2 = scope.domElement) == null ? void 0 : _b2.ownerDocument.removeEventListener("pointermove", onPointerMove);
        (_c = scope.domElement) == null ? void 0 : _c.ownerDocument.removeEventListener("pointerup", onPointerUp);
      }
      scope.dispatchEvent(endEvent);
      state = STATE.NONE;
    }
    function onMouseDown(event) {
      let mouseAction;
      switch (event.button) {
        case 0:
          mouseAction = scope.mouseButtons.LEFT;
          break;
        case 1:
          mouseAction = scope.mouseButtons.MIDDLE;
          break;
        case 2:
          mouseAction = scope.mouseButtons.RIGHT;
          break;
        default:
          mouseAction = -1;
      }
      switch (mouseAction) {
        case MOUSE.DOLLY:
          if (scope.enableZoom === false)
            return;
          handleMouseDownDolly(event);
          state = STATE.DOLLY;
          break;
        case MOUSE.ROTATE:
          if (event.ctrlKey || event.metaKey || event.shiftKey) {
            if (scope.enablePan === false)
              return;
            handleMouseDownPan(event);
            state = STATE.PAN;
          } else {
            if (scope.enableRotate === false)
              return;
            handleMouseDownRotate(event);
            state = STATE.ROTATE;
          }
          break;
        case MOUSE.PAN:
          if (event.ctrlKey || event.metaKey || event.shiftKey) {
            if (scope.enableRotate === false)
              return;
            handleMouseDownRotate(event);
            state = STATE.ROTATE;
          } else {
            if (scope.enablePan === false)
              return;
            handleMouseDownPan(event);
            state = STATE.PAN;
          }
          break;
        default:
          state = STATE.NONE;
      }
      if (state !== STATE.NONE) {
        scope.dispatchEvent(startEvent);
      }
    }
    function onMouseMove(event) {
      if (scope.enabled === false)
        return;
      switch (state) {
        case STATE.ROTATE:
          if (scope.enableRotate === false)
            return;
          handleMouseMoveRotate(event);
          break;
        case STATE.DOLLY:
          if (scope.enableZoom === false)
            return;
          handleMouseMoveDolly(event);
          break;
        case STATE.PAN:
          if (scope.enablePan === false)
            return;
          handleMouseMovePan(event);
          break;
      }
    }
    function onMouseWheel(event) {
      if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) {
        return;
      }
      event.preventDefault();
      scope.dispatchEvent(startEvent);
      handleMouseWheel(event);
      scope.dispatchEvent(endEvent);
    }
    function onKeyDown(event) {
      if (scope.enabled === false || scope.enablePan === false)
        return;
      handleKeyDown(event);
    }
    function onTouchStart(event) {
      trackPointer(event);
      switch (pointers.length) {
        case 1:
          switch (scope.touches.ONE) {
            case TOUCH.ROTATE:
              if (scope.enableRotate === false)
                return;
              handleTouchStartRotate();
              state = STATE.TOUCH_ROTATE;
              break;
            case TOUCH.PAN:
              if (scope.enablePan === false)
                return;
              handleTouchStartPan();
              state = STATE.TOUCH_PAN;
              break;
            default:
              state = STATE.NONE;
          }
          break;
        case 2:
          switch (scope.touches.TWO) {
            case TOUCH.DOLLY_PAN:
              if (scope.enableZoom === false && scope.enablePan === false)
                return;
              handleTouchStartDollyPan();
              state = STATE.TOUCH_DOLLY_PAN;
              break;
            case TOUCH.DOLLY_ROTATE:
              if (scope.enableZoom === false && scope.enableRotate === false)
                return;
              handleTouchStartDollyRotate();
              state = STATE.TOUCH_DOLLY_ROTATE;
              break;
            default:
              state = STATE.NONE;
          }
          break;
        default:
          state = STATE.NONE;
      }
      if (state !== STATE.NONE) {
        scope.dispatchEvent(startEvent);
      }
    }
    function onTouchMove(event) {
      trackPointer(event);
      switch (state) {
        case STATE.TOUCH_ROTATE:
          if (scope.enableRotate === false)
            return;
          handleTouchMoveRotate(event);
          scope.update();
          break;
        case STATE.TOUCH_PAN:
          if (scope.enablePan === false)
            return;
          handleTouchMovePan(event);
          scope.update();
          break;
        case STATE.TOUCH_DOLLY_PAN:
          if (scope.enableZoom === false && scope.enablePan === false)
            return;
          handleTouchMoveDollyPan(event);
          scope.update();
          break;
        case STATE.TOUCH_DOLLY_ROTATE:
          if (scope.enableZoom === false && scope.enableRotate === false)
            return;
          handleTouchMoveDollyRotate(event);
          scope.update();
          break;
        default:
          state = STATE.NONE;
      }
    }
    function onContextMenu(event) {
      if (scope.enabled === false)
        return;
      event.preventDefault();
    }
    function addPointer(event) {
      pointers.push(event);
    }
    function removePointer(event) {
      delete pointerPositions[event.pointerId];
      for (let i2 = 0; i2 < pointers.length; i2++) {
        if (pointers[i2].pointerId == event.pointerId) {
          pointers.splice(i2, 1);
          return;
        }
      }
    }
    function trackPointer(event) {
      let position = pointerPositions[event.pointerId];
      if (position === void 0) {
        position = new Vector2();
        pointerPositions[event.pointerId] = position;
      }
      position.set(event.pageX, event.pageY);
    }
    function getSecondPointerPosition(event) {
      const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0];
      return pointerPositions[pointer.pointerId];
    }
    this.dollyIn = (dollyScale = getZoomScale()) => {
      dollyIn(dollyScale);
      scope.update();
    };
    this.dollyOut = (dollyScale = getZoomScale()) => {
      dollyOut(dollyScale);
      scope.update();
    };
    this.getScale = () => {
      return scale;
    };
    this.setScale = (newScale) => {
      setScale(newScale);
      scope.update();
    };
    this.getZoomScale = () => {
      return getZoomScale();
    };
    if (domElement !== void 0)
      this.connect(domElement);
    this.update();
  }
};
const HorizontalBlurShader = {
  uniforms: {
    tDiffuse: { value: null },
    h: { value: 1 / 512 }
  },
  vertexShader: (
    /* glsl */
    `
      varying vec2 vUv;

      void main() {

        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

      }
  `
  ),
  fragmentShader: (
    /* glsl */
    `
    uniform sampler2D tDiffuse;
    uniform float h;

    varying vec2 vUv;

    void main() {

    	vec4 sum = vec4( 0.0 );

    	sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;
    	sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;
    	sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;
    	sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;
    	sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
    	sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;
    	sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;
    	sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;
    	sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;

    	gl_FragColor = sum;

    }
  `
  )
};
const VerticalBlurShader = {
  uniforms: {
    tDiffuse: { value: null },
    v: { value: 1 / 512 }
  },
  vertexShader: (
    /* glsl */
    `
    varying vec2 vUv;

    void main() {

      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

    }
  `
  ),
  fragmentShader: (
    /* glsl */
    `

  uniform sampler2D tDiffuse;
  uniform float v;

  varying vec2 vUv;

  void main() {

    vec4 sum = vec4( 0.0 );

    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;
    sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;

    gl_FragColor = sum;

  }
  `
  )
};
class RGBELoader extends DataTextureLoader {
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html
  parse(buffer) {
    const rgbe_read_error = 1, rgbe_write_error = 2, rgbe_format_error = 3, rgbe_memory_error = 4, rgbe_error = function(rgbe_error_code, msg) {
      switch (rgbe_error_code) {
        case rgbe_read_error:
          throw new Error("THREE.RGBELoader: Read Error: " + (msg || ""));
        case rgbe_write_error:
          throw new Error("THREE.RGBELoader: Write Error: " + (msg || ""));
        case rgbe_format_error:
          throw new Error("THREE.RGBELoader: Bad File Format: " + (msg || ""));
        default:
        case rgbe_memory_error:
          throw new Error("THREE.RGBELoader: Memory Error: " + (msg || ""));
      }
    }, RGBE_VALID_PROGRAMTYPE = 1, RGBE_VALID_FORMAT = 2, RGBE_VALID_DIMENSIONS = 4, NEWLINE = "\n", fgets = function(buffer2, lineLimit, consume) {
      const chunkSize = 128;
      lineLimit = !lineLimit ? 1024 : lineLimit;
      let p2 = buffer2.pos, i2 = -1, len = 0, s2 = "", chunk = String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p2, p2 + chunkSize)));
      while (0 > (i2 = chunk.indexOf(NEWLINE)) && len < lineLimit && p2 < buffer2.byteLength) {
        s2 += chunk;
        len += chunk.length;
        p2 += chunkSize;
        chunk += String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p2, p2 + chunkSize)));
      }
      if (-1 < i2) {
        buffer2.pos += len + i2 + 1;
        return s2 + chunk.slice(0, i2);
      }
      return false;
    }, RGBE_ReadHeader = function(buffer2) {
      const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/, header = {
        valid: 0,
        string: "",
        comments: "",
        programtype: "RGBE",
        format: "",
        gamma: 1,
        exposure: 1,
        width: 0,
        height: 0
      };
      let line, match;
      if (buffer2.pos >= buffer2.byteLength || !(line = fgets(buffer2))) {
        rgbe_error(rgbe_read_error, "no header found");
      }
      if (!(match = line.match(magic_token_re))) {
        rgbe_error(rgbe_format_error, "bad initial token");
      }
      header.valid |= RGBE_VALID_PROGRAMTYPE;
      header.programtype = match[1];
      header.string += line + "\n";
      while (true) {
        line = fgets(buffer2);
        if (false === line)
          break;
        header.string += line + "\n";
        if ("#" === line.charAt(0)) {
          header.comments += line + "\n";
          continue;
        }
        if (match = line.match(gamma_re)) {
          header.gamma = parseFloat(match[1]);
        }
        if (match = line.match(exposure_re)) {
          header.exposure = parseFloat(match[1]);
        }
        if (match = line.match(format_re)) {
          header.valid |= RGBE_VALID_FORMAT;
          header.format = match[1];
        }
        if (match = line.match(dimensions_re)) {
          header.valid |= RGBE_VALID_DIMENSIONS;
          header.height = parseInt(match[1], 10);
          header.width = parseInt(match[2], 10);
        }
        if (header.valid & RGBE_VALID_FORMAT && header.valid & RGBE_VALID_DIMENSIONS)
          break;
      }
      if (!(header.valid & RGBE_VALID_FORMAT)) {
        rgbe_error(rgbe_format_error, "missing format specifier");
      }
      if (!(header.valid & RGBE_VALID_DIMENSIONS)) {
        rgbe_error(rgbe_format_error, "missing image size specifier");
      }
      return header;
    }, RGBE_ReadPixels_RLE = function(buffer2, w22, h22) {
      const scanline_width = w22;
      if (
        // run length encoding is not allowed so read flat
        scanline_width < 8 || scanline_width > 32767 || // this file is not run length encoded
        2 !== buffer2[0] || 2 !== buffer2[1] || buffer2[2] & 128
      ) {
        return new Uint8Array(buffer2);
      }
      if (scanline_width !== (buffer2[2] << 8 | buffer2[3])) {
        rgbe_error(rgbe_format_error, "wrong scanline width");
      }
      const data_rgba = new Uint8Array(4 * w22 * h22);
      if (!data_rgba.length) {
        rgbe_error(rgbe_memory_error, "unable to allocate buffer space");
      }
      let offset = 0, pos = 0;
      const ptr_end = 4 * scanline_width;
      const rgbeStart = new Uint8Array(4);
      const scanline_buffer = new Uint8Array(ptr_end);
      let num_scanlines = h22;
      while (num_scanlines > 0 && pos < buffer2.byteLength) {
        if (pos + 4 > buffer2.byteLength) {
          rgbe_error(rgbe_read_error);
        }
        rgbeStart[0] = buffer2[pos++];
        rgbeStart[1] = buffer2[pos++];
        rgbeStart[2] = buffer2[pos++];
        rgbeStart[3] = buffer2[pos++];
        if (2 != rgbeStart[0] || 2 != rgbeStart[1] || (rgbeStart[2] << 8 | rgbeStart[3]) != scanline_width) {
          rgbe_error(rgbe_format_error, "bad rgbe scanline format");
        }
        let ptr = 0, count;
        while (ptr < ptr_end && pos < buffer2.byteLength) {
          count = buffer2[pos++];
          const isEncodedRun = count > 128;
          if (isEncodedRun)
            count -= 128;
          if (0 === count || ptr + count > ptr_end) {
            rgbe_error(rgbe_format_error, "bad scanline data");
          }
          if (isEncodedRun) {
            const byteValue = buffer2[pos++];
            for (let i2 = 0; i2 < count; i2++) {
              scanline_buffer[ptr++] = byteValue;
            }
          } else {
            scanline_buffer.set(buffer2.subarray(pos, pos + count), ptr);
            ptr += count;
            pos += count;
          }
        }
        const l2 = scanline_width;
        for (let i2 = 0; i2 < l2; i2++) {
          let off = 0;
          data_rgba[offset] = scanline_buffer[i2 + off];
          off += scanline_width;
          data_rgba[offset + 1] = scanline_buffer[i2 + off];
          off += scanline_width;
          data_rgba[offset + 2] = scanline_buffer[i2 + off];
          off += scanline_width;
          data_rgba[offset + 3] = scanline_buffer[i2 + off];
          offset += 4;
        }
        num_scanlines--;
      }
      return data_rgba;
    };
    const RGBEByteToRGBFloat = function(sourceArray, sourceOffset, destArray, destOffset) {
      const e2 = sourceArray[sourceOffset + 3];
      const scale = Math.pow(2, e2 - 128) / 255;
      destArray[destOffset + 0] = sourceArray[sourceOffset + 0] * scale;
      destArray[destOffset + 1] = sourceArray[sourceOffset + 1] * scale;
      destArray[destOffset + 2] = sourceArray[sourceOffset + 2] * scale;
      destArray[destOffset + 3] = 1;
    };
    const RGBEByteToRGBHalf = function(sourceArray, sourceOffset, destArray, destOffset) {
      const e2 = sourceArray[sourceOffset + 3];
      const scale = Math.pow(2, e2 - 128) / 255;
      destArray[destOffset + 0] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 0] * scale, 65504));
      destArray[destOffset + 1] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 1] * scale, 65504));
      destArray[destOffset + 2] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 2] * scale, 65504));
      destArray[destOffset + 3] = DataUtils.toHalfFloat(1);
    };
    const byteArray = new Uint8Array(buffer);
    byteArray.pos = 0;
    const rgbe_header_info = RGBE_ReadHeader(byteArray);
    const w2 = rgbe_header_info.width, h2 = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos), w2, h2);
    let data, type;
    let numElements;
    switch (this.type) {
      case FloatType:
        numElements = image_rgba_data.length / 4;
        const floatArray = new Float32Array(numElements * 4);
        for (let j2 = 0; j2 < numElements; j2++) {
          RGBEByteToRGBFloat(image_rgba_data, j2 * 4, floatArray, j2 * 4);
        }
        data = floatArray;
        type = FloatType;
        break;
      case HalfFloatType:
        numElements = image_rgba_data.length / 4;
        const halfArray = new Uint16Array(numElements * 4);
        for (let j2 = 0; j2 < numElements; j2++) {
          RGBEByteToRGBHalf(image_rgba_data, j2 * 4, halfArray, j2 * 4);
        }
        data = halfArray;
        type = HalfFloatType;
        break;
      default:
        throw new Error("THREE.RGBELoader: Unsupported type: " + this.type);
    }
    return {
      width: w2,
      height: h2,
      data,
      header: rgbe_header_info.string,
      gamma: rgbe_header_info.gamma,
      exposure: rgbe_header_info.exposure,
      type
    };
  }
  setDataType(value) {
    this.type = value;
    return this;
  }
  load(url, onLoad, onProgress, onError) {
    function onLoadCallback(texture, texData) {
      switch (texture.type) {
        case FloatType:
        case HalfFloatType:
          if ("colorSpace" in texture)
            texture.colorSpace = "srgb-linear";
          else
            texture.encoding = 3e3;
          texture.minFilter = LinearFilter;
          texture.magFilter = LinearFilter;
          texture.generateMipmaps = false;
          texture.flipY = true;
          break;
      }
      if (onLoad)
        onLoad(texture, texData);
    }
    return super.load(url, onLoadCallback, onProgress, onError);
  }
}
const hasColorSpace = version$1 >= 152;
class EXRLoader extends DataTextureLoader {
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  parse(buffer) {
    const USHORT_RANGE = 1 << 16;
    const BITMAP_SIZE = USHORT_RANGE >> 3;
    const HUF_ENCBITS = 16;
    const HUF_DECBITS = 14;
    const HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1;
    const HUF_DECSIZE = 1 << HUF_DECBITS;
    const HUF_DECMASK = HUF_DECSIZE - 1;
    const NBITS = 16;
    const A_OFFSET = 1 << NBITS - 1;
    const MOD_MASK = (1 << NBITS) - 1;
    const SHORT_ZEROCODE_RUN = 59;
    const LONG_ZEROCODE_RUN = 63;
    const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
    const ULONG_SIZE = 8;
    const FLOAT32_SIZE = 4;
    const INT32_SIZE = 4;
    const INT16_SIZE = 2;
    const INT8_SIZE = 1;
    const STATIC_HUFFMAN = 0;
    const DEFLATE = 1;
    const UNKNOWN = 0;
    const LOSSY_DCT = 1;
    const RLE = 2;
    const logBase = Math.pow(2.7182818, 2.2);
    function reverseLutFromBitmap(bitmap, lut) {
      var k2 = 0;
      for (var i2 = 0; i2 < USHORT_RANGE; ++i2) {
        if (i2 == 0 || bitmap[i2 >> 3] & 1 << (i2 & 7)) {
          lut[k2++] = i2;
        }
      }
      var n2 = k2 - 1;
      while (k2 < USHORT_RANGE)
        lut[k2++] = 0;
      return n2;
    }
    function hufClearDecTable(hdec) {
      for (var i2 = 0; i2 < HUF_DECSIZE; i2++) {
        hdec[i2] = {};
        hdec[i2].len = 0;
        hdec[i2].lit = 0;
        hdec[i2].p = null;
      }
    }
    const getBitsReturn = { l: 0, c: 0, lc: 0 };
    function getBits(nBits, c2, lc, uInt8Array2, inOffset) {
      while (lc < nBits) {
        c2 = c2 << 8 | parseUint8Array(uInt8Array2, inOffset);
        lc += 8;
      }
      lc -= nBits;
      getBitsReturn.l = c2 >> lc & (1 << nBits) - 1;
      getBitsReturn.c = c2;
      getBitsReturn.lc = lc;
    }
    const hufTableBuffer = new Array(59);
    function hufCanonicalCodeTable(hcode) {
      for (var i2 = 0; i2 <= 58; ++i2)
        hufTableBuffer[i2] = 0;
      for (var i2 = 0; i2 < HUF_ENCSIZE; ++i2)
        hufTableBuffer[hcode[i2]] += 1;
      var c2 = 0;
      for (var i2 = 58; i2 > 0; --i2) {
        var nc = c2 + hufTableBuffer[i2] >> 1;
        hufTableBuffer[i2] = c2;
        c2 = nc;
      }
      for (var i2 = 0; i2 < HUF_ENCSIZE; ++i2) {
        var l2 = hcode[i2];
        if (l2 > 0)
          hcode[i2] = l2 | hufTableBuffer[l2]++ << 6;
      }
    }
    function hufUnpackEncTable(uInt8Array2, inDataView, inOffset, ni, im, iM, hcode) {
      var p2 = inOffset;
      var c2 = 0;
      var lc = 0;
      for (; im <= iM; im++) {
        if (p2.value - inOffset.value > ni)
          return false;
        getBits(6, c2, lc, uInt8Array2, p2);
        var l2 = getBitsReturn.l;
        c2 = getBitsReturn.c;
        lc = getBitsReturn.lc;
        hcode[im] = l2;
        if (l2 == LONG_ZEROCODE_RUN) {
          if (p2.value - inOffset.value > ni) {
            throw "Something wrong with hufUnpackEncTable";
          }
          getBits(8, c2, lc, uInt8Array2, p2);
          var zerun = getBitsReturn.l + SHORTEST_LONG_RUN;
          c2 = getBitsReturn.c;
          lc = getBitsReturn.lc;
          if (im + zerun > iM + 1) {
            throw "Something wrong with hufUnpackEncTable";
          }
          while (zerun--)
            hcode[im++] = 0;
          im--;
        } else if (l2 >= SHORT_ZEROCODE_RUN) {
          var zerun = l2 - SHORT_ZEROCODE_RUN + 2;
          if (im + zerun > iM + 1) {
            throw "Something wrong with hufUnpackEncTable";
          }
          while (zerun--)
            hcode[im++] = 0;
          im--;
        }
      }
      hufCanonicalCodeTable(hcode);
    }
    function hufLength(code) {
      return code & 63;
    }
    function hufCode(code) {
      return code >> 6;
    }
    function hufBuildDecTable(hcode, im, iM, hdecod) {
      for (; im <= iM; im++) {
        var c2 = hufCode(hcode[im]);
        var l2 = hufLength(hcode[im]);
        if (c2 >> l2) {
          throw "Invalid table entry";
        }
        if (l2 > HUF_DECBITS) {
          var pl = hdecod[c2 >> l2 - HUF_DECBITS];
          if (pl.len) {
            throw "Invalid table entry";
          }
          pl.lit++;
          if (pl.p) {
            var p2 = pl.p;
            pl.p = new Array(pl.lit);
            for (var i2 = 0; i2 < pl.lit - 1; ++i2) {
              pl.p[i2] = p2[i2];
            }
          } else {
            pl.p = new Array(1);
          }
          pl.p[pl.lit - 1] = im;
        } else if (l2) {
          var plOffset = 0;
          for (var i2 = 1 << HUF_DECBITS - l2; i2 > 0; i2--) {
            var pl = hdecod[(c2 << HUF_DECBITS - l2) + plOffset];
            if (pl.len || pl.p) {
              throw "Invalid table entry";
            }
            pl.len = l2;
            pl.lit = im;
            plOffset++;
          }
        }
      }
      return true;
    }
    const getCharReturn = { c: 0, lc: 0 };
    function getChar(c2, lc, uInt8Array2, inOffset) {
      c2 = c2 << 8 | parseUint8Array(uInt8Array2, inOffset);
      lc += 8;
      getCharReturn.c = c2;
      getCharReturn.lc = lc;
    }
    const getCodeReturn = { c: 0, lc: 0 };
    function getCode(po, rlc, c2, lc, uInt8Array2, inDataView, inOffset, outBuffer, outBufferOffset, outBufferEndOffset) {
      if (po == rlc) {
        if (lc < 8) {
          getChar(c2, lc, uInt8Array2, inOffset);
          c2 = getCharReturn.c;
          lc = getCharReturn.lc;
        }
        lc -= 8;
        var cs = c2 >> lc;
        var cs = new Uint8Array([cs])[0];
        if (outBufferOffset.value + cs > outBufferEndOffset) {
          return false;
        }
        var s2 = outBuffer[outBufferOffset.value - 1];
        while (cs-- > 0) {
          outBuffer[outBufferOffset.value++] = s2;
        }
      } else if (outBufferOffset.value < outBufferEndOffset) {
        outBuffer[outBufferOffset.value++] = po;
      } else {
        return false;
      }
      getCodeReturn.c = c2;
      getCodeReturn.lc = lc;
    }
    function UInt16(value) {
      return value & 65535;
    }
    function Int16(value) {
      var ref = UInt16(value);
      return ref > 32767 ? ref - 65536 : ref;
    }
    const wdec14Return = { a: 0, b: 0 };
    function wdec14(l2, h2) {
      var ls = Int16(l2);
      var hs = Int16(h2);
      var hi = hs;
      var ai = ls + (hi & 1) + (hi >> 1);
      var as = ai;
      var bs = ai - hi;
      wdec14Return.a = as;
      wdec14Return.b = bs;
    }
    function wdec16(l2, h2) {
      var m2 = UInt16(l2);
      var d2 = UInt16(h2);
      var bb = m2 - (d2 >> 1) & MOD_MASK;
      var aa = d2 + bb - A_OFFSET & MOD_MASK;
      wdec14Return.a = aa;
      wdec14Return.b = bb;
    }
    function wav2Decode(buffer2, j2, nx, ox, ny, oy, mx) {
      var w14 = mx < 1 << 14;
      var n2 = nx > ny ? ny : nx;
      var p2 = 1;
      var p22;
      while (p2 <= n2)
        p2 <<= 1;
      p2 >>= 1;
      p22 = p2;
      p2 >>= 1;
      while (p2 >= 1) {
        var py2 = 0;
        var ey = py2 + oy * (ny - p22);
        var oy1 = oy * p2;
        var oy2 = oy * p22;
        var ox1 = ox * p2;
        var ox2 = ox * p22;
        var i00, i01, i10, i11;
        for (; py2 <= ey; py2 += oy2) {
          var px2 = py2;
          var ex = py2 + ox * (nx - p22);
          for (; px2 <= ex; px2 += ox2) {
            var p01 = px2 + ox1;
            var p10 = px2 + oy1;
            var p11 = p10 + ox1;
            if (w14) {
              wdec14(buffer2[px2 + j2], buffer2[p10 + j2]);
              i00 = wdec14Return.a;
              i10 = wdec14Return.b;
              wdec14(buffer2[p01 + j2], buffer2[p11 + j2]);
              i01 = wdec14Return.a;
              i11 = wdec14Return.b;
              wdec14(i00, i01);
              buffer2[px2 + j2] = wdec14Return.a;
              buffer2[p01 + j2] = wdec14Return.b;
              wdec14(i10, i11);
              buffer2[p10 + j2] = wdec14Return.a;
              buffer2[p11 + j2] = wdec14Return.b;
            } else {
              wdec16(buffer2[px2 + j2], buffer2[p10 + j2]);
              i00 = wdec14Return.a;
              i10 = wdec14Return.b;
              wdec16(buffer2[p01 + j2], buffer2[p11 + j2]);
              i01 = wdec14Return.a;
              i11 = wdec14Return.b;
              wdec16(i00, i01);
              buffer2[px2 + j2] = wdec14Return.a;
              buffer2[p01 + j2] = wdec14Return.b;
              wdec16(i10, i11);
              buffer2[p10 + j2] = wdec14Return.a;
              buffer2[p11 + j2] = wdec14Return.b;
            }
          }
          if (nx & p2) {
            var p10 = px2 + oy1;
            if (w14)
              wdec14(buffer2[px2 + j2], buffer2[p10 + j2]);
            else
              wdec16(buffer2[px2 + j2], buffer2[p10 + j2]);
            i00 = wdec14Return.a;
            buffer2[p10 + j2] = wdec14Return.b;
            buffer2[px2 + j2] = i00;
          }
        }
        if (ny & p2) {
          var px2 = py2;
          var ex = py2 + ox * (nx - p22);
          for (; px2 <= ex; px2 += ox2) {
            var p01 = px2 + ox1;
            if (w14)
              wdec14(buffer2[px2 + j2], buffer2[p01 + j2]);
            else
              wdec16(buffer2[px2 + j2], buffer2[p01 + j2]);
            i00 = wdec14Return.a;
            buffer2[p01 + j2] = wdec14Return.b;
            buffer2[px2 + j2] = i00;
          }
        }
        p22 = p2;
        p2 >>= 1;
      }
      return py2;
    }
    function hufDecode(encodingTable, decodingTable, uInt8Array2, inDataView, inOffset, ni, rlc, no, outBuffer, outOffset) {
      var c2 = 0;
      var lc = 0;
      var outBufferEndOffset = no;
      var inOffsetEnd = Math.trunc(inOffset.value + (ni + 7) / 8);
      while (inOffset.value < inOffsetEnd) {
        getChar(c2, lc, uInt8Array2, inOffset);
        c2 = getCharReturn.c;
        lc = getCharReturn.lc;
        while (lc >= HUF_DECBITS) {
          var index = c2 >> lc - HUF_DECBITS & HUF_DECMASK;
          var pl = decodingTable[index];
          if (pl.len) {
            lc -= pl.len;
            getCode(pl.lit, rlc, c2, lc, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset);
            c2 = getCodeReturn.c;
            lc = getCodeReturn.lc;
          } else {
            if (!pl.p) {
              throw "hufDecode issues";
            }
            var j2;
            for (j2 = 0; j2 < pl.lit; j2++) {
              var l2 = hufLength(encodingTable[pl.p[j2]]);
              while (lc < l2 && inOffset.value < inOffsetEnd) {
                getChar(c2, lc, uInt8Array2, inOffset);
                c2 = getCharReturn.c;
                lc = getCharReturn.lc;
              }
              if (lc >= l2) {
                if (hufCode(encodingTable[pl.p[j2]]) == (c2 >> lc - l2 & (1 << l2) - 1)) {
                  lc -= l2;
                  getCode(
                    pl.p[j2],
                    rlc,
                    c2,
                    lc,
                    uInt8Array2,
                    inDataView,
                    inOffset,
                    outBuffer,
                    outOffset,
                    outBufferEndOffset
                  );
                  c2 = getCodeReturn.c;
                  lc = getCodeReturn.lc;
                  break;
                }
              }
            }
            if (j2 == pl.lit) {
              throw "hufDecode issues";
            }
          }
        }
      }
      var i2 = 8 - ni & 7;
      c2 >>= i2;
      lc -= i2;
      while (lc > 0) {
        var pl = decodingTable[c2 << HUF_DECBITS - lc & HUF_DECMASK];
        if (pl.len) {
          lc -= pl.len;
          getCode(pl.lit, rlc, c2, lc, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset);
          c2 = getCodeReturn.c;
          lc = getCodeReturn.lc;
        } else {
          throw "hufDecode issues";
        }
      }
      return true;
    }
    function hufUncompress(uInt8Array2, inDataView, inOffset, nCompressed, outBuffer, nRaw) {
      var outOffset = { value: 0 };
      var initialInOffset = inOffset.value;
      var im = parseUint32(inDataView, inOffset);
      var iM = parseUint32(inDataView, inOffset);
      inOffset.value += 4;
      var nBits = parseUint32(inDataView, inOffset);
      inOffset.value += 4;
      if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) {
        throw "Something wrong with HUF_ENCSIZE";
      }
      var freq = new Array(HUF_ENCSIZE);
      var hdec = new Array(HUF_DECSIZE);
      hufClearDecTable(hdec);
      var ni = nCompressed - (inOffset.value - initialInOffset);
      hufUnpackEncTable(uInt8Array2, inDataView, inOffset, ni, im, iM, freq);
      if (nBits > 8 * (nCompressed - (inOffset.value - initialInOffset))) {
        throw "Something wrong with hufUncompress";
      }
      hufBuildDecTable(freq, im, iM, hdec);
      hufDecode(freq, hdec, uInt8Array2, inDataView, inOffset, nBits, iM, nRaw, outBuffer, outOffset);
    }
    function applyLut(lut, data, nData) {
      for (var i2 = 0; i2 < nData; ++i2) {
        data[i2] = lut[data[i2]];
      }
    }
    function predictor(source) {
      for (var t2 = 1; t2 < source.length; t2++) {
        var d2 = source[t2 - 1] + source[t2] - 128;
        source[t2] = d2;
      }
    }
    function interleaveScalar(source, out) {
      var t1 = 0;
      var t2 = Math.floor((source.length + 1) / 2);
      var s2 = 0;
      var stop = source.length - 1;
      while (true) {
        if (s2 > stop)
          break;
        out[s2++] = source[t1++];
        if (s2 > stop)
          break;
        out[s2++] = source[t2++];
      }
    }
    function decodeRunLength(source) {
      var size = source.byteLength;
      var out = new Array();
      var p2 = 0;
      var reader = new DataView(source);
      while (size > 0) {
        var l2 = reader.getInt8(p2++);
        if (l2 < 0) {
          var count = -l2;
          size -= count + 1;
          for (var i2 = 0; i2 < count; i2++) {
            out.push(reader.getUint8(p2++));
          }
        } else {
          var count = l2;
          size -= 2;
          var value = reader.getUint8(p2++);
          for (var i2 = 0; i2 < count + 1; i2++) {
            out.push(value);
          }
        }
      }
      return out;
    }
    function lossyDctDecode(cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer) {
      var dataView = new DataView(outBuffer.buffer);
      var width = channelData[cscSet.idx[0]].width;
      var height = channelData[cscSet.idx[0]].height;
      var numComp = 3;
      var numFullBlocksX = Math.floor(width / 8);
      var numBlocksX = Math.ceil(width / 8);
      var numBlocksY = Math.ceil(height / 8);
      var leftoverX = width - (numBlocksX - 1) * 8;
      var leftoverY = height - (numBlocksY - 1) * 8;
      var currAcComp = { value: 0 };
      var currDcComp = new Array(numComp);
      var dctData = new Array(numComp);
      var halfZigBlock = new Array(numComp);
      var rowBlock = new Array(numComp);
      var rowOffsets = new Array(numComp);
      for (let comp2 = 0; comp2 < numComp; ++comp2) {
        rowOffsets[comp2] = rowPtrs[cscSet.idx[comp2]];
        currDcComp[comp2] = comp2 < 1 ? 0 : currDcComp[comp2 - 1] + numBlocksX * numBlocksY;
        dctData[comp2] = new Float32Array(64);
        halfZigBlock[comp2] = new Uint16Array(64);
        rowBlock[comp2] = new Uint16Array(numBlocksX * 64);
      }
      for (let blocky = 0; blocky < numBlocksY; ++blocky) {
        var maxY = 8;
        if (blocky == numBlocksY - 1)
          maxY = leftoverY;
        var maxX = 8;
        for (let blockx = 0; blockx < numBlocksX; ++blockx) {
          if (blockx == numBlocksX - 1)
            maxX = leftoverX;
          for (let comp2 = 0; comp2 < numComp; ++comp2) {
            halfZigBlock[comp2].fill(0);
            halfZigBlock[comp2][0] = dcBuffer[currDcComp[comp2]++];
            unRleAC(currAcComp, acBuffer, halfZigBlock[comp2]);
            unZigZag(halfZigBlock[comp2], dctData[comp2]);
            dctInverse(dctData[comp2]);
          }
          {
            csc709Inverse(dctData);
          }
          for (let comp2 = 0; comp2 < numComp; ++comp2) {
            convertToHalf(dctData[comp2], rowBlock[comp2], blockx * 64);
          }
        }
        let offset2 = 0;
        for (let comp2 = 0; comp2 < numComp; ++comp2) {
          const type2 = channelData[cscSet.idx[comp2]].type;
          for (let y22 = 8 * blocky; y22 < 8 * blocky + maxY; ++y22) {
            offset2 = rowOffsets[comp2][y22];
            for (let blockx = 0; blockx < numFullBlocksX; ++blockx) {
              const src = blockx * 64 + (y22 & 7) * 8;
              dataView.setUint16(offset2 + 0 * INT16_SIZE * type2, rowBlock[comp2][src + 0], true);
              dataView.setUint16(offset2 + 1 * INT16_SIZE * type2, rowBlock[comp2][src + 1], true);
              dataView.setUint16(offset2 + 2 * INT16_SIZE * type2, rowBlock[comp2][src + 2], true);
              dataView.setUint16(offset2 + 3 * INT16_SIZE * type2, rowBlock[comp2][src + 3], true);
              dataView.setUint16(offset2 + 4 * INT16_SIZE * type2, rowBlock[comp2][src + 4], true);
              dataView.setUint16(offset2 + 5 * INT16_SIZE * type2, rowBlock[comp2][src + 5], true);
              dataView.setUint16(offset2 + 6 * INT16_SIZE * type2, rowBlock[comp2][src + 6], true);
              dataView.setUint16(offset2 + 7 * INT16_SIZE * type2, rowBlock[comp2][src + 7], true);
              offset2 += 8 * INT16_SIZE * type2;
            }
          }
          if (numFullBlocksX != numBlocksX) {
            for (let y22 = 8 * blocky; y22 < 8 * blocky + maxY; ++y22) {
              const offset3 = rowOffsets[comp2][y22] + 8 * numFullBlocksX * INT16_SIZE * type2;
              const src = numFullBlocksX * 64 + (y22 & 7) * 8;
              for (let x2 = 0; x2 < maxX; ++x2) {
                dataView.setUint16(offset3 + x2 * INT16_SIZE * type2, rowBlock[comp2][src + x2], true);
              }
            }
          }
        }
      }
      var halfRow = new Uint16Array(width);
      var dataView = new DataView(outBuffer.buffer);
      for (var comp = 0; comp < numComp; ++comp) {
        channelData[cscSet.idx[comp]].decoded = true;
        var type = channelData[cscSet.idx[comp]].type;
        if (channelData[comp].type != 2)
          continue;
        for (var y2 = 0; y2 < height; ++y2) {
          const offset2 = rowOffsets[comp][y2];
          for (var x = 0; x < width; ++x) {
            halfRow[x] = dataView.getUint16(offset2 + x * INT16_SIZE * type, true);
          }
          for (var x = 0; x < width; ++x) {
            dataView.setFloat32(offset2 + x * INT16_SIZE * type, decodeFloat16(halfRow[x]), true);
          }
        }
      }
    }
    function unRleAC(currAcComp, acBuffer, halfZigBlock) {
      var acValue;
      var dctComp = 1;
      while (dctComp < 64) {
        acValue = acBuffer[currAcComp.value];
        if (acValue == 65280) {
          dctComp = 64;
        } else if (acValue >> 8 == 255) {
          dctComp += acValue & 255;
        } else {
          halfZigBlock[dctComp] = acValue;
          dctComp++;
        }
        currAcComp.value++;
      }
    }
    function unZigZag(src, dst) {
      dst[0] = decodeFloat16(src[0]);
      dst[1] = decodeFloat16(src[1]);
      dst[2] = decodeFloat16(src[5]);
      dst[3] = decodeFloat16(src[6]);
      dst[4] = decodeFloat16(src[14]);
      dst[5] = decodeFloat16(src[15]);
      dst[6] = decodeFloat16(src[27]);
      dst[7] = decodeFloat16(src[28]);
      dst[8] = decodeFloat16(src[2]);
      dst[9] = decodeFloat16(src[4]);
      dst[10] = decodeFloat16(src[7]);
      dst[11] = decodeFloat16(src[13]);
      dst[12] = decodeFloat16(src[16]);
      dst[13] = decodeFloat16(src[26]);
      dst[14] = decodeFloat16(src[29]);
      dst[15] = decodeFloat16(src[42]);
      dst[16] = decodeFloat16(src[3]);
      dst[17] = decodeFloat16(src[8]);
      dst[18] = decodeFloat16(src[12]);
      dst[19] = decodeFloat16(src[17]);
      dst[20] = decodeFloat16(src[25]);
      dst[21] = decodeFloat16(src[30]);
      dst[22] = decodeFloat16(src[41]);
      dst[23] = decodeFloat16(src[43]);
      dst[24] = decodeFloat16(src[9]);
      dst[25] = decodeFloat16(src[11]);
      dst[26] = decodeFloat16(src[18]);
      dst[27] = decodeFloat16(src[24]);
      dst[28] = decodeFloat16(src[31]);
      dst[29] = decodeFloat16(src[40]);
      dst[30] = decodeFloat16(src[44]);
      dst[31] = decodeFloat16(src[53]);
      dst[32] = decodeFloat16(src[10]);
      dst[33] = decodeFloat16(src[19]);
      dst[34] = decodeFloat16(src[23]);
      dst[35] = decodeFloat16(src[32]);
      dst[36] = decodeFloat16(src[39]);
      dst[37] = decodeFloat16(src[45]);
      dst[38] = decodeFloat16(src[52]);
      dst[39] = decodeFloat16(src[54]);
      dst[40] = decodeFloat16(src[20]);
      dst[41] = decodeFloat16(src[22]);
      dst[42] = decodeFloat16(src[33]);
      dst[43] = decodeFloat16(src[38]);
      dst[44] = decodeFloat16(src[46]);
      dst[45] = decodeFloat16(src[51]);
      dst[46] = decodeFloat16(src[55]);
      dst[47] = decodeFloat16(src[60]);
      dst[48] = decodeFloat16(src[21]);
      dst[49] = decodeFloat16(src[34]);
      dst[50] = decodeFloat16(src[37]);
      dst[51] = decodeFloat16(src[47]);
      dst[52] = decodeFloat16(src[50]);
      dst[53] = decodeFloat16(src[56]);
      dst[54] = decodeFloat16(src[59]);
      dst[55] = decodeFloat16(src[61]);
      dst[56] = decodeFloat16(src[35]);
      dst[57] = decodeFloat16(src[36]);
      dst[58] = decodeFloat16(src[48]);
      dst[59] = decodeFloat16(src[49]);
      dst[60] = decodeFloat16(src[57]);
      dst[61] = decodeFloat16(src[58]);
      dst[62] = decodeFloat16(src[62]);
      dst[63] = decodeFloat16(src[63]);
    }
    function dctInverse(data) {
      const a3 = 0.5 * Math.cos(3.14159 / 4);
      const b2 = 0.5 * Math.cos(3.14159 / 16);
      const c2 = 0.5 * Math.cos(3.14159 / 8);
      const d2 = 0.5 * Math.cos(3 * 3.14159 / 16);
      const e2 = 0.5 * Math.cos(5 * 3.14159 / 16);
      const f2 = 0.5 * Math.cos(3 * 3.14159 / 8);
      const g2 = 0.5 * Math.cos(7 * 3.14159 / 16);
      var alpha = new Array(4);
      var beta = new Array(4);
      var theta = new Array(4);
      var gamma = new Array(4);
      for (var row = 0; row < 8; ++row) {
        var rowPtr = row * 8;
        alpha[0] = c2 * data[rowPtr + 2];
        alpha[1] = f2 * data[rowPtr + 2];
        alpha[2] = c2 * data[rowPtr + 6];
        alpha[3] = f2 * data[rowPtr + 6];
        beta[0] = b2 * data[rowPtr + 1] + d2 * data[rowPtr + 3] + e2 * data[rowPtr + 5] + g2 * data[rowPtr + 7];
        beta[1] = d2 * data[rowPtr + 1] - g2 * data[rowPtr + 3] - b2 * data[rowPtr + 5] - e2 * data[rowPtr + 7];
        beta[2] = e2 * data[rowPtr + 1] - b2 * data[rowPtr + 3] + g2 * data[rowPtr + 5] + d2 * data[rowPtr + 7];
        beta[3] = g2 * data[rowPtr + 1] - e2 * data[rowPtr + 3] + d2 * data[rowPtr + 5] - b2 * data[rowPtr + 7];
        theta[0] = a3 * (data[rowPtr + 0] + data[rowPtr + 4]);
        theta[3] = a3 * (data[rowPtr + 0] - data[rowPtr + 4]);
        theta[1] = alpha[0] + alpha[3];
        theta[2] = alpha[1] - alpha[2];
        gamma[0] = theta[0] + theta[1];
        gamma[1] = theta[3] + theta[2];
        gamma[2] = theta[3] - theta[2];
        gamma[3] = theta[0] - theta[1];
        data[rowPtr + 0] = gamma[0] + beta[0];
        data[rowPtr + 1] = gamma[1] + beta[1];
        data[rowPtr + 2] = gamma[2] + beta[2];
        data[rowPtr + 3] = gamma[3] + beta[3];
        data[rowPtr + 4] = gamma[3] - beta[3];
        data[rowPtr + 5] = gamma[2] - beta[2];
        data[rowPtr + 6] = gamma[1] - beta[1];
        data[rowPtr + 7] = gamma[0] - beta[0];
      }
      for (var column = 0; column < 8; ++column) {
        alpha[0] = c2 * data[16 + column];
        alpha[1] = f2 * data[16 + column];
        alpha[2] = c2 * data[48 + column];
        alpha[3] = f2 * data[48 + column];
        beta[0] = b2 * data[8 + column] + d2 * data[24 + column] + e2 * data[40 + column] + g2 * data[56 + column];
        beta[1] = d2 * data[8 + column] - g2 * data[24 + column] - b2 * data[40 + column] - e2 * data[56 + column];
        beta[2] = e2 * data[8 + column] - b2 * data[24 + column] + g2 * data[40 + column] + d2 * data[56 + column];
        beta[3] = g2 * data[8 + column] - e2 * data[24 + column] + d2 * data[40 + column] - b2 * data[56 + column];
        theta[0] = a3 * (data[column] + data[32 + column]);
        theta[3] = a3 * (data[column] - data[32 + column]);
        theta[1] = alpha[0] + alpha[3];
        theta[2] = alpha[1] - alpha[2];
        gamma[0] = theta[0] + theta[1];
        gamma[1] = theta[3] + theta[2];
        gamma[2] = theta[3] - theta[2];
        gamma[3] = theta[0] - theta[1];
        data[0 + column] = gamma[0] + beta[0];
        data[8 + column] = gamma[1] + beta[1];
        data[16 + column] = gamma[2] + beta[2];
        data[24 + column] = gamma[3] + beta[3];
        data[32 + column] = gamma[3] - beta[3];
        data[40 + column] = gamma[2] - beta[2];
        data[48 + column] = gamma[1] - beta[1];
        data[56 + column] = gamma[0] - beta[0];
      }
    }
    function csc709Inverse(data) {
      for (var i2 = 0; i2 < 64; ++i2) {
        var y2 = data[0][i2];
        var cb = data[1][i2];
        var cr = data[2][i2];
        data[0][i2] = y2 + 1.5747 * cr;
        data[1][i2] = y2 - 0.1873 * cb - 0.4682 * cr;
        data[2][i2] = y2 + 1.8556 * cb;
      }
    }
    function convertToHalf(src, dst, idx) {
      for (var i2 = 0; i2 < 64; ++i2) {
        dst[idx + i2] = DataUtils.toHalfFloat(toLinear(src[i2]));
      }
    }
    function toLinear(float) {
      if (float <= 1) {
        return Math.sign(float) * Math.pow(Math.abs(float), 2.2);
      } else {
        return Math.sign(float) * Math.pow(logBase, Math.abs(float) - 1);
      }
    }
    function uncompressRAW(info) {
      return new DataView(info.array.buffer, info.offset.value, info.size);
    }
    function uncompressRLE(info) {
      var compressed = info.viewer.buffer.slice(info.offset.value, info.offset.value + info.size);
      var rawBuffer = new Uint8Array(decodeRunLength(compressed));
      var tmpBuffer = new Uint8Array(rawBuffer.length);
      predictor(rawBuffer);
      interleaveScalar(rawBuffer, tmpBuffer);
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressZIP(info) {
      var compressed = info.array.slice(info.offset.value, info.offset.value + info.size);
      var rawBuffer = unzlibSync(compressed);
      var tmpBuffer = new Uint8Array(rawBuffer.length);
      predictor(rawBuffer);
      interleaveScalar(rawBuffer, tmpBuffer);
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressPIZ(info) {
      var inDataView = info.viewer;
      var inOffset = { value: info.offset.value };
      var outBuffer = new Uint16Array(info.width * info.scanlineBlockSize * (info.channels * info.type));
      var bitmap = new Uint8Array(BITMAP_SIZE);
      var outBufferEnd = 0;
      var pizChannelData = new Array(info.channels);
      for (var i2 = 0; i2 < info.channels; i2++) {
        pizChannelData[i2] = {};
        pizChannelData[i2]["start"] = outBufferEnd;
        pizChannelData[i2]["end"] = pizChannelData[i2]["start"];
        pizChannelData[i2]["nx"] = info.width;
        pizChannelData[i2]["ny"] = info.lines;
        pizChannelData[i2]["size"] = info.type;
        outBufferEnd += pizChannelData[i2].nx * pizChannelData[i2].ny * pizChannelData[i2].size;
      }
      var minNonZero = parseUint16(inDataView, inOffset);
      var maxNonZero = parseUint16(inDataView, inOffset);
      if (maxNonZero >= BITMAP_SIZE) {
        throw "Something is wrong with PIZ_COMPRESSION BITMAP_SIZE";
      }
      if (minNonZero <= maxNonZero) {
        for (var i2 = 0; i2 < maxNonZero - minNonZero + 1; i2++) {
          bitmap[i2 + minNonZero] = parseUint8(inDataView, inOffset);
        }
      }
      var lut = new Uint16Array(USHORT_RANGE);
      var maxValue = reverseLutFromBitmap(bitmap, lut);
      var length = parseUint32(inDataView, inOffset);
      hufUncompress(info.array, inDataView, inOffset, length, outBuffer, outBufferEnd);
      for (var i2 = 0; i2 < info.channels; ++i2) {
        var cd = pizChannelData[i2];
        for (var j2 = 0; j2 < pizChannelData[i2].size; ++j2) {
          wav2Decode(outBuffer, cd.start + j2, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue);
        }
      }
      applyLut(lut, outBuffer, outBufferEnd);
      var tmpOffset2 = 0;
      var tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength);
      for (var y2 = 0; y2 < info.lines; y2++) {
        for (var c2 = 0; c2 < info.channels; c2++) {
          var cd = pizChannelData[c2];
          var n2 = cd.nx * cd.size;
          var cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n2 * INT16_SIZE);
          tmpBuffer.set(cp, tmpOffset2);
          tmpOffset2 += n2 * INT16_SIZE;
          cd.end += n2;
        }
      }
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressPXR(info) {
      var compressed = info.array.slice(info.offset.value, info.offset.value + info.size);
      var rawBuffer = unzlibSync(compressed);
      const sz = info.lines * info.channels * info.width;
      const tmpBuffer = info.type == 1 ? new Uint16Array(sz) : new Uint32Array(sz);
      let tmpBufferEnd = 0;
      let writePtr = 0;
      const ptr = new Array(4);
      for (let y2 = 0; y2 < info.lines; y2++) {
        for (let c2 = 0; c2 < info.channels; c2++) {
          let pixel = 0;
          switch (info.type) {
            case 1:
              ptr[0] = tmpBufferEnd;
              ptr[1] = ptr[0] + info.width;
              tmpBufferEnd = ptr[1] + info.width;
              for (let j2 = 0; j2 < info.width; ++j2) {
                const diff = rawBuffer[ptr[0]++] << 8 | rawBuffer[ptr[1]++];
                pixel += diff;
                tmpBuffer[writePtr] = pixel;
                writePtr++;
              }
              break;
            case 2:
              ptr[0] = tmpBufferEnd;
              ptr[1] = ptr[0] + info.width;
              ptr[2] = ptr[1] + info.width;
              tmpBufferEnd = ptr[2] + info.width;
              for (let j2 = 0; j2 < info.width; ++j2) {
                const diff = rawBuffer[ptr[0]++] << 24 | rawBuffer[ptr[1]++] << 16 | rawBuffer[ptr[2]++] << 8;
                pixel += diff;
                tmpBuffer[writePtr] = pixel;
                writePtr++;
              }
              break;
          }
        }
      }
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressDWA(info) {
      var inDataView = info.viewer;
      var inOffset = { value: info.offset.value };
      var outBuffer = new Uint8Array(info.width * info.lines * (info.channels * info.type * INT16_SIZE));
      var dwaHeader = {
        version: parseInt64(inDataView, inOffset),
        unknownUncompressedSize: parseInt64(inDataView, inOffset),
        unknownCompressedSize: parseInt64(inDataView, inOffset),
        acCompressedSize: parseInt64(inDataView, inOffset),
        dcCompressedSize: parseInt64(inDataView, inOffset),
        rleCompressedSize: parseInt64(inDataView, inOffset),
        rleUncompressedSize: parseInt64(inDataView, inOffset),
        rleRawSize: parseInt64(inDataView, inOffset),
        totalAcUncompressedCount: parseInt64(inDataView, inOffset),
        totalDcUncompressedCount: parseInt64(inDataView, inOffset),
        acCompression: parseInt64(inDataView, inOffset)
      };
      if (dwaHeader.version < 2) {
        throw "EXRLoader.parse: " + EXRHeader.compression + " version " + dwaHeader.version + " is unsupported";
      }
      var channelRules = new Array();
      var ruleSize = parseUint16(inDataView, inOffset) - INT16_SIZE;
      while (ruleSize > 0) {
        var name = parseNullTerminatedString(inDataView.buffer, inOffset);
        var value = parseUint8(inDataView, inOffset);
        var compression = value >> 2 & 3;
        var csc = (value >> 4) - 1;
        var index = new Int8Array([csc])[0];
        var type = parseUint8(inDataView, inOffset);
        channelRules.push({
          name,
          index,
          type,
          compression
        });
        ruleSize -= name.length + 3;
      }
      var channels = EXRHeader.channels;
      var channelData = new Array(info.channels);
      for (var i2 = 0; i2 < info.channels; ++i2) {
        var cd = channelData[i2] = {};
        var channel = channels[i2];
        cd.name = channel.name;
        cd.compression = UNKNOWN;
        cd.decoded = false;
        cd.type = channel.pixelType;
        cd.pLinear = channel.pLinear;
        cd.width = info.width;
        cd.height = info.lines;
      }
      var cscSet = {
        idx: new Array(3)
      };
      for (var offset2 = 0; offset2 < info.channels; ++offset2) {
        var cd = channelData[offset2];
        for (var i2 = 0; i2 < channelRules.length; ++i2) {
          var rule = channelRules[i2];
          if (cd.name == rule.name) {
            cd.compression = rule.compression;
            if (rule.index >= 0) {
              cscSet.idx[rule.index] = offset2;
            }
            cd.offset = offset2;
          }
        }
      }
      if (dwaHeader.acCompressedSize > 0) {
        switch (dwaHeader.acCompression) {
          case STATIC_HUFFMAN:
            var acBuffer = new Uint16Array(dwaHeader.totalAcUncompressedCount);
            hufUncompress(
              info.array,
              inDataView,
              inOffset,
              dwaHeader.acCompressedSize,
              acBuffer,
              dwaHeader.totalAcUncompressedCount
            );
            break;
          case DEFLATE:
            var compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount);
            var data = unzlibSync(compressed);
            var acBuffer = new Uint16Array(data.buffer);
            inOffset.value += dwaHeader.totalAcUncompressedCount;
            break;
        }
      }
      if (dwaHeader.dcCompressedSize > 0) {
        var zlibInfo = {
          array: info.array,
          offset: inOffset,
          size: dwaHeader.dcCompressedSize
        };
        var dcBuffer = new Uint16Array(uncompressZIP(zlibInfo).buffer);
        inOffset.value += dwaHeader.dcCompressedSize;
      }
      if (dwaHeader.rleRawSize > 0) {
        var compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.rleCompressedSize);
        var data = unzlibSync(compressed);
        var rleBuffer = decodeRunLength(data.buffer);
        inOffset.value += dwaHeader.rleCompressedSize;
      }
      var outBufferEnd = 0;
      var rowOffsets = new Array(channelData.length);
      for (var i2 = 0; i2 < rowOffsets.length; ++i2) {
        rowOffsets[i2] = new Array();
      }
      for (var y2 = 0; y2 < info.lines; ++y2) {
        for (var chan = 0; chan < channelData.length; ++chan) {
          rowOffsets[chan].push(outBufferEnd);
          outBufferEnd += channelData[chan].width * info.type * INT16_SIZE;
        }
      }
      lossyDctDecode(cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer);
      for (var i2 = 0; i2 < channelData.length; ++i2) {
        var cd = channelData[i2];
        if (cd.decoded)
          continue;
        switch (cd.compression) {
          case RLE:
            var row = 0;
            var rleOffset = 0;
            for (var y2 = 0; y2 < info.lines; ++y2) {
              var rowOffsetBytes = rowOffsets[i2][row];
              for (var x = 0; x < cd.width; ++x) {
                for (var byte = 0; byte < INT16_SIZE * cd.type; ++byte) {
                  outBuffer[rowOffsetBytes++] = rleBuffer[rleOffset + byte * cd.width * cd.height];
                }
                rleOffset++;
              }
              row++;
            }
            break;
          case LOSSY_DCT:
          default:
            throw "EXRLoader.parse: unsupported channel compression";
        }
      }
      return new DataView(outBuffer.buffer);
    }
    function parseNullTerminatedString(buffer2, offset2) {
      var uintBuffer = new Uint8Array(buffer2);
      var endOffset = 0;
      while (uintBuffer[offset2.value + endOffset] != 0) {
        endOffset += 1;
      }
      var stringValue = new TextDecoder().decode(uintBuffer.slice(offset2.value, offset2.value + endOffset));
      offset2.value = offset2.value + endOffset + 1;
      return stringValue;
    }
    function parseFixedLengthString(buffer2, offset2, size) {
      var stringValue = new TextDecoder().decode(new Uint8Array(buffer2).slice(offset2.value, offset2.value + size));
      offset2.value = offset2.value + size;
      return stringValue;
    }
    function parseRational(dataView, offset2) {
      var x = parseInt32(dataView, offset2);
      var y2 = parseUint32(dataView, offset2);
      return [x, y2];
    }
    function parseTimecode(dataView, offset2) {
      var x = parseUint32(dataView, offset2);
      var y2 = parseUint32(dataView, offset2);
      return [x, y2];
    }
    function parseInt32(dataView, offset2) {
      var Int32 = dataView.getInt32(offset2.value, true);
      offset2.value = offset2.value + INT32_SIZE;
      return Int32;
    }
    function parseUint32(dataView, offset2) {
      var Uint32 = dataView.getUint32(offset2.value, true);
      offset2.value = offset2.value + INT32_SIZE;
      return Uint32;
    }
    function parseUint8Array(uInt8Array2, offset2) {
      var Uint8 = uInt8Array2[offset2.value];
      offset2.value = offset2.value + INT8_SIZE;
      return Uint8;
    }
    function parseUint8(dataView, offset2) {
      var Uint8 = dataView.getUint8(offset2.value);
      offset2.value = offset2.value + INT8_SIZE;
      return Uint8;
    }
    const parseInt64 = function(dataView, offset2) {
      let int;
      if ("getBigInt64" in DataView.prototype) {
        int = Number(dataView.getBigInt64(offset2.value, true));
      } else {
        int = dataView.getUint32(offset2.value + 4, true) + Number(dataView.getUint32(offset2.value, true) << 32);
      }
      offset2.value += ULONG_SIZE;
      return int;
    };
    function parseFloat32(dataView, offset2) {
      var float = dataView.getFloat32(offset2.value, true);
      offset2.value += FLOAT32_SIZE;
      return float;
    }
    function decodeFloat32(dataView, offset2) {
      return DataUtils.toHalfFloat(parseFloat32(dataView, offset2));
    }
    function decodeFloat16(binary) {
      var exponent = (binary & 31744) >> 10, fraction = binary & 1023;
      return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 6103515625e-14 * (fraction / 1024));
    }
    function parseUint16(dataView, offset2) {
      var Uint16 = dataView.getUint16(offset2.value, true);
      offset2.value += INT16_SIZE;
      return Uint16;
    }
    function parseFloat16(buffer2, offset2) {
      return decodeFloat16(parseUint16(buffer2, offset2));
    }
    function parseChlist(dataView, buffer2, offset2, size) {
      var startOffset = offset2.value;
      var channels = [];
      while (offset2.value < startOffset + size - 1) {
        var name = parseNullTerminatedString(buffer2, offset2);
        var pixelType = parseInt32(dataView, offset2);
        var pLinear = parseUint8(dataView, offset2);
        offset2.value += 3;
        var xSampling = parseInt32(dataView, offset2);
        var ySampling = parseInt32(dataView, offset2);
        channels.push({
          name,
          pixelType,
          pLinear,
          xSampling,
          ySampling
        });
      }
      offset2.value += 1;
      return channels;
    }
    function parseChromaticities(dataView, offset2) {
      var redX = parseFloat32(dataView, offset2);
      var redY = parseFloat32(dataView, offset2);
      var greenX = parseFloat32(dataView, offset2);
      var greenY = parseFloat32(dataView, offset2);
      var blueX = parseFloat32(dataView, offset2);
      var blueY = parseFloat32(dataView, offset2);
      var whiteX = parseFloat32(dataView, offset2);
      var whiteY = parseFloat32(dataView, offset2);
      return {
        redX,
        redY,
        greenX,
        greenY,
        blueX,
        blueY,
        whiteX,
        whiteY
      };
    }
    function parseCompression(dataView, offset2) {
      var compressionCodes = [
        "NO_COMPRESSION",
        "RLE_COMPRESSION",
        "ZIPS_COMPRESSION",
        "ZIP_COMPRESSION",
        "PIZ_COMPRESSION",
        "PXR24_COMPRESSION",
        "B44_COMPRESSION",
        "B44A_COMPRESSION",
        "DWAA_COMPRESSION",
        "DWAB_COMPRESSION"
      ];
      var compression = parseUint8(dataView, offset2);
      return compressionCodes[compression];
    }
    function parseBox2i(dataView, offset2) {
      var xMin = parseUint32(dataView, offset2);
      var yMin = parseUint32(dataView, offset2);
      var xMax = parseUint32(dataView, offset2);
      var yMax = parseUint32(dataView, offset2);
      return { xMin, yMin, xMax, yMax };
    }
    function parseLineOrder(dataView, offset2) {
      var lineOrders = ["INCREASING_Y"];
      var lineOrder = parseUint8(dataView, offset2);
      return lineOrders[lineOrder];
    }
    function parseV2f(dataView, offset2) {
      var x = parseFloat32(dataView, offset2);
      var y2 = parseFloat32(dataView, offset2);
      return [x, y2];
    }
    function parseV3f(dataView, offset2) {
      var x = parseFloat32(dataView, offset2);
      var y2 = parseFloat32(dataView, offset2);
      var z2 = parseFloat32(dataView, offset2);
      return [x, y2, z2];
    }
    function parseValue(dataView, buffer2, offset2, type, size) {
      if (type === "string" || type === "stringvector" || type === "iccProfile") {
        return parseFixedLengthString(buffer2, offset2, size);
      } else if (type === "chlist") {
        return parseChlist(dataView, buffer2, offset2, size);
      } else if (type === "chromaticities") {
        return parseChromaticities(dataView, offset2);
      } else if (type === "compression") {
        return parseCompression(dataView, offset2);
      } else if (type === "box2i") {
        return parseBox2i(dataView, offset2);
      } else if (type === "lineOrder") {
        return parseLineOrder(dataView, offset2);
      } else if (type === "float") {
        return parseFloat32(dataView, offset2);
      } else if (type === "v2f") {
        return parseV2f(dataView, offset2);
      } else if (type === "v3f") {
        return parseV3f(dataView, offset2);
      } else if (type === "int") {
        return parseInt32(dataView, offset2);
      } else if (type === "rational") {
        return parseRational(dataView, offset2);
      } else if (type === "timecode") {
        return parseTimecode(dataView, offset2);
      } else if (type === "preview") {
        offset2.value += size;
        return "skipped";
      } else {
        offset2.value += size;
        return void 0;
      }
    }
    function parseHeader(dataView, buffer2, offset2) {
      const EXRHeader2 = {};
      if (dataView.getUint32(0, true) != 20000630) {
        throw "THREE.EXRLoader: provided file doesn't appear to be in OpenEXR format.";
      }
      EXRHeader2.version = dataView.getUint8(4);
      const spec = dataView.getUint8(5);
      EXRHeader2.spec = {
        singleTile: !!(spec & 2),
        longName: !!(spec & 4),
        deepFormat: !!(spec & 8),
        multiPart: !!(spec & 16)
      };
      offset2.value = 8;
      var keepReading = true;
      while (keepReading) {
        var attributeName = parseNullTerminatedString(buffer2, offset2);
        if (attributeName == 0) {
          keepReading = false;
        } else {
          var attributeType = parseNullTerminatedString(buffer2, offset2);
          var attributeSize = parseUint32(dataView, offset2);
          var attributeValue = parseValue(dataView, buffer2, offset2, attributeType, attributeSize);
          if (attributeValue === void 0) {
            console.warn(`EXRLoader.parse: skipped unknown header attribute type '${attributeType}'.`);
          } else {
            EXRHeader2[attributeName] = attributeValue;
          }
        }
      }
      if ((spec & -5) != 0) {
        console.error("EXRHeader:", EXRHeader2);
        throw "THREE.EXRLoader: provided file is currently unsupported.";
      }
      return EXRHeader2;
    }
    function setupDecoder(EXRHeader2, dataView, uInt8Array2, offset2, outputType) {
      const EXRDecoder2 = {
        size: 0,
        viewer: dataView,
        array: uInt8Array2,
        offset: offset2,
        width: EXRHeader2.dataWindow.xMax - EXRHeader2.dataWindow.xMin + 1,
        height: EXRHeader2.dataWindow.yMax - EXRHeader2.dataWindow.yMin + 1,
        channels: EXRHeader2.channels.length,
        bytesPerLine: null,
        lines: null,
        inputSize: null,
        type: EXRHeader2.channels[0].pixelType,
        uncompress: null,
        getter: null,
        format: null,
        [hasColorSpace ? "colorSpace" : "encoding"]: null
      };
      switch (EXRHeader2.compression) {
        case "NO_COMPRESSION":
          EXRDecoder2.lines = 1;
          EXRDecoder2.uncompress = uncompressRAW;
          break;
        case "RLE_COMPRESSION":
          EXRDecoder2.lines = 1;
          EXRDecoder2.uncompress = uncompressRLE;
          break;
        case "ZIPS_COMPRESSION":
          EXRDecoder2.lines = 1;
          EXRDecoder2.uncompress = uncompressZIP;
          break;
        case "ZIP_COMPRESSION":
          EXRDecoder2.lines = 16;
          EXRDecoder2.uncompress = uncompressZIP;
          break;
        case "PIZ_COMPRESSION":
          EXRDecoder2.lines = 32;
          EXRDecoder2.uncompress = uncompressPIZ;
          break;
        case "PXR24_COMPRESSION":
          EXRDecoder2.lines = 16;
          EXRDecoder2.uncompress = uncompressPXR;
          break;
        case "DWAA_COMPRESSION":
          EXRDecoder2.lines = 32;
          EXRDecoder2.uncompress = uncompressDWA;
          break;
        case "DWAB_COMPRESSION":
          EXRDecoder2.lines = 256;
          EXRDecoder2.uncompress = uncompressDWA;
          break;
        default:
          throw "EXRLoader.parse: " + EXRHeader2.compression + " is unsupported";
      }
      EXRDecoder2.scanlineBlockSize = EXRDecoder2.lines;
      if (EXRDecoder2.type == 1) {
        switch (outputType) {
          case FloatType:
            EXRDecoder2.getter = parseFloat16;
            EXRDecoder2.inputSize = INT16_SIZE;
            break;
          case HalfFloatType:
            EXRDecoder2.getter = parseUint16;
            EXRDecoder2.inputSize = INT16_SIZE;
            break;
        }
      } else if (EXRDecoder2.type == 2) {
        switch (outputType) {
          case FloatType:
            EXRDecoder2.getter = parseFloat32;
            EXRDecoder2.inputSize = FLOAT32_SIZE;
            break;
          case HalfFloatType:
            EXRDecoder2.getter = decodeFloat32;
            EXRDecoder2.inputSize = FLOAT32_SIZE;
        }
      } else {
        throw "EXRLoader.parse: unsupported pixelType " + EXRDecoder2.type + " for " + EXRHeader2.compression + ".";
      }
      EXRDecoder2.blockCount = (EXRHeader2.dataWindow.yMax + 1) / EXRDecoder2.scanlineBlockSize;
      for (var i2 = 0; i2 < EXRDecoder2.blockCount; i2++)
        parseInt64(dataView, offset2);
      EXRDecoder2.outputChannels = EXRDecoder2.channels == 3 ? 4 : EXRDecoder2.channels;
      const size = EXRDecoder2.width * EXRDecoder2.height * EXRDecoder2.outputChannels;
      switch (outputType) {
        case FloatType:
          EXRDecoder2.byteArray = new Float32Array(size);
          if (EXRDecoder2.channels < EXRDecoder2.outputChannels)
            EXRDecoder2.byteArray.fill(1, 0, size);
          break;
        case HalfFloatType:
          EXRDecoder2.byteArray = new Uint16Array(size);
          if (EXRDecoder2.channels < EXRDecoder2.outputChannels)
            EXRDecoder2.byteArray.fill(15360, 0, size);
          break;
        default:
          console.error("THREE.EXRLoader: unsupported type: ", outputType);
          break;
      }
      EXRDecoder2.bytesPerLine = EXRDecoder2.width * EXRDecoder2.inputSize * EXRDecoder2.channels;
      if (EXRDecoder2.outputChannels == 4)
        EXRDecoder2.format = RGBAFormat;
      else
        EXRDecoder2.format = RedFormat;
      if (hasColorSpace)
        EXRDecoder2.colorSpace = "srgb-linear";
      else
        EXRDecoder2.encoding = 3e3;
      return EXRDecoder2;
    }
    const bufferDataView = new DataView(buffer);
    const uInt8Array = new Uint8Array(buffer);
    const offset = { value: 0 };
    const EXRHeader = parseHeader(bufferDataView, buffer, offset);
    const EXRDecoder = setupDecoder(EXRHeader, bufferDataView, uInt8Array, offset, this.type);
    const tmpOffset = { value: 0 };
    const channelOffsets = { R: 0, G: 1, B: 2, A: 3, Y: 0 };
    for (let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.scanlineBlockSize; scanlineBlockIdx++) {
      const line = parseUint32(bufferDataView, offset);
      EXRDecoder.size = parseUint32(bufferDataView, offset);
      EXRDecoder.lines = line + EXRDecoder.scanlineBlockSize > EXRDecoder.height ? EXRDecoder.height - line : EXRDecoder.scanlineBlockSize;
      const isCompressed = EXRDecoder.size < EXRDecoder.lines * EXRDecoder.bytesPerLine;
      const viewer = isCompressed ? EXRDecoder.uncompress(EXRDecoder) : uncompressRAW(EXRDecoder);
      offset.value += EXRDecoder.size;
      for (let line_y = 0; line_y < EXRDecoder.scanlineBlockSize; line_y++) {
        const true_y = line_y + scanlineBlockIdx * EXRDecoder.scanlineBlockSize;
        if (true_y >= EXRDecoder.height)
          break;
        for (let channelID = 0; channelID < EXRDecoder.channels; channelID++) {
          const cOff = channelOffsets[EXRHeader.channels[channelID].name];
          for (let x = 0; x < EXRDecoder.width; x++) {
            tmpOffset.value = (line_y * (EXRDecoder.channels * EXRDecoder.width) + channelID * EXRDecoder.width + x) * EXRDecoder.inputSize;
            const outIndex = (EXRDecoder.height - 1 - true_y) * (EXRDecoder.width * EXRDecoder.outputChannels) + x * EXRDecoder.outputChannels + cOff;
            EXRDecoder.byteArray[outIndex] = EXRDecoder.getter(viewer, tmpOffset);
          }
        }
      }
    }
    return {
      header: EXRHeader,
      width: EXRDecoder.width,
      height: EXRDecoder.height,
      data: EXRDecoder.byteArray,
      format: EXRDecoder.format,
      [hasColorSpace ? "colorSpace" : "encoding"]: EXRDecoder[hasColorSpace ? "colorSpace" : "encoding"],
      type: this.type
    };
  }
  setDataType(value) {
    this.type = value;
    return this;
  }
  load(url, onLoad, onProgress, onError) {
    function onLoadCallback(texture, texData) {
      if (hasColorSpace)
        texture.colorSpace = texData.colorSpace;
      else
        texture.encoding = texData.encoding;
      texture.minFilter = LinearFilter;
      texture.magFilter = LinearFilter;
      texture.generateMipmaps = false;
      texture.flipY = false;
      if (onLoad)
        onLoad(texture, texData);
    }
    return super.load(url, onLoadCallback, onProgress, onError);
  }
}
const _box$1 = /* @__PURE__ */ new Box3();
const _vector = /* @__PURE__ */ new Vector3();
class LineSegmentsGeometry extends InstancedBufferGeometry {
  constructor() {
    super();
    this.isLineSegmentsGeometry = true;
    this.type = "LineSegmentsGeometry";
    const positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0];
    const uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2];
    const index = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(index);
    this.setAttribute("position", new Float32BufferAttribute(positions, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  applyMatrix4(matrix) {
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0) {
      start.applyMatrix4(matrix);
      end.applyMatrix4(matrix);
      start.needsUpdate = true;
    }
    if (this.boundingBox !== null) {
      this.computeBoundingBox();
    }
    if (this.boundingSphere !== null) {
      this.computeBoundingSphere();
    }
    return this;
  }
  setPositions(array) {
    let lineSegments;
    if (array instanceof Float32Array) {
      lineSegments = array;
    } else if (Array.isArray(array)) {
      lineSegments = new Float32Array(array);
    }
    const instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1);
    this.setAttribute("instanceStart", new InterleavedBufferAttribute(instanceBuffer, 3, 0));
    this.setAttribute("instanceEnd", new InterleavedBufferAttribute(instanceBuffer, 3, 3));
    this.computeBoundingBox();
    this.computeBoundingSphere();
    return this;
  }
  setColors(array, itemSize = 3) {
    let colors;
    if (array instanceof Float32Array) {
      colors = array;
    } else if (Array.isArray(array)) {
      colors = new Float32Array(array);
    }
    const instanceColorBuffer = new InstancedInterleavedBuffer(colors, itemSize * 2, 1);
    this.setAttribute("instanceColorStart", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, 0));
    this.setAttribute("instanceColorEnd", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, itemSize));
    return this;
  }
  fromWireframeGeometry(geometry) {
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
  fromEdgesGeometry(geometry) {
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
  fromMesh(mesh) {
    this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry));
    return this;
  }
  fromLineSegments(lineSegments) {
    const geometry = lineSegments.geometry;
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
  computeBoundingBox() {
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0 && end !== void 0) {
      this.boundingBox.setFromBufferAttribute(start);
      _box$1.setFromBufferAttribute(end);
      this.boundingBox.union(_box$1);
    }
  }
  computeBoundingSphere() {
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    if (this.boundingBox === null) {
      this.computeBoundingBox();
    }
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0 && end !== void 0) {
      const center = this.boundingSphere.center;
      this.boundingBox.getCenter(center);
      let maxRadiusSq = 0;
      for (let i2 = 0, il = start.count; i2 < il; i2++) {
        _vector.fromBufferAttribute(start, i2);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector));
        _vector.fromBufferAttribute(end, i2);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector));
      }
      this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
      if (isNaN(this.boundingSphere.radius)) {
        console.error(
          "THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",
          this
        );
      }
    }
  }
  toJSON() {
  }
  applyMatrix(matrix) {
    console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().");
    return this.applyMatrix4(matrix);
  }
}
class LineGeometry extends LineSegmentsGeometry {
  constructor() {
    super();
    this.isLineGeometry = true;
    this.type = "LineGeometry";
  }
  setPositions(array) {
    const length = array.length - 3;
    const points = new Float32Array(2 * length);
    for (let i2 = 0; i2 < length; i2 += 3) {
      points[2 * i2] = array[i2];
      points[2 * i2 + 1] = array[i2 + 1];
      points[2 * i2 + 2] = array[i2 + 2];
      points[2 * i2 + 3] = array[i2 + 3];
      points[2 * i2 + 4] = array[i2 + 4];
      points[2 * i2 + 5] = array[i2 + 5];
    }
    super.setPositions(points);
    return this;
  }
  setColors(array, itemSize = 3) {
    const length = array.length - itemSize;
    const colors = new Float32Array(2 * length);
    if (itemSize === 3) {
      for (let i2 = 0; i2 < length; i2 += itemSize) {
        colors[2 * i2] = array[i2];
        colors[2 * i2 + 1] = array[i2 + 1];
        colors[2 * i2 + 2] = array[i2 + 2];
        colors[2 * i2 + 3] = array[i2 + 3];
        colors[2 * i2 + 4] = array[i2 + 4];
        colors[2 * i2 + 5] = array[i2 + 5];
      }
    } else {
      for (let i2 = 0; i2 < length; i2 += itemSize) {
        colors[2 * i2] = array[i2];
        colors[2 * i2 + 1] = array[i2 + 1];
        colors[2 * i2 + 2] = array[i2 + 2];
        colors[2 * i2 + 3] = array[i2 + 3];
        colors[2 * i2 + 4] = array[i2 + 4];
        colors[2 * i2 + 5] = array[i2 + 5];
        colors[2 * i2 + 6] = array[i2 + 6];
        colors[2 * i2 + 7] = array[i2 + 7];
      }
    }
    super.setColors(colors, itemSize);
    return this;
  }
  fromLine(line) {
    const geometry = line.geometry;
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
}
class LineMaterial extends ShaderMaterial {
  constructor(parameters) {
    super({
      type: "LineMaterial",
      uniforms: UniformsUtils.clone(
        UniformsUtils.merge([
          UniformsLib.common,
          UniformsLib.fog,
          {
            worldUnits: { value: 1 },
            linewidth: { value: 1 },
            resolution: { value: new Vector2(1, 1) },
            dashOffset: { value: 0 },
            dashScale: { value: 1 },
            dashSize: { value: 1 },
            gapSize: { value: 1 }
            // todo FIX - maybe change to totalSize
          }
        ])
      ),
      vertexShader: (
        /* glsl */
        `
				#include <common>
				#include <fog_pars_vertex>
				#include <logdepthbuf_pars_vertex>
				#include <clipping_planes_pars_vertex>

				uniform float linewidth;
				uniform vec2 resolution;

				attribute vec3 instanceStart;
				attribute vec3 instanceEnd;

				#ifdef USE_COLOR
					#ifdef USE_LINE_COLOR_ALPHA
						varying vec4 vLineColor;
						attribute vec4 instanceColorStart;
						attribute vec4 instanceColorEnd;
					#else
						varying vec3 vLineColor;
						attribute vec3 instanceColorStart;
						attribute vec3 instanceColorEnd;
					#endif
				#endif

				#ifdef WORLD_UNITS

					varying vec4 worldPos;
					varying vec3 worldStart;
					varying vec3 worldEnd;

					#ifdef USE_DASH

						varying vec2 vUv;

					#endif

				#else

					varying vec2 vUv;

				#endif

				#ifdef USE_DASH

					uniform float dashScale;
					attribute float instanceDistanceStart;
					attribute float instanceDistanceEnd;
					varying float vLineDistance;

				#endif

				void trimSegment( const in vec4 start, inout vec4 end ) {

					// trim end segment so it terminates between the camera plane and the near plane

					// conservative estimate of the near plane
					float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
					float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
					float nearEstimate = - 0.5 * b / a;

					float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

					end.xyz = mix( start.xyz, end.xyz, alpha );

				}

				void main() {

					#ifdef USE_COLOR

						vLineColor = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

					#endif

					#ifdef USE_DASH

						vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
						vUv = uv;

					#endif

					float aspect = resolution.x / resolution.y;

					// camera space
					vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
					vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

					#ifdef WORLD_UNITS

						worldStart = start.xyz;
						worldEnd = end.xyz;

					#else

						vUv = uv;

					#endif

					// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
					// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
					// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
					// perhaps there is a more elegant solution -- WestLangley

					bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

					if ( perspective ) {

						if ( start.z < 0.0 && end.z >= 0.0 ) {

							trimSegment( start, end );

						} else if ( end.z < 0.0 && start.z >= 0.0 ) {

							trimSegment( end, start );

						}

					}

					// clip space
					vec4 clipStart = projectionMatrix * start;
					vec4 clipEnd = projectionMatrix * end;

					// ndc space
					vec3 ndcStart = clipStart.xyz / clipStart.w;
					vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

					// direction
					vec2 dir = ndcEnd.xy - ndcStart.xy;

					// account for clip-space aspect ratio
					dir.x *= aspect;
					dir = normalize( dir );

					#ifdef WORLD_UNITS

						// get the offset direction as perpendicular to the view vector
						vec3 worldDir = normalize( end.xyz - start.xyz );
						vec3 offset;
						if ( position.y < 0.5 ) {

							offset = normalize( cross( start.xyz, worldDir ) );

						} else {

							offset = normalize( cross( end.xyz, worldDir ) );

						}

						// sign flip
						if ( position.x < 0.0 ) offset *= - 1.0;

						float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );

						// don't extend the line if we're rendering dashes because we
						// won't be rendering the endcaps
						#ifndef USE_DASH

							// extend the line bounds to encompass  endcaps
							start.xyz += - worldDir * linewidth * 0.5;
							end.xyz += worldDir * linewidth * 0.5;

							// shift the position of the quad so it hugs the forward edge of the line
							offset.xy -= dir * forwardOffset;
							offset.z += 0.5;

						#endif

						// endcaps
						if ( position.y > 1.0 || position.y < 0.0 ) {

							offset.xy += dir * 2.0 * forwardOffset;

						}

						// adjust for linewidth
						offset *= linewidth * 0.5;

						// set the world position
						worldPos = ( position.y < 0.5 ) ? start : end;
						worldPos.xyz += offset;

						// project the worldpos
						vec4 clip = projectionMatrix * worldPos;

						// shift the depth of the projected points so the line
						// segments overlap neatly
						vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
						clip.z = clipPose.z * clip.w;

					#else

						vec2 offset = vec2( dir.y, - dir.x );
						// undo aspect ratio adjustment
						dir.x /= aspect;
						offset.x /= aspect;

						// sign flip
						if ( position.x < 0.0 ) offset *= - 1.0;

						// endcaps
						if ( position.y < 0.0 ) {

							offset += - dir;

						} else if ( position.y > 1.0 ) {

							offset += dir;

						}

						// adjust for linewidth
						offset *= linewidth;

						// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
						offset /= resolution.y;

						// select end
						vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

						// back to clip space
						offset *= clip.w;

						clip.xy += offset;

					#endif

					gl_Position = clip;

					vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

					#include <logdepthbuf_vertex>
					#include <clipping_planes_vertex>
					#include <fog_vertex>

				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `
				uniform vec3 diffuse;
				uniform float opacity;
				uniform float linewidth;

				#ifdef USE_DASH

					uniform float dashOffset;
					uniform float dashSize;
					uniform float gapSize;

				#endif

				varying float vLineDistance;

				#ifdef WORLD_UNITS

					varying vec4 worldPos;
					varying vec3 worldStart;
					varying vec3 worldEnd;

					#ifdef USE_DASH

						varying vec2 vUv;

					#endif

				#else

					varying vec2 vUv;

				#endif

				#include <common>
				#include <fog_pars_fragment>
				#include <logdepthbuf_pars_fragment>
				#include <clipping_planes_pars_fragment>

				#ifdef USE_COLOR
					#ifdef USE_LINE_COLOR_ALPHA
						varying vec4 vLineColor;
					#else
						varying vec3 vLineColor;
					#endif
				#endif

				vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

					float mua;
					float mub;

					vec3 p13 = p1 - p3;
					vec3 p43 = p4 - p3;

					vec3 p21 = p2 - p1;

					float d1343 = dot( p13, p43 );
					float d4321 = dot( p43, p21 );
					float d1321 = dot( p13, p21 );
					float d4343 = dot( p43, p43 );
					float d2121 = dot( p21, p21 );

					float denom = d2121 * d4343 - d4321 * d4321;

					float numer = d1343 * d4321 - d1321 * d4343;

					mua = numer / denom;
					mua = clamp( mua, 0.0, 1.0 );
					mub = ( d1343 + d4321 * ( mua ) ) / d4343;
					mub = clamp( mub, 0.0, 1.0 );

					return vec2( mua, mub );

				}

				void main() {

					#include <clipping_planes_fragment>

					#ifdef USE_DASH

						if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

						if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

					#endif

					float alpha = opacity;

					#ifdef WORLD_UNITS

						// Find the closest points on the view ray and the line segment
						vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
						vec3 lineDir = worldEnd - worldStart;
						vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

						vec3 p1 = worldStart + lineDir * params.x;
						vec3 p2 = rayEnd * params.y;
						vec3 delta = p1 - p2;
						float len = length( delta );
						float norm = len / linewidth;

						#ifndef USE_DASH

							#ifdef USE_ALPHA_TO_COVERAGE

								float dnorm = fwidth( norm );
								alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

							#else

								if ( norm > 0.5 ) {

									discard;

								}

							#endif

						#endif

					#else

						#ifdef USE_ALPHA_TO_COVERAGE

							// artifacts appear on some hardware if a derivative is taken within a conditional
							float a = vUv.x;
							float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
							float len2 = a * a + b * b;
							float dlen = fwidth( len2 );

							if ( abs( vUv.y ) > 1.0 ) {

								alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

							}

						#else

							if ( abs( vUv.y ) > 1.0 ) {

								float a = vUv.x;
								float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
								float len2 = a * a + b * b;

								if ( len2 > 1.0 ) discard;

							}

						#endif

					#endif

					vec4 diffuseColor = vec4( diffuse, alpha );
					#ifdef USE_COLOR
						#ifdef USE_LINE_COLOR_ALPHA
							diffuseColor *= vLineColor;
						#else
							diffuseColor.rgb *= vLineColor;
						#endif
					#endif

					#include <logdepthbuf_fragment>

					gl_FragColor = diffuseColor;

					#include <tonemapping_fragment>
					#include <${version$1 >= 154 ? "colorspace_fragment" : "encodings_fragment"}>
					#include <fog_fragment>
					#include <premultiplied_alpha_fragment>

				}
			`
      ),
      clipping: true
      // required for clipping support
    });
    this.isLineMaterial = true;
    this.onBeforeCompile = function() {
      if (this.transparent) {
        this.defines.USE_LINE_COLOR_ALPHA = "1";
      } else {
        delete this.defines.USE_LINE_COLOR_ALPHA;
      }
    };
    Object.defineProperties(this, {
      color: {
        enumerable: true,
        get: function() {
          return this.uniforms.diffuse.value;
        },
        set: function(value) {
          this.uniforms.diffuse.value = value;
        }
      },
      worldUnits: {
        enumerable: true,
        get: function() {
          return "WORLD_UNITS" in this.defines;
        },
        set: function(value) {
          if (value === true) {
            this.defines.WORLD_UNITS = "";
          } else {
            delete this.defines.WORLD_UNITS;
          }
        }
      },
      linewidth: {
        enumerable: true,
        get: function() {
          return this.uniforms.linewidth.value;
        },
        set: function(value) {
          this.uniforms.linewidth.value = value;
        }
      },
      dashed: {
        enumerable: true,
        get: function() {
          return Boolean("USE_DASH" in this.defines);
        },
        set(value) {
          if (Boolean(value) !== Boolean("USE_DASH" in this.defines)) {
            this.needsUpdate = true;
          }
          if (value === true) {
            this.defines.USE_DASH = "";
          } else {
            delete this.defines.USE_DASH;
          }
        }
      },
      dashScale: {
        enumerable: true,
        get: function() {
          return this.uniforms.dashScale.value;
        },
        set: function(value) {
          this.uniforms.dashScale.value = value;
        }
      },
      dashSize: {
        enumerable: true,
        get: function() {
          return this.uniforms.dashSize.value;
        },
        set: function(value) {
          this.uniforms.dashSize.value = value;
        }
      },
      dashOffset: {
        enumerable: true,
        get: function() {
          return this.uniforms.dashOffset.value;
        },
        set: function(value) {
          this.uniforms.dashOffset.value = value;
        }
      },
      gapSize: {
        enumerable: true,
        get: function() {
          return this.uniforms.gapSize.value;
        },
        set: function(value) {
          this.uniforms.gapSize.value = value;
        }
      },
      opacity: {
        enumerable: true,
        get: function() {
          return this.uniforms.opacity.value;
        },
        set: function(value) {
          this.uniforms.opacity.value = value;
        }
      },
      resolution: {
        enumerable: true,
        get: function() {
          return this.uniforms.resolution.value;
        },
        set: function(value) {
          this.uniforms.resolution.value.copy(value);
        }
      },
      alphaToCoverage: {
        enumerable: true,
        get: function() {
          return Boolean("USE_ALPHA_TO_COVERAGE" in this.defines);
        },
        set: function(value) {
          if (Boolean(value) !== Boolean("USE_ALPHA_TO_COVERAGE" in this.defines)) {
            this.needsUpdate = true;
          }
          if (value === true) {
            this.defines.USE_ALPHA_TO_COVERAGE = "";
            this.extensions.derivatives = true;
          } else {
            delete this.defines.USE_ALPHA_TO_COVERAGE;
            this.extensions.derivatives = false;
          }
        }
      }
    });
    this.setValues(parameters);
  }
}
const _viewport = /* @__PURE__ */ new Vector4();
const _start = /* @__PURE__ */ new Vector3();
const _end = /* @__PURE__ */ new Vector3();
const _start4 = /* @__PURE__ */ new Vector4();
const _end4 = /* @__PURE__ */ new Vector4();
const _ssOrigin = /* @__PURE__ */ new Vector4();
const _ssOrigin3 = /* @__PURE__ */ new Vector3();
const _mvMatrix = /* @__PURE__ */ new Matrix4();
const _line = /* @__PURE__ */ new Line3();
const _closestPoint = /* @__PURE__ */ new Vector3();
const _box = /* @__PURE__ */ new Box3();
const _sphere = /* @__PURE__ */ new Sphere();
const _clipToWorldVector = /* @__PURE__ */ new Vector4();
let _ray, _lineWidth;
function getWorldSpaceHalfWidth(camera, distance, resolution) {
  _clipToWorldVector.set(0, 0, -distance, 1).applyMatrix4(camera.projectionMatrix);
  _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w);
  _clipToWorldVector.x = _lineWidth / resolution.width;
  _clipToWorldVector.y = _lineWidth / resolution.height;
  _clipToWorldVector.applyMatrix4(camera.projectionMatrixInverse);
  _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w);
  return Math.abs(Math.max(_clipToWorldVector.x, _clipToWorldVector.y));
}
function raycastWorldUnits(lineSegments, intersects2) {
  const matrixWorld = lineSegments.matrixWorld;
  const geometry = lineSegments.geometry;
  const instanceStart = geometry.attributes.instanceStart;
  const instanceEnd = geometry.attributes.instanceEnd;
  const segmentCount = Math.min(geometry.instanceCount, instanceStart.count);
  for (let i2 = 0, l2 = segmentCount; i2 < l2; i2++) {
    _line.start.fromBufferAttribute(instanceStart, i2);
    _line.end.fromBufferAttribute(instanceEnd, i2);
    _line.applyMatrix4(matrixWorld);
    const pointOnLine = new Vector3();
    const point = new Vector3();
    _ray.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
    const isInside = point.distanceTo(pointOnLine) < _lineWidth * 0.5;
    if (isInside) {
      intersects2.push({
        point,
        pointOnLine,
        distance: _ray.origin.distanceTo(point),
        object: lineSegments,
        face: null,
        faceIndex: i2,
        uv: null,
        [UV1]: null
      });
    }
  }
}
function raycastScreenSpace(lineSegments, camera, intersects2) {
  const projectionMatrix = camera.projectionMatrix;
  const material = lineSegments.material;
  const resolution = material.resolution;
  const matrixWorld = lineSegments.matrixWorld;
  const geometry = lineSegments.geometry;
  const instanceStart = geometry.attributes.instanceStart;
  const instanceEnd = geometry.attributes.instanceEnd;
  const segmentCount = Math.min(geometry.instanceCount, instanceStart.count);
  const near = -camera.near;
  _ray.at(1, _ssOrigin);
  _ssOrigin.w = 1;
  _ssOrigin.applyMatrix4(camera.matrixWorldInverse);
  _ssOrigin.applyMatrix4(projectionMatrix);
  _ssOrigin.multiplyScalar(1 / _ssOrigin.w);
  _ssOrigin.x *= resolution.x / 2;
  _ssOrigin.y *= resolution.y / 2;
  _ssOrigin.z = 0;
  _ssOrigin3.copy(_ssOrigin);
  _mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld);
  for (let i2 = 0, l2 = segmentCount; i2 < l2; i2++) {
    _start4.fromBufferAttribute(instanceStart, i2);
    _end4.fromBufferAttribute(instanceEnd, i2);
    _start4.w = 1;
    _end4.w = 1;
    _start4.applyMatrix4(_mvMatrix);
    _end4.applyMatrix4(_mvMatrix);
    const isBehindCameraNear = _start4.z > near && _end4.z > near;
    if (isBehindCameraNear) {
      continue;
    }
    if (_start4.z > near) {
      const deltaDist = _start4.z - _end4.z;
      const t2 = (_start4.z - near) / deltaDist;
      _start4.lerp(_end4, t2);
    } else if (_end4.z > near) {
      const deltaDist = _end4.z - _start4.z;
      const t2 = (_end4.z - near) / deltaDist;
      _end4.lerp(_start4, t2);
    }
    _start4.applyMatrix4(projectionMatrix);
    _end4.applyMatrix4(projectionMatrix);
    _start4.multiplyScalar(1 / _start4.w);
    _end4.multiplyScalar(1 / _end4.w);
    _start4.x *= resolution.x / 2;
    _start4.y *= resolution.y / 2;
    _end4.x *= resolution.x / 2;
    _end4.y *= resolution.y / 2;
    _line.start.copy(_start4);
    _line.start.z = 0;
    _line.end.copy(_end4);
    _line.end.z = 0;
    const param = _line.closestPointToPointParameter(_ssOrigin3, true);
    _line.at(param, _closestPoint);
    const zPos = MathUtils.lerp(_start4.z, _end4.z, param);
    const isInClipSpace = zPos >= -1 && zPos <= 1;
    const isInside = _ssOrigin3.distanceTo(_closestPoint) < _lineWidth * 0.5;
    if (isInClipSpace && isInside) {
      _line.start.fromBufferAttribute(instanceStart, i2);
      _line.end.fromBufferAttribute(instanceEnd, i2);
      _line.start.applyMatrix4(matrixWorld);
      _line.end.applyMatrix4(matrixWorld);
      const pointOnLine = new Vector3();
      const point = new Vector3();
      _ray.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
      intersects2.push({
        point,
        pointOnLine,
        distance: _ray.origin.distanceTo(point),
        object: lineSegments,
        face: null,
        faceIndex: i2,
        uv: null,
        [UV1]: null
      });
    }
  }
}
class LineSegments2 extends Mesh {
  constructor(geometry = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) {
    super(geometry, material);
    this.isLineSegments2 = true;
    this.type = "LineSegments2";
  }
  // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  computeLineDistances() {
    const geometry = this.geometry;
    const instanceStart = geometry.attributes.instanceStart;
    const instanceEnd = geometry.attributes.instanceEnd;
    const lineDistances = new Float32Array(2 * instanceStart.count);
    for (let i2 = 0, j2 = 0, l2 = instanceStart.count; i2 < l2; i2++, j2 += 2) {
      _start.fromBufferAttribute(instanceStart, i2);
      _end.fromBufferAttribute(instanceEnd, i2);
      lineDistances[j2] = j2 === 0 ? 0 : lineDistances[j2 - 1];
      lineDistances[j2 + 1] = lineDistances[j2] + _start.distanceTo(_end);
    }
    const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1);
    geometry.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0));
    geometry.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1));
    return this;
  }
  raycast(raycaster, intersects2) {
    const worldUnits = this.material.worldUnits;
    const camera = raycaster.camera;
    if (camera === null && !worldUnits) {
      console.error(
        'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'
      );
    }
    const threshold = raycaster.params.Line2 !== void 0 ? raycaster.params.Line2.threshold || 0 : 0;
    _ray = raycaster.ray;
    const matrixWorld = this.matrixWorld;
    const geometry = this.geometry;
    const material = this.material;
    _lineWidth = material.linewidth + threshold;
    if (geometry.boundingSphere === null) {
      geometry.computeBoundingSphere();
    }
    _sphere.copy(geometry.boundingSphere).applyMatrix4(matrixWorld);
    let sphereMargin;
    if (worldUnits) {
      sphereMargin = _lineWidth * 0.5;
    } else {
      const distanceToSphere = Math.max(camera.near, _sphere.distanceToPoint(_ray.origin));
      sphereMargin = getWorldSpaceHalfWidth(camera, distanceToSphere, material.resolution);
    }
    _sphere.radius += sphereMargin;
    if (_ray.intersectsSphere(_sphere) === false) {
      return;
    }
    if (geometry.boundingBox === null) {
      geometry.computeBoundingBox();
    }
    _box.copy(geometry.boundingBox).applyMatrix4(matrixWorld);
    let boxMargin;
    if (worldUnits) {
      boxMargin = _lineWidth * 0.5;
    } else {
      const distanceToBox = Math.max(camera.near, _box.distanceToPoint(_ray.origin));
      boxMargin = getWorldSpaceHalfWidth(camera, distanceToBox, material.resolution);
    }
    _box.expandByScalar(boxMargin);
    if (_ray.intersectsBox(_box) === false) {
      return;
    }
    if (worldUnits) {
      raycastWorldUnits(this, intersects2);
    } else {
      raycastScreenSpace(this, camera, intersects2);
    }
  }
  onBeforeRender(renderer) {
    const uniforms = this.material.uniforms;
    if (uniforms && uniforms.resolution) {
      renderer.getViewport(_viewport);
      this.material.uniforms.resolution.value.set(_viewport.z, _viewport.w);
    }
  }
}
class Line2 extends LineSegments2 {
  constructor(geometry = new LineGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) {
    super(geometry, material);
    this.isLine2 = true;
    this.type = "Line2";
  }
}
const Line4 = /* @__PURE__ */ reactExports.forwardRef(function Line5({
  points,
  color = 16777215,
  vertexColors,
  linewidth,
  lineWidth,
  segments,
  dashed,
  ...rest
}, ref) {
  var _vertexColors$, _ref;
  const size = useThree((state) => state.size);
  const line2 = reactExports.useMemo(() => segments ? new LineSegments2() : new Line2(), [segments]);
  const [lineMaterial] = reactExports.useState(() => new LineMaterial());
  const itemSize = (vertexColors == null || (_vertexColors$ = vertexColors[0]) == null ? void 0 : _vertexColors$.length) === 4 ? 4 : 3;
  const lineGeom = reactExports.useMemo(() => {
    const geom = segments ? new LineSegmentsGeometry() : new LineGeometry();
    const pValues = points.map((p2) => {
      const isArray2 = Array.isArray(p2);
      return p2 instanceof Vector3 || p2 instanceof Vector4 ? [p2.x, p2.y, p2.z] : p2 instanceof Vector2 ? [p2.x, p2.y, 0] : isArray2 && p2.length === 3 ? [p2[0], p2[1], p2[2]] : isArray2 && p2.length === 2 ? [p2[0], p2[1], 0] : p2;
    });
    geom.setPositions(pValues.flat());
    if (vertexColors) {
      color = 16777215;
      const cValues = vertexColors.map((c2) => c2 instanceof Color ? c2.toArray() : c2);
      geom.setColors(cValues.flat(), itemSize);
    }
    return geom;
  }, [points, segments, vertexColors, itemSize]);
  reactExports.useLayoutEffect(() => {
    line2.computeLineDistances();
  }, [points, line2]);
  reactExports.useLayoutEffect(() => {
    if (dashed) {
      lineMaterial.defines.USE_DASH = "";
    } else {
      delete lineMaterial.defines.USE_DASH;
    }
    lineMaterial.needsUpdate = true;
  }, [dashed, lineMaterial]);
  reactExports.useEffect(() => {
    return () => {
      lineGeom.dispose();
      lineMaterial.dispose();
    };
  }, [lineGeom]);
  return /* @__PURE__ */ reactExports.createElement("primitive", _extends({
    object: line2,
    ref
  }, rest), /* @__PURE__ */ reactExports.createElement("primitive", {
    object: lineGeom,
    attach: "geometry"
  }), /* @__PURE__ */ reactExports.createElement("primitive", _extends({
    object: lineMaterial,
    attach: "material",
    color,
    vertexColors: Boolean(vertexColors),
    resolution: [size.width, size.height],
    linewidth: (_ref = linewidth !== null && linewidth !== void 0 ? linewidth : lineWidth) !== null && _ref !== void 0 ? _ref : 1,
    dashed,
    transparent: itemSize === 4
  }, rest)));
});
function shaderMaterial(uniforms, vertexShader2, fragmentShader2, onInit) {
  const material = class material extends ShaderMaterial {
    constructor(parameters = {}) {
      const entries = Object.entries(uniforms);
      super({
        uniforms: entries.reduce((acc, [name, value]) => {
          const uniform = UniformsUtils.clone({
            [name]: {
              value
            }
          });
          return {
            ...acc,
            ...uniform
          };
        }, {}),
        vertexShader: vertexShader2,
        fragmentShader: fragmentShader2
      });
      this.key = "";
      entries.forEach(([name]) => Object.defineProperty(this, name, {
        get: () => this.uniforms[name].value,
        set: (v5) => this.uniforms[name].value = v5
      }));
      Object.assign(this, parameters);
    }
  };
  material.key = MathUtils.generateUUID();
  return material;
}
const getVersion = () => parseInt(REVISION.replace(/\D+/g, ""));
const version = /* @__PURE__ */ getVersion();
const Edges = /* @__PURE__ */ reactExports.forwardRef(({
  threshold = 15,
  geometry: explicitGeometry,
  ...props
}, fref) => {
  const ref = reactExports.useRef(null);
  reactExports.useImperativeHandle(fref, () => ref.current, []);
  const tmpPoints = reactExports.useMemo(() => [0, 0, 0, 1, 0, 0], []);
  const memoizedGeometry = reactExports.useRef();
  const memoizedThreshold = reactExports.useRef();
  reactExports.useLayoutEffect(() => {
    const parent = ref.current.parent;
    const geometry = explicitGeometry !== null && explicitGeometry !== void 0 ? explicitGeometry : parent == null ? void 0 : parent.geometry;
    if (!geometry) return;
    const cached = memoizedGeometry.current === geometry && memoizedThreshold.current === threshold;
    if (cached) return;
    memoizedGeometry.current = geometry;
    memoizedThreshold.current = threshold;
    const points = new EdgesGeometry(geometry, threshold).attributes.position.array;
    ref.current.geometry.setPositions(points);
    ref.current.geometry.attributes.instanceStart.needsUpdate = true;
    ref.current.geometry.attributes.instanceEnd.needsUpdate = true;
    ref.current.computeLineDistances();
  });
  return /* @__PURE__ */ reactExports.createElement(Line4, _extends({
    segments: true,
    points: tmpPoints,
    ref,
    raycast: () => null
  }, props));
});
const OutlinesMaterial = /* @__PURE__ */ shaderMaterial({
  screenspace: false,
  color: /* @__PURE__ */ new Color("black"),
  opacity: 1,
  thickness: 0.05,
  size: /* @__PURE__ */ new Vector2()
}, `#include <common>
   #include <morphtarget_pars_vertex>
   #include <skinning_pars_vertex>
   #include <clipping_planes_pars_vertex>
   uniform float thickness;
   uniform bool screenspace;
   uniform vec2 size;
   void main() {
     #if defined (USE_SKINNING)
	     #include <beginnormal_vertex>
       #include <morphnormal_vertex>
       #include <skinbase_vertex>
       #include <skinnormal_vertex>
       #include <defaultnormal_vertex>
     #endif
     #include <begin_vertex>
	   #include <morphtarget_vertex>
	   #include <skinning_vertex>
     #include <project_vertex>
     #include <clipping_planes_vertex>
     vec4 tNormal = vec4(normal, 0.0);
     vec4 tPosition = vec4(transformed, 1.0);
     #ifdef USE_INSTANCING
       tNormal = instanceMatrix * tNormal;
       tPosition = instanceMatrix * tPosition;
     #endif
     if (screenspace) {
       vec3 newPosition = tPosition.xyz + tNormal.xyz * thickness;
       gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0); 
     } else {
       vec4 clipPosition = projectionMatrix * modelViewMatrix * tPosition;
       vec4 clipNormal = projectionMatrix * modelViewMatrix * tNormal;
       vec2 offset = normalize(clipNormal.xy) * thickness / size * clipPosition.w * 2.0;
       clipPosition.xy += offset;
       gl_Position = clipPosition;
     }
   }`, `uniform vec3 color;
   uniform float opacity;
   #include <clipping_planes_pars_fragment>
   void main(){
     #include <clipping_planes_fragment>
     gl_FragColor = vec4(color, opacity);
     #include <tonemapping_fragment>
     #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}>
   }`);
function Outlines({
  color = "black",
  opacity = 1,
  transparent = false,
  screenspace = false,
  toneMapped = true,
  polygonOffset = false,
  polygonOffsetFactor = 0,
  renderOrder = 0,
  thickness = 0.05,
  angle = Math.PI,
  clippingPlanes,
  ...props
}) {
  const ref = reactExports.useRef();
  const [material] = reactExports.useState(() => new OutlinesMaterial({
    side: BackSide
  }));
  const {
    gl
  } = useThree();
  const contextSize = gl.getDrawingBufferSize(new Vector2());
  reactExports.useMemo(() => extend({
    OutlinesMaterial
  }), []);
  const oldAngle = reactExports.useRef(0);
  const oldGeometry = reactExports.useRef();
  reactExports.useLayoutEffect(() => {
    const group = ref.current;
    if (!group) return;
    const parent = group.parent;
    if (parent && parent.geometry) {
      if (oldAngle.current !== angle || oldGeometry.current !== parent.geometry) {
        var _group$children;
        oldAngle.current = angle;
        oldGeometry.current = parent.geometry;
        let mesh = (_group$children = group.children) == null ? void 0 : _group$children[0];
        if (mesh) {
          if (angle) mesh.geometry.dispose();
          group.remove(mesh);
        }
        if (parent.skeleton) {
          mesh = new SkinnedMesh();
          mesh.material = material;
          mesh.bind(parent.skeleton, parent.bindMatrix);
          group.add(mesh);
        } else if (parent.isInstancedMesh) {
          mesh = new InstancedMesh(parent.geometry, material, parent.count);
          mesh.instanceMatrix = parent.instanceMatrix;
          group.add(mesh);
        } else {
          mesh = new Mesh();
          mesh.material = material;
          group.add(mesh);
        }
        mesh.geometry = angle ? toCreasedNormals(parent.geometry, angle) : parent.geometry;
        mesh.morphTargetInfluences = parent.morphTargetInfluences;
        mesh.morphTargetDictionary = parent.morphTargetDictionary;
      }
    }
  });
  reactExports.useLayoutEffect(() => {
    const group = ref.current;
    if (!group) return;
    const mesh = group.children[0];
    if (mesh) {
      mesh.renderOrder = renderOrder;
      const parent = group.parent;
      applyProps(mesh, {
        morphTargetInfluences: parent.morphTargetInfluences,
        morphTargetDictionary: parent.morphTargetDictionary
      });
      applyProps(mesh.material, {
        transparent,
        thickness,
        color,
        opacity,
        size: contextSize,
        screenspace,
        toneMapped,
        polygonOffset,
        polygonOffsetFactor,
        clippingPlanes,
        clipping: clippingPlanes && clippingPlanes.length > 0
      });
    }
  });
  reactExports.useEffect(() => {
    return () => {
      const group = ref.current;
      if (!group) return;
      const mesh = group.children[0];
      if (mesh) {
        if (angle) mesh.geometry.dispose();
        group.remove(mesh);
      }
    };
  }, []);
  return /* @__PURE__ */ reactExports.createElement("group", _extends({
    ref
  }, props));
}
const OrbitControls2 = /* @__PURE__ */ reactExports.forwardRef(({
  makeDefault,
  camera,
  regress,
  domElement,
  enableDamping = true,
  keyEvents = false,
  onChange,
  onStart,
  onEnd,
  ...restProps
}, ref) => {
  const invalidate2 = useThree((state) => state.invalidate);
  const defaultCamera = useThree((state) => state.camera);
  const gl = useThree((state) => state.gl);
  const events = useThree((state) => state.events);
  const setEvents = useThree((state) => state.setEvents);
  const set = useThree((state) => state.set);
  const get = useThree((state) => state.get);
  const performance2 = useThree((state) => state.performance);
  const explCamera = camera || defaultCamera;
  const explDomElement = domElement || events.connected || gl.domElement;
  const controls = reactExports.useMemo(() => new OrbitControls$1(explCamera), [explCamera]);
  useFrame(() => {
    if (controls.enabled) controls.update();
  }, -1);
  reactExports.useEffect(() => {
    if (keyEvents) {
      controls.connect(keyEvents === true ? explDomElement : keyEvents);
    }
    controls.connect(explDomElement);
    return () => void controls.dispose();
  }, [keyEvents, explDomElement, regress, controls, invalidate2]);
  reactExports.useEffect(() => {
    const callback = (e2) => {
      invalidate2();
      if (regress) performance2.regress();
      if (onChange) onChange(e2);
    };
    const onStartCb = (e2) => {
      if (onStart) onStart(e2);
    };
    const onEndCb = (e2) => {
      if (onEnd) onEnd(e2);
    };
    controls.addEventListener("change", callback);
    controls.addEventListener("start", onStartCb);
    controls.addEventListener("end", onEndCb);
    return () => {
      controls.removeEventListener("start", onStartCb);
      controls.removeEventListener("end", onEndCb);
      controls.removeEventListener("change", callback);
    };
  }, [onChange, onStart, onEnd, controls, invalidate2, setEvents]);
  reactExports.useEffect(() => {
    if (makeDefault) {
      const old = get().controls;
      set({
        controls
      });
      return () => set({
        controls: old
      });
    }
  }, [makeDefault, controls]);
  return /* @__PURE__ */ reactExports.createElement("primitive", _extends({
    ref,
    object: controls,
    enableDamping
  }, restProps));
});
const Center = /* @__PURE__ */ reactExports.forwardRef(function Center2({
  children,
  disable,
  disableX,
  disableY,
  disableZ,
  left,
  right,
  top,
  bottom,
  front,
  back,
  onCentered,
  precise = true,
  cacheKey = 0,
  ...props
}, fRef) {
  const ref = reactExports.useRef(null);
  const outer = reactExports.useRef(null);
  const inner = reactExports.useRef(null);
  reactExports.useLayoutEffect(() => {
    outer.current.matrixWorld.identity();
    const box3 = new Box3().setFromObject(inner.current, precise);
    const center = new Vector3();
    const sphere = new Sphere();
    const width = box3.max.x - box3.min.x;
    const height = box3.max.y - box3.min.y;
    const depth = box3.max.z - box3.min.z;
    box3.getCenter(center);
    box3.getBoundingSphere(sphere);
    const vAlign = top ? height / 2 : bottom ? -height / 2 : 0;
    const hAlign = left ? -width / 2 : right ? width / 2 : 0;
    const dAlign = front ? depth / 2 : back ? -depth / 2 : 0;
    outer.current.position.set(disable || disableX ? 0 : -center.x + hAlign, disable || disableY ? 0 : -center.y + vAlign, disable || disableZ ? 0 : -center.z + dAlign);
    if (typeof onCentered !== "undefined") {
      onCentered({
        parent: ref.current.parent,
        container: ref.current,
        width,
        height,
        depth,
        boundingBox: box3,
        boundingSphere: sphere,
        center,
        verticalAlignment: vAlign,
        horizontalAlignment: hAlign,
        depthAlignment: dAlign
      });
    }
  }, [cacheKey, onCentered, top, left, front, disable, disableX, disableY, disableZ, precise, right, bottom, back]);
  reactExports.useImperativeHandle(fRef, () => ref.current, []);
  return /* @__PURE__ */ reactExports.createElement("group", _extends({
    ref
  }, props), /* @__PURE__ */ reactExports.createElement("group", {
    ref: outer
  }, /* @__PURE__ */ reactExports.createElement("group", {
    ref: inner
  }, children)));
});
const LinearEncoding = 3e3;
const sRGBEncoding = 3001;
const DiscardMaterial = /* @__PURE__ */ shaderMaterial({}, "void main() { }", "void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); discard;  }");
function create(type, effect) {
  const El = type + "Geometry";
  return /* @__PURE__ */ reactExports.forwardRef(({
    args,
    children,
    ...props
  }, fref) => {
    const ref = reactExports.useRef(null);
    reactExports.useImperativeHandle(fref, () => ref.current);
    reactExports.useLayoutEffect(() => void (effect == null ? void 0 : effect(ref.current)));
    return /* @__PURE__ */ reactExports.createElement("mesh", _extends({
      ref
    }, props), /* @__PURE__ */ reactExports.createElement(El, {
      attach: "geometry",
      args
    }), children);
  });
}
const Box = /* @__PURE__ */ create("box");
var AnimationState = /* @__PURE__ */ (function(AnimationState2) {
  AnimationState2[AnimationState2["NONE"] = 0] = "NONE";
  AnimationState2[AnimationState2["START"] = 1] = "START";
  AnimationState2[AnimationState2["ACTIVE"] = 2] = "ACTIVE";
  return AnimationState2;
})(AnimationState || {});
const isOrthographic = (def) => def && def.isOrthographicCamera;
const isBox3 = (def) => def && def.isBox3;
const interpolateFuncDefault = (t2) => {
  return 1 - Math.exp(-5 * t2) + 7e-3 * t2;
};
const context = /* @__PURE__ */ reactExports.createContext(null);
function Bounds({
  children,
  maxDuration = 1,
  margin = 1.2,
  observe,
  fit,
  clip,
  interpolateFunc = interpolateFuncDefault,
  onFit
}) {
  const ref = reactExports.useRef(null);
  const {
    camera,
    size,
    invalidate: invalidate2
  } = useThree();
  const controls = useThree((state) => state.controls);
  const onFitRef = reactExports.useRef(onFit);
  onFitRef.current = onFit;
  const origin = reactExports.useRef({
    camPos: new Vector3(),
    camRot: new Quaternion(),
    camZoom: 1
  });
  const goal = reactExports.useRef({
    camPos: void 0,
    camRot: void 0,
    camZoom: void 0,
    camUp: void 0,
    target: void 0
  });
  const animationState = reactExports.useRef(AnimationState.NONE);
  const t2 = reactExports.useRef(0);
  const [box] = reactExports.useState(() => new Box3());
  const api = reactExports.useMemo(() => {
    function getSize() {
      const boxSize = box.getSize(new Vector3());
      const center = box.getCenter(new Vector3());
      const maxSize = Math.max(boxSize.x, boxSize.y, boxSize.z);
      const fitHeightDistance = isOrthographic(camera) ? maxSize * 4 : maxSize / (2 * Math.atan(Math.PI * camera.fov / 360));
      const fitWidthDistance = isOrthographic(camera) ? maxSize * 4 : fitHeightDistance / camera.aspect;
      const distance = margin * Math.max(fitHeightDistance, fitWidthDistance);
      return {
        box,
        size: boxSize,
        center,
        distance
      };
    }
    return {
      getSize,
      refresh(object) {
        if (isBox3(object)) box.copy(object);
        else {
          const target = object || ref.current;
          if (!target) return this;
          target.updateWorldMatrix(true, true);
          box.setFromObject(target);
        }
        if (box.isEmpty()) {
          const max2 = camera.position.length() || 10;
          box.setFromCenterAndSize(new Vector3(), new Vector3(max2, max2, max2));
        }
        origin.current.camPos.copy(camera.position);
        origin.current.camRot.copy(camera.quaternion);
        isOrthographic(camera) && (origin.current.camZoom = camera.zoom);
        goal.current.camPos = void 0;
        goal.current.camRot = void 0;
        goal.current.camZoom = void 0;
        goal.current.camUp = void 0;
        goal.current.target = void 0;
        return this;
      },
      reset() {
        const {
          center,
          distance
        } = getSize();
        const direction = camera.position.clone().sub(center).normalize();
        goal.current.camPos = center.clone().addScaledVector(direction, distance);
        goal.current.target = center.clone();
        const mCamRot = new Matrix4().lookAt(goal.current.camPos, goal.current.target, camera.up);
        goal.current.camRot = new Quaternion().setFromRotationMatrix(mCamRot);
        animationState.current = AnimationState.START;
        t2.current = 0;
        return this;
      },
      moveTo(position) {
        goal.current.camPos = Array.isArray(position) ? new Vector3(...position) : position.clone();
        animationState.current = AnimationState.START;
        t2.current = 0;
        return this;
      },
      lookAt({
        target,
        up
      }) {
        goal.current.target = Array.isArray(target) ? new Vector3(...target) : target.clone();
        if (up) {
          goal.current.camUp = Array.isArray(up) ? new Vector3(...up) : up.clone();
        } else {
          goal.current.camUp = camera.up.clone();
        }
        const mCamRot = new Matrix4().lookAt(goal.current.camPos || camera.position, goal.current.target, goal.current.camUp);
        goal.current.camRot = new Quaternion().setFromRotationMatrix(mCamRot);
        animationState.current = AnimationState.START;
        t2.current = 0;
        return this;
      },
      /**
       * @deprecated Use moveTo and lookAt instead
       */
      to({
        position,
        target
      }) {
        return this.moveTo(position).lookAt({
          target
        });
      },
      fit() {
        if (!isOrthographic(camera)) {
          return this.reset();
        }
        let maxHeight = 0, maxWidth = 0;
        const vertices = [new Vector3(box.min.x, box.min.y, box.min.z), new Vector3(box.min.x, box.max.y, box.min.z), new Vector3(box.min.x, box.min.y, box.max.z), new Vector3(box.min.x, box.max.y, box.max.z), new Vector3(box.max.x, box.max.y, box.max.z), new Vector3(box.max.x, box.max.y, box.min.z), new Vector3(box.max.x, box.min.y, box.max.z), new Vector3(box.max.x, box.min.y, box.min.z)];
        const pos = goal.current.camPos || camera.position;
        const target = goal.current.target || (controls == null ? void 0 : controls.target);
        const up = goal.current.camUp || camera.up;
        const mCamWInv = target ? new Matrix4().lookAt(pos, target, up).setPosition(pos).invert() : camera.matrixWorldInverse;
        for (const v5 of vertices) {
          v5.applyMatrix4(mCamWInv);
          maxHeight = Math.max(maxHeight, Math.abs(v5.y));
          maxWidth = Math.max(maxWidth, Math.abs(v5.x));
        }
        maxHeight *= 2;
        maxWidth *= 2;
        const zoomForHeight = (camera.top - camera.bottom) / maxHeight;
        const zoomForWidth = (camera.right - camera.left) / maxWidth;
        goal.current.camZoom = Math.min(zoomForHeight, zoomForWidth) / margin;
        animationState.current = AnimationState.START;
        t2.current = 0;
        onFitRef.current && onFitRef.current(this.getSize());
        return this;
      },
      clip() {
        const {
          distance
        } = getSize();
        camera.near = distance / 100;
        camera.far = distance * 100;
        camera.updateProjectionMatrix();
        if (controls) {
          controls.maxDistance = distance * 10;
          controls.update();
        }
        invalidate2();
        return this;
      }
    };
  }, [box, camera, controls, margin, invalidate2]);
  reactExports.useLayoutEffect(() => {
    if (controls) {
      const callback = () => {
        if (controls && goal.current.target && animationState.current !== AnimationState.NONE) {
          const front = new Vector3().setFromMatrixColumn(camera.matrix, 2);
          const d0 = origin.current.camPos.distanceTo(controls.target);
          const d1 = (goal.current.camPos || origin.current.camPos).distanceTo(goal.current.target);
          const d2 = (1 - t2.current) * d0 + t2.current * d1;
          controls.target.copy(camera.position).addScaledVector(front, -d2);
          controls.update();
        }
        animationState.current = AnimationState.NONE;
      };
      controls.addEventListener("start", callback);
      return () => controls.removeEventListener("start", callback);
    }
  }, [controls]);
  const count = reactExports.useRef(0);
  reactExports.useLayoutEffect(() => {
    if (observe || count.current++ === 0) {
      api.refresh();
      if (fit) api.reset().fit();
      if (clip) api.clip();
    }
  }, [size, clip, fit, observe, camera, controls]);
  useFrame((state, delta) => {
    if (animationState.current === AnimationState.START) {
      animationState.current = AnimationState.ACTIVE;
      invalidate2();
    } else if (animationState.current === AnimationState.ACTIVE) {
      t2.current += delta / maxDuration;
      if (t2.current >= 1) {
        goal.current.camPos && camera.position.copy(goal.current.camPos);
        goal.current.camRot && camera.quaternion.copy(goal.current.camRot);
        goal.current.camUp && camera.up.copy(goal.current.camUp);
        goal.current.camZoom && isOrthographic(camera) && (camera.zoom = goal.current.camZoom);
        camera.updateMatrixWorld();
        camera.updateProjectionMatrix();
        if (controls && goal.current.target) {
          controls.target.copy(goal.current.target);
          controls.update();
        }
        animationState.current = AnimationState.NONE;
      } else {
        const k2 = interpolateFunc(t2.current);
        goal.current.camPos && camera.position.lerpVectors(origin.current.camPos, goal.current.camPos, k2);
        goal.current.camRot && camera.quaternion.slerpQuaternions(origin.current.camRot, goal.current.camRot, k2);
        goal.current.camUp && camera.up.set(0, 1, 0).applyQuaternion(camera.quaternion);
        goal.current.camZoom && isOrthographic(camera) && (camera.zoom = (1 - k2) * origin.current.camZoom + k2 * goal.current.camZoom);
        camera.updateMatrixWorld();
        camera.updateProjectionMatrix();
      }
      invalidate2();
    }
  });
  return /* @__PURE__ */ reactExports.createElement("group", {
    ref
  }, /* @__PURE__ */ reactExports.createElement(context.Provider, {
    value: api
  }, children));
}
function useBounds() {
  return reactExports.useContext(context);
}
const getBufferForType = (type, width, height) => {
  let out;
  switch (type) {
    case UnsignedByteType:
      out = new Uint8ClampedArray(width * height * 4);
      break;
    case HalfFloatType:
      out = new Uint16Array(width * height * 4);
      break;
    case UnsignedIntType:
      out = new Uint32Array(width * height * 4);
      break;
    case ByteType:
      out = new Int8Array(width * height * 4);
      break;
    case ShortType:
      out = new Int16Array(width * height * 4);
      break;
    case IntType:
      out = new Int32Array(width * height * 4);
      break;
    case FloatType:
      out = new Float32Array(width * height * 4);
      break;
    default:
      throw new Error("Unsupported data type");
  }
  return out;
};
let _canReadPixelsResult;
const canReadPixels = (type, renderer, camera, renderTargetOptions) => {
  if (_canReadPixelsResult !== void 0)
    return _canReadPixelsResult;
  const testRT = new WebGLRenderTarget(1, 1, renderTargetOptions);
  renderer.setRenderTarget(testRT);
  const mesh = new Mesh(new PlaneGeometry(), new MeshBasicMaterial({ color: 16777215 }));
  renderer.render(mesh, camera);
  renderer.setRenderTarget(null);
  const out = getBufferForType(type, testRT.width, testRT.height);
  renderer.readRenderTargetPixels(testRT, 0, 0, testRT.width, testRT.height, out);
  testRT.dispose();
  mesh.geometry.dispose();
  mesh.material.dispose();
  _canReadPixelsResult = out[0] !== 0;
  return _canReadPixelsResult;
};
class QuadRenderer {
  /**
   * Constructs a new QuadRenderer
   *
   * @param options Parameters for this QuadRenderer
   */
  constructor(options) {
    __publicField(this, "_renderer");
    __publicField(this, "_rendererIsDisposable", false);
    __publicField(this, "_material");
    __publicField(this, "_scene");
    __publicField(this, "_camera");
    __publicField(this, "_quad");
    __publicField(this, "_renderTarget");
    __publicField(this, "_width");
    __publicField(this, "_height");
    __publicField(this, "_type");
    __publicField(this, "_colorSpace");
    __publicField(this, "_supportsReadPixels", true);
    /**
     * Renders the input texture using the specified material
     */
    __publicField(this, "render", () => {
      this._renderer.setRenderTarget(this._renderTarget);
      try {
        this._renderer.render(this._scene, this._camera);
      } catch (e2) {
        this._renderer.setRenderTarget(null);
        throw e2;
      }
      this._renderer.setRenderTarget(null);
    });
    var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n2, _o2, _p;
    this._width = options.width;
    this._height = options.height;
    this._type = options.type;
    this._colorSpace = options.colorSpace;
    const rtOptions = {
      // fixed options
      format: RGBAFormat,
      depthBuffer: false,
      stencilBuffer: false,
      // user options
      type: this._type,
      // set in class property
      colorSpace: this._colorSpace,
      // set in class property
      anisotropy: ((_a2 = options.renderTargetOptions) == null ? void 0 : _a2.anisotropy) !== void 0 ? (_b2 = options.renderTargetOptions) == null ? void 0 : _b2.anisotropy : 1,
      generateMipmaps: ((_c = options.renderTargetOptions) == null ? void 0 : _c.generateMipmaps) !== void 0 ? (_d = options.renderTargetOptions) == null ? void 0 : _d.generateMipmaps : false,
      magFilter: ((_e2 = options.renderTargetOptions) == null ? void 0 : _e2.magFilter) !== void 0 ? (_f = options.renderTargetOptions) == null ? void 0 : _f.magFilter : LinearFilter,
      minFilter: ((_g = options.renderTargetOptions) == null ? void 0 : _g.minFilter) !== void 0 ? (_h = options.renderTargetOptions) == null ? void 0 : _h.minFilter : LinearFilter,
      samples: ((_i = options.renderTargetOptions) == null ? void 0 : _i.samples) !== void 0 ? (_j = options.renderTargetOptions) == null ? void 0 : _j.samples : void 0,
      wrapS: ((_k = options.renderTargetOptions) == null ? void 0 : _k.wrapS) !== void 0 ? (_l = options.renderTargetOptions) == null ? void 0 : _l.wrapS : ClampToEdgeWrapping,
      wrapT: ((_m = options.renderTargetOptions) == null ? void 0 : _m.wrapT) !== void 0 ? (_n2 = options.renderTargetOptions) == null ? void 0 : _n2.wrapT : ClampToEdgeWrapping
    };
    this._material = options.material;
    if (options.renderer) {
      this._renderer = options.renderer;
    } else {
      this._renderer = QuadRenderer.instantiateRenderer();
      this._rendererIsDisposable = true;
    }
    this._scene = new Scene();
    this._camera = new OrthographicCamera();
    this._camera.position.set(0, 0, 10);
    this._camera.left = -0.5;
    this._camera.right = 0.5;
    this._camera.top = 0.5;
    this._camera.bottom = -0.5;
    this._camera.updateProjectionMatrix();
    if (!canReadPixels(this._type, this._renderer, this._camera, rtOptions)) {
      let alternativeType;
      switch (this._type) {
        case HalfFloatType:
          alternativeType = this._renderer.extensions.has("EXT_color_buffer_float") ? FloatType : void 0;
          break;
      }
      if (alternativeType !== void 0) {
        console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${FloatType}`);
        this._type = alternativeType;
      } else {
        this._supportsReadPixels = false;
        console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown");
      }
    }
    this._quad = new Mesh(new PlaneGeometry(), this._material);
    this._quad.geometry.computeBoundingBox();
    this._scene.add(this._quad);
    this._renderTarget = new WebGLRenderTarget(this.width, this.height, rtOptions);
    this._renderTarget.texture.mapping = ((_o2 = options.renderTargetOptions) == null ? void 0 : _o2.mapping) !== void 0 ? (_p = options.renderTargetOptions) == null ? void 0 : _p.mapping : UVMapping;
  }
  /**
   * Instantiates a temporary renderer
   *
   * @returns
   */
  static instantiateRenderer() {
    const renderer = new WebGLRenderer();
    renderer.setSize(128, 128);
    return renderer;
  }
  /**
   * Obtains a Buffer containing the rendered texture.
   *
   * @throws Error if the browser cannot read pixels from this RenderTarget type.
   * @returns a TypedArray containing RGBA values from this renderer
   */
  toArray() {
    if (!this._supportsReadPixels)
      throw new Error("Can't read pixels in this browser");
    const out = getBufferForType(this._type, this._width, this._height);
    this._renderer.readRenderTargetPixels(this._renderTarget, 0, 0, this._width, this._height, out);
    return out;
  }
  /**
   * Performs a readPixel operation in the renderTarget
   * and returns a DataTexture containing the read data
   *
   * @param options options
   * @returns
   */
  toDataTexture(options) {
    const returnValue = new DataTexture(
      // fixed values
      this.toArray(),
      this.width,
      this.height,
      RGBAFormat,
      this._type,
      // user values
      (options == null ? void 0 : options.mapping) || UVMapping,
      (options == null ? void 0 : options.wrapS) || ClampToEdgeWrapping,
      (options == null ? void 0 : options.wrapT) || ClampToEdgeWrapping,
      (options == null ? void 0 : options.magFilter) || LinearFilter,
      (options == null ? void 0 : options.minFilter) || LinearFilter,
      (options == null ? void 0 : options.anisotropy) || 1,
      // fixed value
      LinearSRGBColorSpace
    );
    returnValue.generateMipmaps = (options == null ? void 0 : options.generateMipmaps) !== void 0 ? options == null ? void 0 : options.generateMipmaps : false;
    return returnValue;
  }
  /**
   * If using a disposable renderer, it will dispose it.
   */
  disposeOnDemandRenderer() {
    this._renderer.setRenderTarget(null);
    if (this._rendererIsDisposable) {
      this._renderer.dispose();
      this._renderer.forceContextLoss();
    }
  }
  /**
   * Will dispose of **all** assets used by this renderer.
   *
   *
   * @param disposeRenderTarget will dispose of the renderTarget which will not be usable later
   * set this to true if you passed the `renderTarget.texture` to a `PMREMGenerator`
   * or are otherwise done with it.
   *
   * @example
   * ```js
   * const loader = new HDRJPGLoader(renderer)
   * const result = await loader.loadAsync('gainmap.jpeg')
   * const mesh = new Mesh(geometry, new MeshBasicMaterial({ map: result.renderTarget.texture }) )
   * // DO NOT dispose the renderTarget here,
   * // it is used directly in the material
   * result.dispose()
   * ```
   *
   * @example
   * ```js
   * const loader = new HDRJPGLoader(renderer)
   * const pmremGenerator = new PMREMGenerator( renderer );
   * const result = await loader.loadAsync('gainmap.jpeg')
   * const envMap = pmremGenerator.fromEquirectangular(result.renderTarget.texture)
   * const mesh = new Mesh(geometry, new MeshStandardMaterial({ envMap }) )
   * // renderTarget can be disposed here
   * // because it was used to generate a PMREM texture
   * result.dispose(true)
   * ```
   */
  dispose(disposeRenderTarget) {
    this.disposeOnDemandRenderer();
    if (disposeRenderTarget) {
      this.renderTarget.dispose();
    }
    if (this.material instanceof ShaderMaterial) {
      Object.values(this.material.uniforms).forEach((v5) => {
        if (v5.value instanceof Texture)
          v5.value.dispose();
      });
    }
    Object.values(this.material).forEach((value) => {
      if (value instanceof Texture)
        value.dispose();
    });
    this.material.dispose();
    this._quad.geometry.dispose();
  }
  /**
   * Width of the texture
   */
  get width() {
    return this._width;
  }
  set width(value) {
    this._width = value;
    this._renderTarget.setSize(this._width, this._height);
  }
  /**
   * Height of the texture
   */
  get height() {
    return this._height;
  }
  set height(value) {
    this._height = value;
    this._renderTarget.setSize(this._width, this._height);
  }
  /**
   * The renderer used
   */
  get renderer() {
    return this._renderer;
  }
  /**
   * The `WebGLRenderTarget` used.
   */
  get renderTarget() {
    return this._renderTarget;
  }
  set renderTarget(value) {
    this._renderTarget = value;
    this._width = value.width;
    this._height = value.height;
  }
  /**
   * The `Material` used.
   */
  get material() {
    return this._material;
  }
  /**
   *
   */
  get type() {
    return this._type;
  }
  get colorSpace() {
    return this._colorSpace;
  }
}
class GainMapNotFoundError extends Error {
}
class XMPMetadataNotFoundError extends Error {
}
const getXMLValue = (xml, tag, defaultValue) => {
  const attributeMatch = new RegExp(`${tag}="([^"]*)"`, "i").exec(xml);
  if (attributeMatch)
    return attributeMatch[1];
  const tagMatch = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, "i").exec(xml);
  if (tagMatch) {
    const liValues = tagMatch[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);
    if (liValues && liValues.length === 3) {
      return liValues.map((v5) => v5.replace(/<\/?rdf:li>/g, ""));
    }
    return tagMatch[1].trim();
  }
  if (defaultValue !== void 0)
    return defaultValue;
  throw new Error(`Can't find ${tag} in gainmap metadata`);
};
const extractXMP = (input) => {
  let str;
  if (typeof TextDecoder !== "undefined")
    str = new TextDecoder().decode(input);
  else
    str = input.toString();
  let start = str.indexOf("<x:xmpmeta");
  while (start !== -1) {
    const end = str.indexOf("x:xmpmeta>", start);
    const xmpBlock = str.slice(start, end + 10);
    try {
      const gainMapMin = getXMLValue(xmpBlock, "hdrgm:GainMapMin", "0");
      const gainMapMax = getXMLValue(xmpBlock, "hdrgm:GainMapMax");
      const gamma = getXMLValue(xmpBlock, "hdrgm:Gamma", "1");
      const offsetSDR = getXMLValue(xmpBlock, "hdrgm:OffsetSDR", "0.015625");
      const offsetHDR = getXMLValue(xmpBlock, "hdrgm:OffsetHDR", "0.015625");
      const hdrCapacityMinMatch = /hdrgm:HDRCapacityMin="([^"]*)"/.exec(xmpBlock);
      const hdrCapacityMin = hdrCapacityMinMatch ? hdrCapacityMinMatch[1] : "0";
      const hdrCapacityMaxMatch = /hdrgm:HDRCapacityMax="([^"]*)"/.exec(xmpBlock);
      if (!hdrCapacityMaxMatch)
        throw new Error("Incomplete gainmap metadata");
      const hdrCapacityMax = hdrCapacityMaxMatch[1];
      return {
        gainMapMin: Array.isArray(gainMapMin) ? gainMapMin.map((v5) => parseFloat(v5)) : [parseFloat(gainMapMin), parseFloat(gainMapMin), parseFloat(gainMapMin)],
        gainMapMax: Array.isArray(gainMapMax) ? gainMapMax.map((v5) => parseFloat(v5)) : [parseFloat(gainMapMax), parseFloat(gainMapMax), parseFloat(gainMapMax)],
        gamma: Array.isArray(gamma) ? gamma.map((v5) => parseFloat(v5)) : [parseFloat(gamma), parseFloat(gamma), parseFloat(gamma)],
        offsetSdr: Array.isArray(offsetSDR) ? offsetSDR.map((v5) => parseFloat(v5)) : [parseFloat(offsetSDR), parseFloat(offsetSDR), parseFloat(offsetSDR)],
        offsetHdr: Array.isArray(offsetHDR) ? offsetHDR.map((v5) => parseFloat(v5)) : [parseFloat(offsetHDR), parseFloat(offsetHDR), parseFloat(offsetHDR)],
        hdrCapacityMin: parseFloat(hdrCapacityMin),
        hdrCapacityMax: parseFloat(hdrCapacityMax)
      };
    } catch (e2) {
    }
    start = str.indexOf("<x:xmpmeta", end);
  }
};
class MPFExtractor {
  constructor(options) {
    __publicField(this, "options");
    this.options = {
      debug: options && options.debug !== void 0 ? options.debug : false,
      extractFII: options && options.extractFII !== void 0 ? options.extractFII : true,
      extractNonFII: options && options.extractNonFII !== void 0 ? options.extractNonFII : true
    };
  }
  extract(imageArrayBuffer) {
    return new Promise((resolve2, reject) => {
      const debug = this.options.debug;
      const dataView = new DataView(imageArrayBuffer.buffer);
      if (dataView.getUint16(0) !== 65496) {
        reject(new Error("Not a valid jpeg"));
        return;
      }
      const length = dataView.byteLength;
      let offset = 2;
      let loops = 0;
      let marker;
      while (offset < length) {
        if (++loops > 250) {
          reject(new Error(`Found no marker after ${loops} loops 😵`));
          return;
        }
        if (dataView.getUint8(offset) !== 255) {
          reject(new Error(`Not a valid marker at offset 0x${offset.toString(16)}, found: 0x${dataView.getUint8(offset).toString(16)}`));
          return;
        }
        marker = dataView.getUint8(offset + 1);
        if (debug)
          console.log(`Marker: ${marker.toString(16)}`);
        if (marker === 226) {
          if (debug)
            console.log("Found APP2 marker (0xffe2)");
          const formatPt = offset + 4;
          if (dataView.getUint32(formatPt) === 1297106432) {
            const tiffOffset = formatPt + 4;
            let bigEnd;
            if (dataView.getUint16(tiffOffset) === 18761) {
              bigEnd = false;
            } else if (dataView.getUint16(tiffOffset) === 19789) {
              bigEnd = true;
            } else {
              reject(new Error("No valid endianness marker found in TIFF header"));
              return;
            }
            if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 42) {
              reject(new Error("Not valid TIFF data! (no 0x002A marker)"));
              return;
            }
            const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
            if (firstIFDOffset < 8) {
              reject(new Error("Not valid TIFF data! (First offset less than 8)"));
              return;
            }
            const dirStart = tiffOffset + firstIFDOffset;
            const count = dataView.getUint16(dirStart, !bigEnd);
            const entriesStart = dirStart + 2;
            let numberOfImages = 0;
            for (let i2 = entriesStart; i2 < entriesStart + 12 * count; i2 += 12) {
              if (dataView.getUint16(i2, !bigEnd) === 45057) {
                numberOfImages = dataView.getUint32(i2 + 8, !bigEnd);
              }
            }
            const nextIFDOffsetLen = 4;
            const MPImageListValPt = dirStart + 2 + count * 12 + nextIFDOffsetLen;
            const images = [];
            for (let i2 = MPImageListValPt; i2 < MPImageListValPt + numberOfImages * 16; i2 += 16) {
              const image = {
                MPType: dataView.getUint32(i2, !bigEnd),
                size: dataView.getUint32(i2 + 4, !bigEnd),
                // This offset is specified relative to the address of the MP Endian
                // field in the MP Header, unless the image is a First Individual Image,
                // in which case the value of the offset shall be NULL (0x00000000).
                dataOffset: dataView.getUint32(i2 + 8, !bigEnd),
                dependantImages: dataView.getUint32(i2 + 12, !bigEnd),
                start: -1,
                end: -1,
                isFII: false
              };
              if (!image.dataOffset) {
                image.start = 0;
                image.isFII = true;
              } else {
                image.start = tiffOffset + image.dataOffset;
                image.isFII = false;
              }
              image.end = image.start + image.size;
              images.push(image);
            }
            if (this.options.extractNonFII && images.length) {
              const bufferBlob = new Blob([dataView]);
              const imgs = [];
              for (const image of images) {
                if (image.isFII && !this.options.extractFII) {
                  continue;
                }
                const imageBlob = bufferBlob.slice(image.start, image.end + 1, "image/jpeg");
                imgs.push(imageBlob);
              }
              resolve2(imgs);
            }
          }
        }
        offset += 2 + dataView.getUint16(offset + 2);
      }
    });
  }
}
const extractGainmapFromJPEG = async (jpegFile) => {
  const metadata = extractXMP(jpegFile);
  if (!metadata)
    throw new XMPMetadataNotFoundError("Gain map XMP metadata not found");
  const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true });
  const images = await mpfExtractor.extract(jpegFile);
  if (images.length !== 2)
    throw new GainMapNotFoundError("Gain map recovery image not found");
  return {
    sdr: new Uint8Array(await images[0].arrayBuffer()),
    gainMap: new Uint8Array(await images[1].arrayBuffer()),
    metadata
  };
};
const getHTMLImageFromBlob = (blob) => {
  return new Promise((resolve2, reject) => {
    const img = document.createElement("img");
    img.onload = () => {
      resolve2(img);
    };
    img.onerror = (e2) => {
      reject(e2);
    };
    img.src = URL.createObjectURL(blob);
  });
};
class LoaderBaseShared extends Loader {
  constructor(config, manager) {
    super(manager);
    __publicField(this, "_renderer");
    __publicField(this, "_renderTargetOptions");
    __publicField(this, "_internalLoadingManager");
    __publicField(this, "_config");
    this._config = config;
    if (config.renderer)
      this._renderer = config.renderer;
    this._internalLoadingManager = new LoadingManager();
  }
  setRenderer(renderer) {
    this._renderer = renderer;
    return this;
  }
  setRenderTargetOptions(options) {
    this._renderTargetOptions = options;
    return this;
  }
  prepareQuadRenderer() {
    if (!this._renderer) {
      console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");
    }
    const material = this._config.createMaterial({
      gainMapMax: [1, 1, 1],
      gainMapMin: [0, 0, 0],
      gamma: [1, 1, 1],
      offsetHdr: [1, 1, 1],
      offsetSdr: [1, 1, 1],
      hdrCapacityMax: 1,
      hdrCapacityMin: 0,
      maxDisplayBoost: 1,
      gainMap: new Texture(),
      sdr: new Texture()
    });
    return this._config.createQuadRenderer({
      width: 16,
      height: 16,
      type: HalfFloatType,
      colorSpace: LinearSRGBColorSpace,
      material,
      renderer: this._renderer,
      renderTargetOptions: this._renderTargetOptions
    });
  }
  async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
    const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: "image/jpeg" }) : void 0;
    const sdrBlob = new Blob([sdrBuffer], { type: "image/jpeg" });
    let sdrImage;
    let gainMapImage;
    let needsFlip = false;
    if (typeof createImageBitmap === "undefined") {
      const res = await Promise.all([
        gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(void 0),
        getHTMLImageFromBlob(sdrBlob)
      ]);
      gainMapImage = res[0];
      sdrImage = res[1];
      needsFlip = imageOrientation === "flipY";
    } else {
      const res = await Promise.all([
        gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || "flipY" }) : Promise.resolve(void 0),
        createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || "flipY" })
      ]);
      gainMapImage = res[0];
      sdrImage = res[1];
    }
    return { sdrImage, gainMapImage, needsFlip };
  }
  createTextures(sdrImage, gainMapImage, needsFlip) {
    const gainMap = new Texture(gainMapImage || new ImageData(2, 2), UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, LinearSRGBColorSpace);
    gainMap.flipY = needsFlip;
    gainMap.needsUpdate = true;
    const sdr = new Texture(sdrImage, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, SRGBColorSpace);
    sdr.flipY = needsFlip;
    sdr.needsUpdate = true;
    return { gainMap, sdr };
  }
  updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
    quadRenderer.width = sdrImage.width;
    quadRenderer.height = sdrImage.height;
    quadRenderer.material.gainMap = gainMap;
    quadRenderer.material.sdr = sdr;
    quadRenderer.material.gainMapMin = metadata.gainMapMin;
    quadRenderer.material.gainMapMax = metadata.gainMapMax;
    quadRenderer.material.offsetHdr = metadata.offsetHdr;
    quadRenderer.material.offsetSdr = metadata.offsetSdr;
    quadRenderer.material.gamma = metadata.gamma;
    quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin;
    quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax;
    quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax);
    quadRenderer.material.needsUpdate = true;
  }
}
const vertexShader = (
  /* glsl */
  `
varying vec2 vUv;

void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`
);
const fragmentShader = (
  /* glsl */
  `
// min half float value
#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 )
// max half float value
#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 )

uniform sampler2D sdr;
uniform sampler2D gainMap;
uniform vec3 gamma;
uniform vec3 offsetHdr;
uniform vec3 offsetSdr;
uniform vec3 gainMapMin;
uniform vec3 gainMapMax;
uniform float weightFactor;

varying vec2 vUv;

void main() {
  vec3 rgb = texture2D( sdr, vUv ).rgb;
  vec3 recovery = texture2D( gainMap, vUv ).rgb;
  vec3 logRecovery = pow( recovery, gamma );
  vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery;
  vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr;
  vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));
  gl_FragColor = vec4( clampedHdrColor , 1.0 );
}
`
);
class GainMapDecoderMaterial extends ShaderMaterial {
  /**
   *
   * @param params
   */
  constructor({ gamma, offsetHdr, offsetSdr, gainMapMin, gainMapMax, maxDisplayBoost, hdrCapacityMin, hdrCapacityMax, sdr, gainMap }) {
    super({
      name: "GainMapDecoderMaterial",
      vertexShader,
      fragmentShader,
      uniforms: {
        sdr: { value: sdr },
        gainMap: { value: gainMap },
        gamma: { value: new Vector3(1 / gamma[0], 1 / gamma[1], 1 / gamma[2]) },
        offsetHdr: { value: new Vector3().fromArray(offsetHdr) },
        offsetSdr: { value: new Vector3().fromArray(offsetSdr) },
        gainMapMin: { value: new Vector3().fromArray(gainMapMin) },
        gainMapMax: { value: new Vector3().fromArray(gainMapMax) },
        weightFactor: {
          value: (Math.log2(maxDisplayBoost) - hdrCapacityMin) / (hdrCapacityMax - hdrCapacityMin)
        }
      },
      blending: NoBlending,
      depthTest: false,
      depthWrite: false
    });
    __publicField(this, "_maxDisplayBoost");
    __publicField(this, "_hdrCapacityMin");
    __publicField(this, "_hdrCapacityMax");
    this._maxDisplayBoost = maxDisplayBoost;
    this._hdrCapacityMin = hdrCapacityMin;
    this._hdrCapacityMax = hdrCapacityMax;
    this.needsUpdate = true;
    this.uniformsNeedUpdate = true;
  }
  get sdr() {
    return this.uniforms.sdr.value;
  }
  set sdr(value) {
    this.uniforms.sdr.value = value;
  }
  get gainMap() {
    return this.uniforms.gainMap.value;
  }
  set gainMap(value) {
    this.uniforms.gainMap.value = value;
  }
  /**
   * @see {@link GainMapMetadata.offsetHdr}
   */
  get offsetHdr() {
    return this.uniforms.offsetHdr.value.toArray();
  }
  set offsetHdr(value) {
    this.uniforms.offsetHdr.value.fromArray(value);
  }
  /**
   * @see {@link GainMapMetadata.offsetSdr}
   */
  get offsetSdr() {
    return this.uniforms.offsetSdr.value.toArray();
  }
  set offsetSdr(value) {
    this.uniforms.offsetSdr.value.fromArray(value);
  }
  /**
   * @see {@link GainMapMetadata.gainMapMin}
   */
  get gainMapMin() {
    return this.uniforms.gainMapMin.value.toArray();
  }
  set gainMapMin(value) {
    this.uniforms.gainMapMin.value.fromArray(value);
  }
  /**
   * @see {@link GainMapMetadata.gainMapMax}
   */
  get gainMapMax() {
    return this.uniforms.gainMapMax.value.toArray();
  }
  set gainMapMax(value) {
    this.uniforms.gainMapMax.value.fromArray(value);
  }
  /**
   * @see {@link GainMapMetadata.gamma}
   */
  get gamma() {
    const g2 = this.uniforms.gamma.value;
    return [1 / g2.x, 1 / g2.y, 1 / g2.z];
  }
  set gamma(value) {
    const g2 = this.uniforms.gamma.value;
    g2.x = 1 / value[0];
    g2.y = 1 / value[1];
    g2.z = 1 / value[2];
  }
  /**
   * @see {@link GainMapMetadata.hdrCapacityMin}
   * @remarks Logarithmic space
   */
  get hdrCapacityMin() {
    return this._hdrCapacityMin;
  }
  set hdrCapacityMin(value) {
    this._hdrCapacityMin = value;
    this.calculateWeight();
  }
  /**
   * @see {@link GainMapMetadata.hdrCapacityMin}
   * @remarks Logarithmic space
   */
  get hdrCapacityMax() {
    return this._hdrCapacityMax;
  }
  set hdrCapacityMax(value) {
    this._hdrCapacityMax = value;
    this.calculateWeight();
  }
  /**
   * @see {@link GainmapDecodingParameters.maxDisplayBoost}
   * @remarks Non Logarithmic space
   */
  get maxDisplayBoost() {
    return this._maxDisplayBoost;
  }
  set maxDisplayBoost(value) {
    this._maxDisplayBoost = Math.max(1, Math.min(65504, value));
    this.calculateWeight();
  }
  calculateWeight() {
    const val = (Math.log2(this._maxDisplayBoost) - this._hdrCapacityMin) / (this._hdrCapacityMax - this._hdrCapacityMin);
    this.uniforms.weightFactor.value = Math.max(0, Math.min(1, val));
  }
}
class LoaderBaseWebGL extends LoaderBaseShared {
  constructor(renderer, manager) {
    super({
      renderer,
      createMaterial: (params) => new GainMapDecoderMaterial(params),
      createQuadRenderer: (params) => new QuadRenderer(params)
    }, manager);
  }
  /**
   * @private
   * @param quadRenderer
   * @param metadata
   * @param sdrBuffer
   * @param gainMapBuffer
   */
  async render(quadRenderer, metadata, sdrBuffer, gainMapBuffer) {
    const { sdrImage, gainMapImage, needsFlip } = await this.processImages(sdrBuffer, gainMapBuffer, "flipY");
    const { gainMap, sdr } = this.createTextures(sdrImage, gainMapImage, needsFlip);
    this.updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata);
    quadRenderer.render();
  }
}
class GainMapLoader extends LoaderBaseWebGL {
  /**
   * Loads a gainmap using separate data
   * * sdr image
   * * gain map image
   * * metadata json
   *
   * useful for webp gain maps
   *
   * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
   * @param onLoad Load complete callback, will receive the result
   * @param onProgress Progress callback, will receive a `ProgressEvent`
   * @param onError Error callback
   * @returns
   */
  load([sdrUrl, gainMapUrl, metadataUrl], onLoad, onProgress, onError) {
    const quadRenderer = this.prepareQuadRenderer();
    let sdr;
    let gainMap;
    let metadata;
    const loadCheck = async () => {
      if (sdr && gainMap && metadata) {
        try {
          await this.render(quadRenderer, metadata, sdr, gainMap);
        } catch (error2) {
          this.manager.itemError(sdrUrl);
          this.manager.itemError(gainMapUrl);
          this.manager.itemError(metadataUrl);
          if (typeof onError === "function")
            onError(error2);
          quadRenderer.disposeOnDemandRenderer();
          return;
        }
        if (typeof onLoad === "function")
          onLoad(quadRenderer);
        this.manager.itemEnd(sdrUrl);
        this.manager.itemEnd(gainMapUrl);
        this.manager.itemEnd(metadataUrl);
        quadRenderer.disposeOnDemandRenderer();
      }
    };
    let sdrLengthComputable = true;
    let sdrTotal = 0;
    let sdrLoaded = 0;
    let gainMapLengthComputable = true;
    let gainMapTotal = 0;
    let gainMapLoaded = 0;
    let metadataLengthComputable = true;
    let metadataTotal = 0;
    let metadataLoaded = 0;
    const progressHandler = () => {
      if (typeof onProgress === "function") {
        const total = sdrTotal + gainMapTotal + metadataTotal;
        const loaded = sdrLoaded + gainMapLoaded + metadataLoaded;
        const lengthComputable = sdrLengthComputable && gainMapLengthComputable && metadataLengthComputable;
        onProgress(new ProgressEvent("progress", { lengthComputable, loaded, total }));
      }
    };
    this.manager.itemStart(sdrUrl);
    this.manager.itemStart(gainMapUrl);
    this.manager.itemStart(metadataUrl);
    const sdrLoader = new FileLoader(this._internalLoadingManager);
    sdrLoader.setResponseType("arraybuffer");
    sdrLoader.setRequestHeader(this.requestHeader);
    sdrLoader.setPath(this.path);
    sdrLoader.setWithCredentials(this.withCredentials);
    sdrLoader.load(sdrUrl, async (buffer) => {
      if (typeof buffer === "string")
        throw new Error("Invalid sdr buffer");
      sdr = buffer;
      await loadCheck();
    }, (e2) => {
      sdrLengthComputable = e2.lengthComputable;
      sdrLoaded = e2.loaded;
      sdrTotal = e2.total;
      progressHandler();
    }, (error2) => {
      this.manager.itemError(sdrUrl);
      if (typeof onError === "function")
        onError(error2);
    });
    const gainMapLoader = new FileLoader(this._internalLoadingManager);
    gainMapLoader.setResponseType("arraybuffer");
    gainMapLoader.setRequestHeader(this.requestHeader);
    gainMapLoader.setPath(this.path);
    gainMapLoader.setWithCredentials(this.withCredentials);
    gainMapLoader.load(gainMapUrl, async (buffer) => {
      if (typeof buffer === "string")
        throw new Error("Invalid gainmap buffer");
      gainMap = buffer;
      await loadCheck();
    }, (e2) => {
      gainMapLengthComputable = e2.lengthComputable;
      gainMapLoaded = e2.loaded;
      gainMapTotal = e2.total;
      progressHandler();
    }, (error2) => {
      this.manager.itemError(gainMapUrl);
      if (typeof onError === "function")
        onError(error2);
    });
    const metadataLoader = new FileLoader(this._internalLoadingManager);
    metadataLoader.setRequestHeader(this.requestHeader);
    metadataLoader.setPath(this.path);
    metadataLoader.setWithCredentials(this.withCredentials);
    metadataLoader.load(metadataUrl, async (json3) => {
      if (typeof json3 !== "string")
        throw new Error("Invalid metadata string");
      metadata = JSON.parse(json3);
      await loadCheck();
    }, (e2) => {
      metadataLengthComputable = e2.lengthComputable;
      metadataLoaded = e2.loaded;
      metadataTotal = e2.total;
      progressHandler();
    }, (error2) => {
      this.manager.itemError(metadataUrl);
      if (typeof onError === "function")
        onError(error2);
    });
    return quadRenderer;
  }
}
class HDRJPGLoader extends LoaderBaseWebGL {
  /**
   * Loads a JPEG containing gain map metadata
   * Renders a normal SDR image if gainmap data is not found
   *
   * @param url Path to a JPEG file containing embedded gain map metadata
   * @param onLoad Load complete callback, will receive the result
   * @param onProgress Progress callback, will receive a `ProgressEvent`
   * @param onError Error callback
   * @returns
   */
  load(url, onLoad, onProgress, onError) {
    const quadRenderer = this.prepareQuadRenderer();
    const loader2 = new FileLoader(this._internalLoadingManager);
    loader2.setResponseType("arraybuffer");
    loader2.setRequestHeader(this.requestHeader);
    loader2.setPath(this.path);
    loader2.setWithCredentials(this.withCredentials);
    this.manager.itemStart(url);
    loader2.load(url, async (jpeg) => {
      if (typeof jpeg === "string")
        throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");
      const jpegBuffer = new Uint8Array(jpeg);
      let sdrJPEG;
      let gainMapJPEG;
      let metadata;
      try {
        const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
        sdrJPEG = extractionResult.sdr;
        gainMapJPEG = extractionResult.gainMap;
        metadata = extractionResult.metadata;
      } catch (e2) {
        if (e2 instanceof XMPMetadataNotFoundError || e2 instanceof GainMapNotFoundError) {
          console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`);
          metadata = {
            gainMapMin: [0, 0, 0],
            gainMapMax: [1, 1, 1],
            gamma: [1, 1, 1],
            hdrCapacityMin: 0,
            hdrCapacityMax: 1,
            offsetHdr: [0, 0, 0],
            offsetSdr: [0, 0, 0]
          };
          sdrJPEG = jpegBuffer;
        } else {
          throw e2;
        }
      }
      try {
        await this.render(quadRenderer, metadata, sdrJPEG.buffer, gainMapJPEG == null ? void 0 : gainMapJPEG.buffer);
      } catch (error2) {
        this.manager.itemError(url);
        if (typeof onError === "function")
          onError(error2);
        quadRenderer.disposeOnDemandRenderer();
        return;
      }
      if (typeof onLoad === "function")
        onLoad(quadRenderer);
      this.manager.itemEnd(url);
      quadRenderer.disposeOnDemandRenderer();
    }, onProgress, (error2) => {
      this.manager.itemError(url);
      if (typeof onError === "function")
        onError(error2);
    });
    return quadRenderer;
  }
}
const presetsObj = {
  apartment: "lebombo_1k.hdr",
  city: "potsdamer_platz_1k.hdr",
  dawn: "kiara_1_dawn_1k.hdr",
  forest: "forest_slope_1k.hdr",
  lobby: "st_fagans_interior_1k.hdr",
  night: "dikhololo_night_1k.hdr",
  park: "rooitou_park_1k.hdr",
  studio: "studio_small_03_1k.hdr",
  sunset: "venice_sunset_1k.hdr",
  warehouse: "empty_warehouse_01_1k.hdr"
};
const CUBEMAP_ROOT = "https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/";
const isArray = (arr) => Array.isArray(arr);
const defaultFiles = ["/px.png", "/nx.png", "/py.png", "/ny.png", "/pz.png", "/nz.png"];
function useEnvironment({
  files = defaultFiles,
  path = "",
  preset = void 0,
  encoding = void 0,
  extensions
} = {}) {
  let loader2 = null;
  let multiFile = false;
  if (preset) {
    validatePreset(preset);
    files = presetsObj[preset];
    path = CUBEMAP_ROOT;
  }
  multiFile = isArray(files);
  const {
    extension,
    isCubemap
  } = getExtension(files);
  loader2 = getLoader(extension);
  if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files);
  const gl = useThree((state) => state.gl);
  reactExports.useLayoutEffect(() => {
    if (extension !== "webp" && extension !== "jpg" && extension !== "jpeg") return;
    function clearGainmapTexture() {
      useLoader.clear(
        // @ts-expect-error
        loader2,
        multiFile ? [files] : files
      );
    }
    gl.domElement.addEventListener("webglcontextlost", clearGainmapTexture, {
      once: true
    });
  }, [files, gl.domElement]);
  const loaderResult = useLoader(
    // @ts-expect-error
    loader2,
    multiFile ? [files] : files,
    (loader3) => {
      if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
        loader3.setRenderer(gl);
      }
      loader3.setPath == null || loader3.setPath(path);
      if (extensions) extensions(loader3);
    }
  );
  let texture = multiFile ? (
    // @ts-ignore
    loaderResult[0]
  ) : loaderResult;
  if (extension === "jpg" || extension === "jpeg" || extension === "webp") {
    var _renderTarget;
    texture = (_renderTarget = texture.renderTarget) == null ? void 0 : _renderTarget.texture;
  }
  texture.mapping = isCubemap ? CubeReflectionMapping : EquirectangularReflectionMapping;
  if ("colorSpace" in texture) texture.colorSpace = (encoding !== null && encoding !== void 0 ? encoding : isCubemap) ? "srgb" : "srgb-linear";
  else texture.encoding = (encoding !== null && encoding !== void 0 ? encoding : isCubemap) ? sRGBEncoding : LinearEncoding;
  return texture;
}
const preloadDefaultOptions = {
  files: defaultFiles,
  path: "",
  preset: void 0,
  extensions: void 0
};
useEnvironment.preload = (preloadOptions) => {
  const options = {
    ...preloadDefaultOptions,
    ...preloadOptions
  };
  let {
    files,
    path = ""
  } = options;
  const {
    preset,
    extensions
  } = options;
  if (preset) {
    validatePreset(preset);
    files = presetsObj[preset];
    path = CUBEMAP_ROOT;
  }
  const {
    extension
  } = getExtension(files);
  if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
    throw new Error("useEnvironment: Preloading gainmaps is not supported");
  }
  const loader2 = getLoader(extension);
  if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files);
  useLoader.preload(
    // @ts-expect-error
    loader2,
    isArray(files) ? [files] : files,
    (loader3) => {
      loader3.setPath == null || loader3.setPath(path);
      if (extensions) extensions(loader3);
    }
  );
};
const clearDefaultOptins = {
  files: defaultFiles,
  preset: void 0
};
useEnvironment.clear = (clearOptions) => {
  const options = {
    ...clearDefaultOptins,
    ...clearOptions
  };
  let {
    files
  } = options;
  const {
    preset
  } = options;
  if (preset) {
    validatePreset(preset);
    files = presetsObj[preset];
  }
  const {
    extension
  } = getExtension(files);
  const loader2 = getLoader(extension);
  if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files);
  useLoader.clear(
    // @ts-expect-error
    loader2,
    isArray(files) ? [files] : files
  );
};
function validatePreset(preset) {
  if (!(preset in presetsObj)) throw new Error("Preset must be one of: " + Object.keys(presetsObj).join(", "));
}
function getExtension(files) {
  var _firstEntry$split$pop;
  const isCubemap = isArray(files) && files.length === 6;
  const isGainmap = isArray(files) && files.length === 3 && files.some((file) => file.endsWith("json"));
  const firstEntry = isArray(files) ? files[0] : files;
  const extension = isCubemap ? "cube" : isGainmap ? "webp" : firstEntry.startsWith("data:application/exr") ? "exr" : firstEntry.startsWith("data:application/hdr") ? "hdr" : firstEntry.startsWith("data:image/jpeg") ? "jpg" : (_firstEntry$split$pop = firstEntry.split(".").pop()) == null || (_firstEntry$split$pop = _firstEntry$split$pop.split("?")) == null || (_firstEntry$split$pop = _firstEntry$split$pop.shift()) == null ? void 0 : _firstEntry$split$pop.toLowerCase();
  return {
    extension,
    isCubemap,
    isGainmap
  };
}
function getLoader(extension) {
  const loader2 = extension === "cube" ? CubeTextureLoader : extension === "hdr" ? RGBELoader : extension === "exr" ? EXRLoader : extension === "jpg" || extension === "jpeg" ? HDRJPGLoader : extension === "webp" ? GainMapLoader : null;
  return loader2;
}
const isRef = (obj) => obj.current && obj.current.isScene;
const resolveScene = (scene) => isRef(scene) ? scene.current : scene;
function setEnvProps(background, scene, defaultScene, texture, sceneProps = {}) {
  var _target$backgroundRot, _target$backgroundRot2, _target$environmentRo, _target$environmentRo2;
  sceneProps = {
    backgroundBlurriness: 0,
    backgroundIntensity: 1,
    backgroundRotation: [0, 0, 0],
    environmentIntensity: 1,
    environmentRotation: [0, 0, 0],
    ...sceneProps
  };
  const target = resolveScene(scene || defaultScene);
  const oldbg = target.background;
  const oldenv = target.environment;
  const oldSceneProps = {
    // @ts-ignore
    backgroundBlurriness: target.backgroundBlurriness,
    // @ts-ignore
    backgroundIntensity: target.backgroundIntensity,
    // @ts-ignore
    backgroundRotation: (_target$backgroundRot = (_target$backgroundRot2 = target.backgroundRotation) == null || _target$backgroundRot2.clone == null ? void 0 : _target$backgroundRot2.clone()) !== null && _target$backgroundRot !== void 0 ? _target$backgroundRot : [0, 0, 0],
    // @ts-ignore
    environmentIntensity: target.environmentIntensity,
    // @ts-ignore
    environmentRotation: (_target$environmentRo = (_target$environmentRo2 = target.environmentRotation) == null || _target$environmentRo2.clone == null ? void 0 : _target$environmentRo2.clone()) !== null && _target$environmentRo !== void 0 ? _target$environmentRo : [0, 0, 0]
  };
  if (background !== "only") target.environment = texture;
  if (background) target.background = texture;
  applyProps(target, sceneProps);
  return () => {
    if (background !== "only") target.environment = oldenv;
    if (background) target.background = oldbg;
    applyProps(target, oldSceneProps);
  };
}
function EnvironmentMap({
  scene,
  background = false,
  map,
  ...config
}) {
  const defaultScene = useThree((state) => state.scene);
  reactExports.useLayoutEffect(() => {
    if (map) return setEnvProps(background, scene, defaultScene, map, config);
  });
  return null;
}
function EnvironmentCube({
  background = false,
  scene,
  blur,
  backgroundBlurriness,
  backgroundIntensity,
  backgroundRotation,
  environmentIntensity,
  environmentRotation,
  ...rest
}) {
  const texture = useEnvironment(rest);
  const defaultScene = useThree((state) => state.scene);
  reactExports.useLayoutEffect(() => {
    return setEnvProps(background, scene, defaultScene, texture, {
      backgroundBlurriness: blur !== null && blur !== void 0 ? blur : backgroundBlurriness,
      backgroundIntensity,
      backgroundRotation,
      environmentIntensity,
      environmentRotation
    });
  });
  reactExports.useEffect(() => {
    return () => {
      texture.dispose();
    };
  }, [texture]);
  return null;
}
function EnvironmentPortal({
  children,
  near = 0.1,
  far = 1e3,
  resolution = 256,
  frames = 1,
  map,
  background = false,
  blur,
  backgroundBlurriness,
  backgroundIntensity,
  backgroundRotation,
  environmentIntensity,
  environmentRotation,
  scene,
  files,
  path,
  preset = void 0,
  extensions
}) {
  const gl = useThree((state) => state.gl);
  const defaultScene = useThree((state) => state.scene);
  const camera = reactExports.useRef(null);
  const [virtualScene] = reactExports.useState(() => new Scene());
  const fbo = reactExports.useMemo(() => {
    const fbo2 = new WebGLCubeRenderTarget(resolution);
    fbo2.texture.type = HalfFloatType;
    return fbo2;
  }, [resolution]);
  reactExports.useEffect(() => {
    return () => {
      fbo.dispose();
    };
  }, [fbo]);
  reactExports.useLayoutEffect(() => {
    if (frames === 1) {
      const autoClear = gl.autoClear;
      gl.autoClear = true;
      camera.current.update(gl, virtualScene);
      gl.autoClear = autoClear;
    }
    return setEnvProps(background, scene, defaultScene, fbo.texture, {
      backgroundBlurriness: blur !== null && blur !== void 0 ? blur : backgroundBlurriness,
      backgroundIntensity,
      backgroundRotation,
      environmentIntensity,
      environmentRotation
    });
  }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
  let count = 1;
  useFrame(() => {
    if (frames === Infinity || count < frames) {
      const autoClear = gl.autoClear;
      gl.autoClear = true;
      camera.current.update(gl, virtualScene);
      gl.autoClear = autoClear;
      count++;
    }
  });
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, createPortal(/* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, children, /* @__PURE__ */ reactExports.createElement("cubeCamera", {
    ref: camera,
    args: [near, far, fbo]
  }), files || preset ? /* @__PURE__ */ reactExports.createElement(EnvironmentCube, {
    background: true,
    files,
    preset,
    path,
    extensions
  }) : map ? /* @__PURE__ */ reactExports.createElement(EnvironmentMap, {
    background: true,
    map,
    extensions
  }) : null), virtualScene));
}
function EnvironmentGround(props) {
  var _props$ground, _props$ground2, _scale2, _props$ground3;
  const textureDefault = useEnvironment(props);
  const texture = props.map || textureDefault;
  reactExports.useMemo(() => extend({
    GroundProjectedEnvImpl: GroundProjectedEnv
  }), []);
  reactExports.useEffect(() => {
    return () => {
      textureDefault.dispose();
    };
  }, [textureDefault]);
  const args = reactExports.useMemo(() => [texture], [texture]);
  const height = (_props$ground = props.ground) == null ? void 0 : _props$ground.height;
  const radius = (_props$ground2 = props.ground) == null ? void 0 : _props$ground2.radius;
  const scale = (_scale2 = (_props$ground3 = props.ground) == null ? void 0 : _props$ground3.scale) !== null && _scale2 !== void 0 ? _scale2 : 1e3;
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(EnvironmentMap, _extends({}, props, {
    map: texture
  })), /* @__PURE__ */ reactExports.createElement("groundProjectedEnvImpl", {
    args,
    scale,
    height,
    radius
  }));
}
function Environment(props) {
  return props.ground ? /* @__PURE__ */ reactExports.createElement(EnvironmentGround, props) : props.map ? /* @__PURE__ */ reactExports.createElement(EnvironmentMap, props) : props.children ? /* @__PURE__ */ reactExports.createElement(EnvironmentPortal, props) : /* @__PURE__ */ reactExports.createElement(EnvironmentCube, props);
}
const ContactShadows = /* @__PURE__ */ reactExports.forwardRef(({
  scale = 10,
  frames = Infinity,
  opacity = 1,
  width = 1,
  height = 1,
  blur = 1,
  near = 0,
  far = 10,
  resolution = 512,
  smooth = true,
  color = "#000000",
  depthWrite = false,
  renderOrder,
  ...props
}, fref) => {
  const ref = reactExports.useRef(null);
  const scene = useThree((state) => state.scene);
  const gl = useThree((state) => state.gl);
  const shadowCamera = reactExports.useRef(null);
  width = width * (Array.isArray(scale) ? scale[0] : scale || 1);
  height = height * (Array.isArray(scale) ? scale[1] : scale || 1);
  const [renderTarget, planeGeometry, depthMaterial, blurPlane, horizontalBlurMaterial, verticalBlurMaterial, renderTargetBlur] = reactExports.useMemo(() => {
    const renderTarget2 = new WebGLRenderTarget(resolution, resolution);
    const renderTargetBlur2 = new WebGLRenderTarget(resolution, resolution);
    renderTargetBlur2.texture.generateMipmaps = renderTarget2.texture.generateMipmaps = false;
    const planeGeometry2 = new PlaneGeometry(width, height).rotateX(Math.PI / 2);
    const blurPlane2 = new Mesh(planeGeometry2);
    const depthMaterial2 = new MeshDepthMaterial();
    depthMaterial2.depthTest = depthMaterial2.depthWrite = false;
    depthMaterial2.onBeforeCompile = (shader) => {
      shader.uniforms = {
        ...shader.uniforms,
        ucolor: {
          value: new Color(color)
        }
      };
      shader.fragmentShader = shader.fragmentShader.replace(
        `void main() {`,
        //
        `uniform vec3 ucolor;
           void main() {
          `
      );
      shader.fragmentShader = shader.fragmentShader.replace(
        "vec4( vec3( 1.0 - fragCoordZ ), opacity );",
        // Colorize the shadow, multiply by the falloff so that the center can remain darker
        "vec4( ucolor * fragCoordZ * 2.0, ( 1.0 - fragCoordZ ) * 1.0 );"
      );
    };
    const horizontalBlurMaterial2 = new ShaderMaterial(HorizontalBlurShader);
    const verticalBlurMaterial2 = new ShaderMaterial(VerticalBlurShader);
    verticalBlurMaterial2.depthTest = horizontalBlurMaterial2.depthTest = false;
    return [renderTarget2, planeGeometry2, depthMaterial2, blurPlane2, horizontalBlurMaterial2, verticalBlurMaterial2, renderTargetBlur2];
  }, [resolution, width, height, scale, color]);
  const blurShadows = (blur2) => {
    blurPlane.visible = true;
    blurPlane.material = horizontalBlurMaterial;
    horizontalBlurMaterial.uniforms.tDiffuse.value = renderTarget.texture;
    horizontalBlurMaterial.uniforms.h.value = blur2 * 1 / 256;
    gl.setRenderTarget(renderTargetBlur);
    gl.render(blurPlane, shadowCamera.current);
    blurPlane.material = verticalBlurMaterial;
    verticalBlurMaterial.uniforms.tDiffuse.value = renderTargetBlur.texture;
    verticalBlurMaterial.uniforms.v.value = blur2 * 1 / 256;
    gl.setRenderTarget(renderTarget);
    gl.render(blurPlane, shadowCamera.current);
    blurPlane.visible = false;
  };
  let count = 0;
  let initialBackground;
  let initialOverrideMaterial;
  useFrame(() => {
    if (shadowCamera.current && (frames === Infinity || count < frames)) {
      count++;
      initialBackground = scene.background;
      initialOverrideMaterial = scene.overrideMaterial;
      ref.current.visible = false;
      scene.background = null;
      scene.overrideMaterial = depthMaterial;
      gl.setRenderTarget(renderTarget);
      gl.render(scene, shadowCamera.current);
      blurShadows(blur);
      if (smooth) blurShadows(blur * 0.4);
      gl.setRenderTarget(null);
      ref.current.visible = true;
      scene.overrideMaterial = initialOverrideMaterial;
      scene.background = initialBackground;
    }
  });
  reactExports.useImperativeHandle(fref, () => ref.current, []);
  return /* @__PURE__ */ reactExports.createElement("group", _extends({
    "rotation-x": Math.PI / 2
  }, props, {
    ref
  }), /* @__PURE__ */ reactExports.createElement("mesh", {
    renderOrder,
    geometry: planeGeometry,
    scale: [1, -1, 1],
    rotation: [-Math.PI / 2, 0, 0]
  }, /* @__PURE__ */ reactExports.createElement("meshBasicMaterial", {
    transparent: true,
    map: renderTarget.texture,
    opacity,
    depthWrite
  })), /* @__PURE__ */ reactExports.createElement("orthographicCamera", {
    ref: shadowCamera,
    args: [-width / 2, width / 2, height / 2, -height / 2, near, far]
  }));
});
function isLight(object) {
  return object.isLight;
}
function isGeometry(object) {
  return !!object.geometry;
}
const accumulativeContext = /* @__PURE__ */ reactExports.createContext(null);
const SoftShadowMaterial = /* @__PURE__ */ shaderMaterial({
  color: /* @__PURE__ */ new Color(),
  blend: 2,
  alphaTest: 0.75,
  opacity: 0,
  map: null
}, `varying vec2 vUv;
   void main() {
     gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.);
     vUv = uv;
   }`, `varying vec2 vUv;
   uniform sampler2D map;
   uniform vec3 color;
   uniform float opacity;
   uniform float alphaTest;
   uniform float blend;
   void main() {
     vec4 sampledDiffuseColor = texture2D(map, vUv);
     gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity);
     #include <tonemapping_fragment>
     #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}>
   }`);
const AccumulativeShadows = /* @__PURE__ */ reactExports.forwardRef(({
  children,
  temporal,
  frames = 40,
  limit = Infinity,
  blend = 20,
  scale = 10,
  opacity = 1,
  alphaTest = 0.75,
  color = "black",
  colorBlend = 2,
  resolution = 1024,
  toneMapped = true,
  ...props
}, forwardRef) => {
  extend({
    SoftShadowMaterial
  });
  const gl = useThree((state) => state.gl);
  const scene = useThree((state) => state.scene);
  const camera = useThree((state) => state.camera);
  const invalidate2 = useThree((state) => state.invalidate);
  const gPlane = reactExports.useRef(null);
  const gLights = reactExports.useRef(null);
  const [plm] = reactExports.useState(() => new ProgressiveLightMap(gl, scene, resolution));
  reactExports.useLayoutEffect(() => {
    plm.configure(gPlane.current);
  }, []);
  const api = reactExports.useMemo(() => ({
    lights: /* @__PURE__ */ new Map(),
    temporal: !!temporal,
    frames: Math.max(2, frames),
    blend: Math.max(2, frames === Infinity ? blend : frames),
    count: 0,
    getMesh: () => gPlane.current,
    reset: () => {
      plm.clear();
      const material = gPlane.current.material;
      material.opacity = 0;
      material.alphaTest = 0;
      api.count = 0;
    },
    update: (frames2 = 1) => {
      const material = gPlane.current.material;
      if (!api.temporal) {
        material.opacity = opacity;
        material.alphaTest = alphaTest;
      } else {
        material.opacity = Math.min(opacity, material.opacity + opacity / api.blend);
        material.alphaTest = Math.min(alphaTest, material.alphaTest + alphaTest / api.blend);
      }
      gLights.current.visible = true;
      plm.prepare();
      for (let i2 = 0; i2 < frames2; i2++) {
        api.lights.forEach((light) => light.update());
        plm.update(camera, api.blend);
      }
      gLights.current.visible = false;
      plm.finish();
    }
  }), [plm, camera, scene, temporal, frames, blend, opacity, alphaTest]);
  reactExports.useLayoutEffect(() => {
    api.reset();
    if (!api.temporal && api.frames !== Infinity) api.update(api.blend);
  });
  reactExports.useImperativeHandle(forwardRef, () => api, [api]);
  useFrame(() => {
    if ((api.temporal || api.frames === Infinity) && api.count < api.frames && api.count < limit) {
      invalidate2();
      api.update();
      api.count++;
    }
  });
  return /* @__PURE__ */ reactExports.createElement("group", props, /* @__PURE__ */ reactExports.createElement("group", {
    traverse: () => null,
    ref: gLights
  }, /* @__PURE__ */ reactExports.createElement(accumulativeContext.Provider, {
    value: api
  }, children)), /* @__PURE__ */ reactExports.createElement("mesh", {
    receiveShadow: true,
    ref: gPlane,
    scale,
    rotation: [-Math.PI / 2, 0, 0]
  }, /* @__PURE__ */ reactExports.createElement("planeGeometry", null), /* @__PURE__ */ reactExports.createElement("softShadowMaterial", {
    transparent: true,
    depthWrite: false,
    toneMapped,
    color,
    blend: colorBlend,
    map: plm.progressiveLightMap2.texture
  })));
});
const RandomizedLight = /* @__PURE__ */ reactExports.forwardRef(({
  castShadow = true,
  bias = 1e-3,
  mapSize = 512,
  size = 5,
  near = 0.5,
  far = 500,
  frames = 1,
  position = [0, 0, 0],
  radius = 1,
  amount = 8,
  intensity = version >= 155 ? Math.PI : 1,
  ambient = 0.5,
  ...props
}, forwardRef) => {
  const gLights = reactExports.useRef(null);
  const length = new Vector3(...position).length();
  const parent = reactExports.useContext(accumulativeContext);
  const update = reactExports.useCallback(() => {
    let light;
    if (gLights.current) {
      for (let l2 = 0; l2 < gLights.current.children.length; l2++) {
        light = gLights.current.children[l2];
        if (Math.random() > ambient) {
          light.position.set(position[0] + MathUtils.randFloatSpread(radius), position[1] + MathUtils.randFloatSpread(radius), position[2] + MathUtils.randFloatSpread(radius));
        } else {
          let lambda = Math.acos(2 * Math.random() - 1) - Math.PI / 2;
          let phi = 2 * Math.PI * Math.random();
          light.position.set(Math.cos(lambda) * Math.cos(phi) * length, Math.abs(Math.cos(lambda) * Math.sin(phi) * length), Math.sin(lambda) * length);
        }
      }
    }
  }, [radius, ambient, length, ...position]);
  const api = reactExports.useMemo(() => ({
    update
  }), [update]);
  reactExports.useImperativeHandle(forwardRef, () => api, [api]);
  reactExports.useLayoutEffect(() => {
    var _parent$lights;
    const group = gLights.current;
    if (parent) (_parent$lights = parent.lights) == null || _parent$lights.set(group.uuid, api);
    return () => {
      var _parent$lights2;
      return void (parent == null || (_parent$lights2 = parent.lights) == null ? void 0 : _parent$lights2.delete(group.uuid));
    };
  }, [parent, api]);
  return /* @__PURE__ */ reactExports.createElement("group", _extends({
    ref: gLights
  }, props), Array.from({
    length: amount
  }, (_2, index) => /* @__PURE__ */ reactExports.createElement("directionalLight", {
    key: index,
    castShadow,
    "shadow-bias": bias,
    "shadow-mapSize": [mapSize, mapSize],
    intensity: intensity / amount
  }, /* @__PURE__ */ reactExports.createElement("orthographicCamera", {
    attach: "shadow-camera",
    args: [-size, size, size, -size, near, far]
  }))));
});
class ProgressiveLightMap {
  constructor(renderer, scene, res = 1024) {
    this.renderer = renderer;
    this.res = res;
    this.scene = scene;
    this.buffer1Active = false;
    this.lights = [];
    this.meshes = [];
    this.object = null;
    this.clearColor = new Color();
    this.clearAlpha = 0;
    const textureParams = {
      type: HalfFloatType,
      magFilter: NearestFilter,
      minFilter: NearestFilter
    };
    this.progressiveLightMap1 = new WebGLRenderTarget(this.res, this.res, textureParams);
    this.progressiveLightMap2 = new WebGLRenderTarget(this.res, this.res, textureParams);
    this.discardMat = new DiscardMaterial();
    this.targetMat = new MeshLambertMaterial({
      fog: false
    });
    this.previousShadowMap = {
      value: this.progressiveLightMap1.texture
    };
    this.averagingWindow = {
      value: 100
    };
    this.targetMat.onBeforeCompile = (shader) => {
      shader.vertexShader = "varying vec2 vUv;\n" + shader.vertexShader.slice(0, -1) + "vUv = uv; gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }";
      const bodyStart = shader.fragmentShader.indexOf("void main() {");
      shader.fragmentShader = "varying vec2 vUv;\n" + shader.fragmentShader.slice(0, bodyStart) + "uniform sampler2D previousShadowMap;\n	uniform float averagingWindow;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + `
vec3 texelOld = texture2D(previousShadowMap, vUv).rgb;
        gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/ averagingWindow);
      }`;
      shader.uniforms.previousShadowMap = this.previousShadowMap;
      shader.uniforms.averagingWindow = this.averagingWindow;
    };
  }
  clear() {
    this.renderer.getClearColor(this.clearColor);
    this.clearAlpha = this.renderer.getClearAlpha();
    this.renderer.setClearColor("black", 1);
    this.renderer.setRenderTarget(this.progressiveLightMap1);
    this.renderer.clear();
    this.renderer.setRenderTarget(this.progressiveLightMap2);
    this.renderer.clear();
    this.renderer.setRenderTarget(null);
    this.renderer.setClearColor(this.clearColor, this.clearAlpha);
    this.lights = [];
    this.meshes = [];
    this.scene.traverse((object) => {
      if (isGeometry(object)) {
        this.meshes.push({
          object,
          material: object.material
        });
      } else if (isLight(object)) {
        this.lights.push({
          object,
          intensity: object.intensity
        });
      }
    });
  }
  prepare() {
    this.lights.forEach((light) => light.object.intensity = 0);
    this.meshes.forEach((mesh) => mesh.object.material = this.discardMat);
  }
  finish() {
    this.lights.forEach((light) => light.object.intensity = light.intensity);
    this.meshes.forEach((mesh) => mesh.object.material = mesh.material);
  }
  configure(object) {
    this.object = object;
  }
  update(camera, blendWindow = 100) {
    if (!this.object) return;
    this.averagingWindow.value = blendWindow;
    this.object.material = this.targetMat;
    const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
    const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
    const oldBg = this.scene.background;
    this.scene.background = null;
    this.renderer.setRenderTarget(activeMap);
    this.previousShadowMap.value = inactiveMap.texture;
    this.buffer1Active = !this.buffer1Active;
    this.renderer.render(this.scene, camera);
    this.renderer.setRenderTarget(null);
    this.scene.background = oldBg;
  }
}
const presets = {
  rembrandt: {
    main: [1, 2, 1],
    fill: [-2, -0.5, -2]
  },
  portrait: {
    main: [-1, 2, 0.5],
    fill: [-1, 0.5, -1.5]
  },
  upfront: {
    main: [0, 2, 1],
    fill: [-1, 0.5, -1.5]
  },
  soft: {
    main: [-2, 4, 4],
    fill: [-1, 0.5, -1.5]
  }
};
function Refit({
  radius,
  adjustCamera
}) {
  const api = useBounds();
  reactExports.useEffect(() => {
    if (adjustCamera) api.refresh().clip().fit();
  }, [radius, adjustCamera]);
  return null;
}
function Stage({
  children,
  center,
  adjustCamera = true,
  intensity = 0.5,
  shadows = "contact",
  environment = "city",
  preset = "rembrandt",
  ...props
}) {
  var _bias, _normalBias, _size, _offset2, _amount, _radius, _ambient, _intensity;
  const config = typeof preset === "string" ? presets[preset] : preset;
  const [{
    radius,
    height
  }, set] = reactExports.useState({
    radius: 0,
    width: 0,
    height: 0,
    depth: 0
  });
  const shadowBias = (_bias = shadows == null ? void 0 : shadows.bias) !== null && _bias !== void 0 ? _bias : -1e-4;
  const normalBias = (_normalBias = shadows == null ? void 0 : shadows.normalBias) !== null && _normalBias !== void 0 ? _normalBias : 0;
  const shadowSize = (_size = shadows == null ? void 0 : shadows.size) !== null && _size !== void 0 ? _size : 1024;
  const shadowOffset = (_offset2 = shadows == null ? void 0 : shadows.offset) !== null && _offset2 !== void 0 ? _offset2 : 0;
  const contactShadow = shadows === "contact" || (shadows == null ? void 0 : shadows.type) === "contact";
  const accumulativeShadow = shadows === "accumulative" || (shadows == null ? void 0 : shadows.type) === "accumulative";
  const shadowSpread = {
    ...typeof shadows === "object" ? shadows : {}
  };
  const environmentProps = !environment ? null : typeof environment === "string" ? {
    preset: environment
  } : environment;
  const onCentered = reactExports.useCallback((props2) => {
    const {
      width,
      height: height2,
      depth,
      boundingSphere
    } = props2;
    set({
      radius: boundingSphere.radius,
      width,
      height: height2,
      depth
    });
    if (center != null && center.onCentered) center.onCentered(props2);
  }, []);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement("ambientLight", {
    intensity: intensity / 3
  }), /* @__PURE__ */ reactExports.createElement("spotLight", {
    penumbra: 1,
    position: [config.main[0] * radius, config.main[1] * radius, config.main[2] * radius],
    intensity: intensity * 2,
    castShadow: !!shadows,
    "shadow-bias": shadowBias,
    "shadow-normalBias": normalBias,
    "shadow-mapSize": shadowSize
  }), /* @__PURE__ */ reactExports.createElement("pointLight", {
    position: [config.fill[0] * radius, config.fill[1] * radius, config.fill[2] * radius],
    intensity
  }), /* @__PURE__ */ reactExports.createElement(Bounds, _extends({
    fit: !!adjustCamera,
    clip: !!adjustCamera,
    margin: Number(adjustCamera),
    observe: true
  }, props), /* @__PURE__ */ reactExports.createElement(Refit, {
    radius,
    adjustCamera
  }), /* @__PURE__ */ reactExports.createElement(Center, _extends({}, center, {
    position: [0, shadowOffset / 2, 0],
    onCentered
  }), children)), /* @__PURE__ */ reactExports.createElement("group", {
    position: [0, -height / 2 - shadowOffset / 2, 0]
  }, contactShadow && /* @__PURE__ */ reactExports.createElement(ContactShadows, _extends({
    scale: radius * 4,
    far: radius,
    blur: 2
  }, shadowSpread)), accumulativeShadow && /* @__PURE__ */ reactExports.createElement(AccumulativeShadows, _extends({
    temporal: true,
    frames: 100,
    alphaTest: 0.9,
    toneMapped: true,
    scale: radius * 4
  }, shadowSpread), /* @__PURE__ */ reactExports.createElement(RandomizedLight, {
    amount: (_amount = shadowSpread.amount) !== null && _amount !== void 0 ? _amount : 8,
    radius: (_radius = shadowSpread.radius) !== null && _radius !== void 0 ? _radius : radius,
    ambient: (_ambient = shadowSpread.ambient) !== null && _ambient !== void 0 ? _ambient : 0.5,
    intensity: (_intensity = shadowSpread.intensity) !== null && _intensity !== void 0 ? _intensity : 1,
    position: [config.main[0] * radius, config.main[1] * radius, config.main[2] * radius],
    size: radius * 4,
    bias: -shadowBias,
    mapSize: shadowSize
  }))), environment && /* @__PURE__ */ reactExports.createElement(Environment, environmentProps));
}
const LShape = ({
  bottomWidth = 1,
  topWidth = 0.5,
  edgeHeight = 0.5,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const shape2 = new Shape();
    shape2.moveTo(-bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(-bottomWidth / 2 + topWidth, -height / 2 + edgeHeight);
    shape2.lineTo(-bottomWidth / 2 + topWidth, height / 2);
    shape2.lineTo(-bottomWidth / 2, height / 2);
    shape2.lineTo(-bottomWidth / 2, -height / 2);
    return shape2;
  }, [bottomWidth, topWidth, edgeHeight, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const WedgeSeat = ({
  width = 1,
  edgeHeight = 0.5,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const shape2 = new Shape();
    shape2.moveTo(-width / 2, -height / 2);
    shape2.lineTo(width / 2, -height / 2);
    shape2.lineTo(width / 2, -height / 2 + edgeHeight);
    shape2.lineTo(-width / 2, height / 2);
    shape2.lineTo(-width / 2, -height / 2);
    return shape2;
  }, [width, edgeHeight, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const ClippedBolster = ({
  bottomWidth = 1,
  topWidth = 0.5,
  edgeHeight = 0.5,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const shape2 = new Shape();
    shape2.moveTo(-bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(-bottomWidth / 2 + topWidth, height / 2);
    shape2.lineTo(-bottomWidth / 2, height / 2);
    shape2.lineTo(-bottomWidth / 2, -height / 2);
    return shape2;
  }, [bottomWidth, topWidth, edgeHeight, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const Bolster = ({
  bottomWidth = 1,
  topWidth = 0.5,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const shape2 = new Shape();
    shape2.moveTo(-bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2);
    shape2.lineTo(-bottomWidth / 2 + topWidth, height / 2);
    shape2.lineTo(-bottomWidth / 2, height / 2);
    shape2.lineTo(-bottomWidth / 2, -height / 2);
    return shape2;
  }, [bottomWidth, topWidth, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const TShape = ({
  bottomWidth = 1,
  topWidth = 0.5,
  edgeHeight = 0.5,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const shape2 = new Shape();
    shape2.moveTo(-bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2);
    shape2.lineTo(bottomWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(topWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(topWidth / 2, height / 2);
    shape2.lineTo(-topWidth / 2, height / 2);
    shape2.lineTo(-topWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(-bottomWidth / 2, -height / 2 + edgeHeight);
    shape2.lineTo(-bottomWidth / 2, -height / 2);
    return shape2;
  }, [bottomWidth, topWidth, edgeHeight, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const RoundedRectangle = ({
  width = 1,
  height = 1,
  depth = 0.1,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const cornerRadius = Math.min(width, height) * 0.3;
    const shape2 = new Shape();
    shape2.moveTo(-width / 2, -height / 2);
    shape2.lineTo(width / 2, -height / 2);
    shape2.lineTo(width / 2, height / 2 - cornerRadius);
    shape2.absarc(
      width / 2 - cornerRadius,
      height / 2 - cornerRadius,
      cornerRadius,
      0,
      Math.PI / 2,
      false
    );
    shape2.lineTo(-width / 2, height / 2);
    shape2.lineTo(-width / 2, -height / 2);
    return shape2;
  }, [width, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const Rectangle = ({
  width = 1,
  height = 1,
  depth = 1,
  color = "lightblue"
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { args: [width, height, depth], castShadow: true, receiveShadow: true, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { linewidth: 1, threshold: 15, color: "black" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Outlines, { thickness: 0.01, color: "black" })
  ] });
};
const Circle = ({
  diameter = 1,
  depth = 1,
  color = "lightblue"
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { castShadow: true, receiveShadow: true, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("cylinderGeometry", { args: [diameter / 2, diameter / 2, depth, 32] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { linewidth: 1, threshold: 15, color: "black" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Outlines, { thickness: 0.01, color: "black" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color })
  ] });
};
const Semicircle = ({
  diameter = 1,
  depth = 1,
  color = "lightblue"
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("group", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { castShadow: true, receiveShadow: true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "cylinderGeometry",
        {
          args: [diameter / 2, diameter / 2, depth, 32, 1, false, 0, Math.PI]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { linewidth: 1, threshold: 15, color: "black" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Outlines, { thickness: 0.01, color: "black" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { rotation: [0, Math.PI / 2, Math.PI / 2], castShadow: true, receiveShadow: true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("planeGeometry", { args: [depth, diameter] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color: "lightblue", side: 2 })
    ] })
  ] });
};
const Bullnose = ({
  width = 1,
  height = 1,
  depth = 1,
  color = "lightblue"
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("group", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { args: [width - height / 2, height, depth], castShadow: true, receiveShadow: true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { linewidth: 1, threshold: 15, color: "black" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Outlines, { thickness: 0.01, color: "black" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { rotation: [Math.PI / 2, Math.PI / 2, 0], castShadow: true, receiveShadow: true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "cylinderGeometry",
        {
          args: [
            height / 2,
            height / 2,
            depth,
            32,
            1,
            false,
            -Math.PI / 2,
            Math.PI
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { linewidth: 1, threshold: 15, color: "black" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Outlines, { thickness: 0.01, color: "black" })
    ] })
  ] });
};
const Wedge = ({
  width = 1,
  height = 1,
  depth = 1,
  color = "lightblue"
}) => {
  const geometry = React.useMemo(() => {
    const vertices = new Float32Array([
      -width / 2,
      -height / 2,
      -depth / 2,
      width / 2,
      -height / 2,
      -depth / 2,
      width / 2,
      height / 2,
      -depth / 2,
      -width / 2,
      height / 2,
      -depth / 2,
      -width / 2,
      -height / 2,
      depth / 2,
      width / 2,
      -height / 2,
      depth / 2,
      width / 2,
      height / 2,
      depth / 2,
      -width / 2,
      height / 2,
      depth / 2
    ]);
    const indices = [
      0,
      1,
      2,
      0,
      2,
      3,
      // back
      4,
      5,
      6,
      4,
      6,
      7,
      // front
      0,
      4,
      7,
      0,
      7,
      3,
      // left
      1,
      5,
      6,
      1,
      6,
      2,
      // right
      3,
      2,
      6,
      3,
      6,
      7,
      // top
      0,
      1,
      5,
      0,
      5,
      4
      // bottom
    ];
    const geom = new BufferGeometry();
    geom.setAttribute("position", new BufferAttribute(vertices, 3));
    geom.setIndex(indices);
    geom.computeVertexNormals();
    return geom;
  }, [width, height, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, castShadow: true, receiveShadow: true, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const Trapezium = ({
  width = 600,
  topWidth = 400,
  height = 400,
  depth = 100,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const s2 = new Shape();
    const xOffset = (width - topWidth) / 2;
    s2.moveTo(-width / 2, -height / 2);
    s2.lineTo(width / 2, -height / 2);
    s2.lineTo(width / 2 - xOffset, height / 2);
    s2.lineTo(-width / 2 + xOffset, height / 2);
    s2.lineTo(-width / 2, -height / 2);
    return s2;
  }, [width, topWidth, height]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const BoatMattress = ({
  width = 1800,
  topWidth = 900,
  bottomWidth = 600,
  depth = 150,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const s2 = new Shape();
    s2.moveTo(-topWidth / 2, -width / 2);
    s2.lineTo(topWidth / 2, -width / 2);
    s2.lineTo(bottomWidth / 2, width / 2);
    s2.lineTo(-bottomWidth / 2, width / 2);
    s2.lineTo(-topWidth / 2, -width / 2);
    return s2;
  }, [width, topWidth, bottomWidth]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const CurvedL = ({
  width = 600,
  height = 600,
  edgeWidth = 300,
  edgeHeight = 300,
  radius = 100,
  depth = 100,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const s2 = new Shape();
    const r2 = Math.min(radius, edgeWidth, edgeHeight);
    s2.moveTo(-width / 2, -height / 2);
    s2.lineTo(width / 2, -height / 2);
    s2.lineTo(width / 2, -height / 2 + edgeHeight);
    s2.lineTo(-width / 2 + edgeWidth + r2, -height / 2 + edgeHeight);
    s2.quadraticCurveTo(
      -width / 2 + edgeWidth,
      -height / 2 + edgeHeight,
      -width / 2 + edgeWidth,
      -height / 2 + edgeHeight + r2
    );
    s2.lineTo(-width / 2 + edgeWidth, height / 2);
    s2.lineTo(-width / 2, height / 2);
    s2.lineTo(-width / 2, -height / 2);
    return s2;
  }, [width, height, edgeWidth, edgeHeight, radius]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const CurvedT = ({
  width = 800,
  height = 600,
  innerWidth = 400,
  edgeHeight = 300,
  radius = 100,
  depth = 100,
  color = "lightblue"
}) => {
  const shape = React.useMemo(() => {
    const s2 = new Shape();
    const sideW = (width - innerWidth) / 2;
    const r2 = Math.min(radius, sideW, edgeHeight);
    s2.moveTo(-width / 2, -height / 2);
    s2.lineTo(width / 2, -height / 2);
    s2.lineTo(width / 2, -height / 2 + edgeHeight);
    s2.lineTo(width / 2 - sideW + r2, -height / 2 + edgeHeight);
    s2.quadraticCurveTo(
      width / 2 - sideW,
      -height / 2 + edgeHeight,
      width / 2 - sideW,
      -height / 2 + edgeHeight + r2
    );
    s2.lineTo(width / 2 - sideW, height / 2);
    s2.lineTo(-width / 2 + sideW, height / 2);
    s2.lineTo(-width / 2 + sideW, -height / 2 + edgeHeight + r2);
    s2.quadraticCurveTo(
      -width / 2 + sideW,
      -height / 2 + edgeHeight,
      -width / 2 + sideW - r2,
      -height / 2 + edgeHeight
    );
    s2.lineTo(-width / 2, -height / 2 + edgeHeight);
    s2.lineTo(-width / 2, -height / 2);
    return s2;
  }, [width, height, innerWidth, edgeHeight, radius]);
  const geometry = React.useMemo(() => {
    return new ExtrudeGeometry(shape, {
      depth,
      bevelEnabled: false
    });
  }, [shape, depth]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("mesh", { geometry, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("meshStandardMaterial", { color }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Edges, { color: "black" })
  ] });
};
const InputOverlay = ({
  label,
  value,
  onChange,
  style
}) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
  "div",
  {
    className: "absolute flex flex-col items-center pointer-events-auto",
    style,
    children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          type: "number",
          value,
          onChange: (e2) => onChange(parseFloat(e2.target.value) || 0),
          className: "w-16 h-8 text-center border-2 border-blue-500 rounded-lg shadow-lg focus:ring-2 focus:ring-blue-400 focus:outline-none bg-white font-bold text-slate-900 transition-all hover:scale-105"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-500 uppercase tracking-tighter mt-1 bg-white/80 px-1 rounded", children: label })
    ]
  }
);
function ShapeDiagram({
  shape,
  dimensions,
  onDimensionChange
}) {
  const renderDiagram = () => {
    switch (shape) {
      case "rectangle":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("rect", { x: "10", y: "20", width: "80", height: "60", rx: "4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "90",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "95",
                    y1: "20",
                    x2: "95",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "10",
                    markerHeight: "10",
                    refX: "5",
                    refY: "5",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L10,5 L0,10 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", right: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "roundedRectangle":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("rect", { x: "10", y: "20", width: "80", height: "60", rx: "15" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "90",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "95",
                    y1: "20",
                    x2: "95",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", right: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "lShape":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M10 20 h40 v30 h35 v35 h-75 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "50",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "92",
                    x2: "85",
                    y2: "92",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "5",
                    y1: "20",
                    x2: "5",
                    y2: "85",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "90",
                    y1: "50",
                    x2: "90",
                    y2: "85",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Top Width",
              value: dimensions.topWidth,
              onChange: (val) => onDimensionChange("topWidth", val),
              style: { top: "5%", left: "30%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Bottom Width",
              value: dimensions.bottomWidth,
              onChange: (val) => onDimensionChange("bottomWidth", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", left: "0%", transform: "translateY(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Edge",
              value: dimensions.edgeHeight,
              onChange: (val) => onDimensionChange("edgeHeight", val),
              style: { top: "67.5%", right: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "tShape":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M10 20 h80 v30 h-25 v35 h-30 v-35 h-25 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "90",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "35",
                    y1: "92",
                    x2: "65",
                    y2: "92",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "5",
                    y1: "20",
                    x2: "5",
                    y2: "50",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Top Width",
              value: dimensions.topWidth,
              onChange: (val) => onDimensionChange("topWidth", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Bottom Width",
              value: dimensions.bottomWidth,
              onChange: (val) => onDimensionChange("bottomWidth", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "35%", left: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "circle":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("circle", { cx: "50", cy: "50", r: "35" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "15",
                    y1: "50",
                    x2: "85",
                    y2: "50",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Diameter",
              value: dimensions.diameter,
              onChange: (val) => onDimensionChange("diameter", val),
              style: { top: "55%", left: "50%", transform: "translateX(-50%)" }
            }
          )
        ] });
      case "semicircle":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M15 70 a35 35 0 0 1 70 0 Z" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "15",
                    y1: "75",
                    x2: "85",
                    y2: "75",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Diameter",
              value: dimensions.diameter,
              onChange: (val) => onDimensionChange("diameter", val),
              style: {
                bottom: "10%",
                left: "50%",
                transform: "translateX(-50%)"
              }
            }
          )
        ] });
      case "bolster":
      case "clippedBolster":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M15 80 h70 l-20 -60 h-30 z" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "35",
                    y1: "15",
                    x2: "65",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "15",
                    y1: "87",
                    x2: "85",
                    y2: "87",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "20",
                    x2: "10",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Top Width",
              value: dimensions.topWidth,
              onChange: (val) => onDimensionChange("topWidth", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Bottom Width",
              value: dimensions.bottomWidth,
              onChange: (val) => onDimensionChange("bottomWidth", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", left: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "bullnose":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M15 20 h40 a30 30 0 0 1 0 60 h-40 z" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "15",
                    y1: "15",
                    x2: "55",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "20",
                    x2: "10",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "5%", left: "35%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", left: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "wedge":
      case "wedgeSeat":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M15 80 h70 v-60 z" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "15",
                    y1: "87",
                    x2: "85",
                    y2: "87",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "92",
                    y1: "20",
                    x2: "92",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", right: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "trapezium":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M10 80 h80 l-20 -50 h-40 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "30",
                    y1: "25",
                    x2: "70",
                    y2: "25",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "87",
                    x2: "90",
                    y2: "87",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "5",
                    y1: "30",
                    x2: "5",
                    y2: "80",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Top Width",
              value: dimensions.topWidth,
              onChange: (val) => onDimensionChange("topWidth", val),
              style: { top: "15%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Bottom Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "55%", left: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "boatMattress":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M25 20 h50 l15 65 h-80 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "25",
                    y1: "15",
                    x2: "75",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "92",
                    x2: "90",
                    y2: "92",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "5",
                    y1: "20",
                    x2: "5",
                    y2: "85",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Head Width (B)",
              value: dimensions.topWidth,
              onChange: (val) => onDimensionChange("topWidth", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Foot Width (C)",
              value: dimensions.bottomWidth,
              onChange: (val) => onDimensionChange("bottomWidth", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Length (A)",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "50%", left: "0%", transform: "translateY(-50%)" }
            }
          )
        ] });
      case "curvedL":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M10 20 h40 v30 h35 v35 h-75 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "circle",
                  {
                    cx: "50",
                    cy: "50",
                    r: "10",
                    fill: "none",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    strokeDasharray: "2 2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "85",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "5",
                    y1: "20",
                    x2: "5",
                    y2: "85",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Total Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Total Height",
              value: dimensions.height,
              onChange: (val) => onDimensionChange("height", val),
              style: { top: "50%", left: "0%", transform: "translateY(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Radius",
              value: dimensions.radius,
              onChange: (val) => onDimensionChange("radius", val),
              style: { top: "40%", left: "40%" }
            }
          )
        ] });
      case "curvedT":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              viewBox: "0 0 100 100",
              className: "w-full h-full text-blue-200 fill-current overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M10 20 h80 v30 h-25 v35 h-30 v-35 h-25 z", rx: "2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "circle",
                  {
                    cx: "35",
                    cy: "50",
                    r: "8",
                    fill: "none",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    strokeDasharray: "2 2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "circle",
                  {
                    cx: "65",
                    cy: "50",
                    r: "8",
                    fill: "none",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    strokeDasharray: "2 2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "line",
                  {
                    x1: "10",
                    y1: "15",
                    x2: "90",
                    y2: "15",
                    stroke: "#3b82f6",
                    strokeWidth: "1",
                    markerEnd: "url(#arrow)",
                    markerStart: "url(#arrow)"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "marker",
                  {
                    id: "arrow",
                    markerWidth: "6",
                    markerHeight: "6",
                    refX: "3",
                    refY: "3",
                    orient: "auto",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M0,0 L6,3 L0,6 Z", fill: "#3b82f6" })
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Total Width",
              value: dimensions.width,
              onChange: (val) => onDimensionChange("width", val),
              style: { top: "5%", left: "50%", transform: "translateX(-50%)" }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputOverlay,
            {
              label: "Inner Width",
              value: dimensions.innerWidth,
              onChange: (val) => onDimensionChange("innerWidth", val),
              style: { bottom: "0%", left: "50%", transform: "translateX(-50%)" }
            }
          )
        ] });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative w-full max-w-md aspect-square bg-slate-50 rounded-3xl flex items-center justify-center p-12 border border-slate-200", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-48 h-48 bg-blue-100 rounded-2xl mx-auto flex items-center justify-center mb-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-blue-500 font-bold uppercase", children: "Diagram Preview" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 gap-4", children: Object.entries(dimensions).filter(([k2]) => k2 !== "depth").map(([key, value]) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-500 uppercase mb-1", children: key }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                type: "number",
                value,
                onChange: (e2) => onDimensionChange(
                  key,
                  parseFloat(e2.target.value) || 0
                ),
                className: "w-20 h-10 text-center border-2 border-slate-200 rounded-xl focus:border-blue-500 focus:outline-none bg-white font-bold"
              }
            )
          ] }, key)) })
        ] }) });
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full flex justify-center py-8", children: renderDiagram() });
}
const FOAM_TYPE_CONFIG = {
  "medium-firm-white": {
    label: "Medium-Firm White",
    priceMultiplier: 1,
    color: "#f5f5f5"
  },
  "firm-blue": {
    label: "Firm Blue Foam",
    priceMultiplier: 1.15,
    color: "#3b82f6"
  },
  "extra-firm-reconstituted-6lb": {
    label: "Extra-Firm Reconstituted 6LB",
    priceMultiplier: 1.25,
    color: "#6b7280"
  },
  "severe-firm-reconstituted-9lb": {
    label: "Severe-Firm Reconstituted 9LB",
    priceMultiplier: 1.45,
    color: "#374151"
  },
  "luxury-memory-foam": {
    label: "Luxury Memory Foam",
    priceMultiplier: 2,
    color: "#8b5cf6"
  }
};
const ADDITION_CONFIG = {
  none: {
    label: "None",
    priceAddon: 0
  },
  stockinette: {
    label: "Stockinette Covering",
    priceAddon: 15
  },
  "dacron-and-stockinette": {
    label: "Dacron and Stockinette Covering",
    priceAddon: 35
  }
};
const COVER_PRICE = 25;
const FOAM_TYPES = Object.keys(FOAM_TYPE_CONFIG);
const ADDITION_TYPES = Object.keys(ADDITION_CONFIG);
function FoamTypeSelector({
  value,
  onChange
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("fieldset", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("legend", { className: "block text-sm/6 font-medium text-gray-900", children: "Foam Type" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      yt,
      {
        value,
        onChange,
        className: "mt-2 grid grid-cols-1 gap-2",
        children: FOAM_TYPES.map((foamType) => {
          const config = FOAM_TYPE_CONFIG[foamType];
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Ke$1,
            {
              value: foamType,
              className: "group relative flex cursor-pointer rounded-lg border border-gray-300 bg-white p-3 shadow-sm focus:outline-none data-[checked]:border-indigo-600 data-[checked]:ring-2 data-[checked]:ring-indigo-600",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex flex-1 items-center", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: "h-6 w-6 rounded-full border border-gray-200 shrink-0",
                      style: { backgroundColor: config.color }
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-3 flex flex-col", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-sm font-medium text-gray-900", children: config.label }),
                    config.priceMultiplier !== 1 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500", children: [
                      "+",
                      ((config.priceMultiplier - 1) * 100).toFixed(0),
                      "%"
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  ForwardRef$3,
                  {
                    "aria-hidden": "true",
                    className: "size-5 text-indigo-600 group-[:not([data-checked])]:invisible"
                  }
                )
              ]
            },
            foamType
          );
        })
      }
    )
  ] });
}
function AdditionSelector({
  value,
  onChange
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("fieldset", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("legend", { className: "block text-sm/6 font-medium text-gray-900", children: "Optional Additions" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(yt, { value, onChange, className: "mt-2 space-y-2", children: ADDITION_TYPES.map((additionType) => {
      const config = ADDITION_CONFIG[additionType];
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Ke$1,
        {
          value: additionType,
          className: "group flex cursor-pointer items-center gap-3",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex size-5 items-center justify-center rounded-full border border-gray-300 bg-white group-data-[checked]:border-indigo-600 group-data-[checked]:bg-indigo-600", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "size-2 rounded-full bg-white opacity-0 group-data-[checked]:opacity-100" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex flex-1 items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-900", children: config.label }),
              config.priceAddon > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-500", children: [
                "+£",
                config.priceAddon.toFixed(2)
              ] })
            ] })
          ]
        },
        additionType
      );
    }) })
  ] });
}
function CoverCheckbox({ checked, onChange }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          id: "cover",
          name: "cover",
          type: "checkbox",
          checked,
          onChange: (e2) => onChange(e2.target.checked),
          className: "size-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-600"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "cover", className: "text-sm font-medium text-gray-900", children: "Add Cover" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-500", children: [
      "+£",
      COVER_PRICE.toFixed(2)
    ] })
  ] });
}
function PriceBreakdown({ breakdown }) {
  const { foamCost, additionCost, coverCost, postageCost, totalPrice } = breakdown;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg bg-gray-50 p-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium text-gray-900 mb-3", children: "Price Breakdown" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-gray-600", children: "Foam" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: "text-gray-900", children: [
          "£",
          foamCost.toFixed(2)
        ] })
      ] }),
      additionCost > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-gray-600", children: "Addition" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: "text-gray-900", children: [
          "£",
          additionCost.toFixed(2)
        ] })
      ] }),
      coverCost > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-gray-600", children: "Cover" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: "text-gray-900", children: [
          "£",
          coverCost.toFixed(2)
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-gray-600", children: "Postage" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: "text-gray-900", children: [
          "£",
          postageCost.toFixed(2)
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between border-t border-gray-200 pt-2 mt-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "font-medium text-gray-900", children: "Total" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: "font-medium text-gray-900", children: [
          "£",
          totalPrice.toFixed(2)
        ] })
      ] })
    ] })
  ] });
}
const BASE_PRICE_PER_CUBIC_INCH = 0.35;
const WHITE_PRICE = 0.35;
const GREY_PRICE = 0.4;
const DARK_BLUE_PRICE = 0.45;
const FOAM_ONLY_PERCENTAGE = 0.56;
const FEES_PERCENTAGE = 0.15;
const convertDimensionsToRectangle = (shape, dimensions) => {
  switch (shape) {
    case "rectangle":
      return dimensions;
    case "roundedRectangle":
      return dimensions;
    case "lShape":
      return {
        width: Math.max(dimensions.bottomWidth, dimensions.topWidth),
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "tShape":
      return {
        width: Math.max(dimensions.bottomWidth, dimensions.topWidth),
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "bolster":
      return {
        width: Math.max(dimensions.bottomWidth, dimensions.topWidth),
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "clippedBolster":
      return {
        width: Math.max(dimensions.bottomWidth, dimensions.topWidth),
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "circle":
      return {
        width: dimensions.diameter,
        height: dimensions.diameter,
        depth: dimensions.depth
      };
    case "semicircle":
      return {
        width: dimensions.diameter,
        height: dimensions.diameter / 2,
        depth: dimensions.depth
      };
    case "bullnose":
      return dimensions;
    case "wedge":
      return dimensions;
    case "wedgeSeat":
      return {
        width: dimensions.width,
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "trapezium":
      return {
        width: Math.max(dimensions.width, dimensions.topWidth),
        height: dimensions.height,
        depth: dimensions.depth
      };
    case "boatMattress":
      return {
        width: dimensions.width,
        height: Math.max(dimensions.topWidth, dimensions.bottomWidth),
        depth: dimensions.depth
      };
    case "curvedL":
    case "curvedT":
      return {
        width: dimensions.width,
        height: dimensions.height,
        depth: dimensions.depth
      };
  }
};
const getPrice = (shape, dimensions) => {
  const cubicInchesArea = dimensions.depth / 2.54 * (dimensions.width / 2.54) * (dimensions.height / 2.54) / 144;
  const whitePrice = cubicInchesArea * WHITE_PRICE;
  const greyPrice = cubicInchesArea * GREY_PRICE;
  const darkBluePrice = cubicInchesArea * DARK_BLUE_PRICE;
  const sides = [dimensions.depth, dimensions.width, dimensions.height].sort(
    (a3, b2) => b2 - a3
  );
  const halvedAndDoubledSizes = [sides[0] / 2, sides[1], sides[2] * 2];
  console.log(halvedAndDoubledSizes);
  const postageVolume = (halvedAndDoubledSizes[0] + halvedAndDoubledSizes[1]) * 2 + halvedAndDoubledSizes[2];
  console.log(postageVolume);
  const postagePrice = postageVolume > 240 ? 7.8 : 3.8;
  const totalWhiteCost = (whitePrice + postagePrice) / (1 - FOAM_ONLY_PERCENTAGE - FEES_PERCENTAGE);
  const totalGreyCost = (greyPrice + postagePrice) / (1 - FOAM_ONLY_PERCENTAGE - FEES_PERCENTAGE);
  const totalDarkBlueCost = (darkBluePrice + postagePrice) / (1 - FOAM_ONLY_PERCENTAGE - FEES_PERCENTAGE);
  return {
    whitePrice,
    greyPrice,
    darkBluePrice,
    totalWhiteCost,
    totalGreyCost,
    totalDarkBlueCost
  };
};
const calculatePrice = (shape, dimensions, foamType, addition, hasCover) => {
  const rectDimensions = convertDimensionsToRectangle(shape, dimensions);
  const cubicInchesArea = rectDimensions.depth / 2.54 * (rectDimensions.width / 2.54) * (rectDimensions.height / 2.54) / 144;
  const foamMultiplier = FOAM_TYPE_CONFIG[foamType].priceMultiplier;
  const baseFoamCost = cubicInchesArea * BASE_PRICE_PER_CUBIC_INCH * foamMultiplier;
  const additionCost = ADDITION_CONFIG[addition].priceAddon;
  const coverCost = hasCover ? COVER_PRICE : 0;
  const sides = [
    rectDimensions.depth,
    rectDimensions.width,
    rectDimensions.height
  ].sort((a3, b2) => b2 - a3);
  const halvedAndDoubledSizes = [sides[0] / 2, sides[1], sides[2] * 2];
  const postageVolume = (halvedAndDoubledSizes[0] + halvedAndDoubledSizes[1]) * 2 + halvedAndDoubledSizes[2];
  const postageCost = postageVolume > 240 ? 7.8 : 3.8;
  const subtotal = baseFoamCost + additionCost + coverCost + postageCost;
  const totalPrice = subtotal / (1 - FOAM_ONLY_PERCENTAGE - FEES_PERCENTAGE);
  return {
    foamCost: Number(baseFoamCost.toFixed(2)),
    additionCost,
    coverCost,
    postageCost,
    totalPrice: Number(totalPrice.toFixed(2))
  };
};
const shapeConfigs = {
  rectangle: {
    fields: {
      width: { default: 500, label: "Width (mm)" },
      height: { default: 500, label: "Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  roundedRectangle: {
    fields: {
      width: { default: 500, label: "Width (mm)" },
      height: { default: 500, label: "Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  lShape: {
    fields: {
      bottomWidth: { default: 600, label: "Bottom Width (mm)" },
      topWidth: { default: 300, label: "Top Width (mm)" },
      edgeHeight: { default: 300, label: "Edge Height (mm)" },
      height: { default: 600, label: "Total Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  tShape: {
    fields: {
      bottomWidth: { default: 600, label: "Bottom Width (mm)" },
      topWidth: { default: 300, label: "Top Width (mm)" },
      edgeHeight: { default: 300, label: "Edge Height (mm)" },
      height: { default: 600, label: "Total Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  bolster: {
    fields: {
      bottomWidth: { default: 400, label: "Bottom Width (mm)" },
      topWidth: { default: 200, label: "Top Width (mm)" },
      height: { default: 200, label: "Height (mm)" },
      depth: { default: 600, label: "Total Length (mm)" }
    }
  },
  clippedBolster: {
    fields: {
      bottomWidth: { default: 400, label: "Bottom Width (mm)" },
      topWidth: { default: 200, label: "Top Width (mm)" },
      edgeHeight: { default: 100, label: "Edge Height (mm)" },
      height: { default: 200, label: "Height (mm)" },
      depth: { default: 600, label: "Total Length (mm)" }
    }
  },
  circle: {
    fields: {
      diameter: { default: 400, label: "Diameter (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  semicircle: {
    fields: {
      diameter: { default: 400, label: "Diameter (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  bullnose: {
    fields: {
      width: { default: 500, label: "Width (mm)" },
      height: { default: 500, label: "Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  wedge: {
    fields: {
      width: { default: 500, label: "Total Width (mm)" },
      height: { default: 500, label: "Total Height (mm)" },
      depth: { default: 500, label: "Total Depth (mm)" }
    }
  },
  wedgeSeat: {
    fields: {
      width: { default: 500, label: "Width (mm)" },
      edgeHeight: { default: 100, label: "Front Edge (mm)" },
      height: { default: 500, label: "Total Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  trapezium: {
    fields: {
      width: { default: 600, label: "Bottom Width (mm)" },
      topWidth: { default: 400, label: "Top Width (mm)" },
      height: { default: 400, label: "Height (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  boatMattress: {
    fields: {
      width: { default: 1800, label: "Length - A (mm)" },
      topWidth: { default: 900, label: "Head Width - B (mm)" },
      bottomWidth: { default: 600, label: "Foot Width - C (mm)" },
      depth: { default: 150, label: "Thickness (mm)" }
    }
  },
  curvedL: {
    fields: {
      width: { default: 600, label: "Total Width (mm)" },
      height: { default: 600, label: "Total Height (mm)" },
      edgeWidth: { default: 300, label: "Edge Width (mm)" },
      edgeHeight: { default: 300, label: "Edge Height (mm)" },
      radius: { default: 100, label: "Corner Radius (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  },
  curvedT: {
    fields: {
      width: { default: 800, label: "Total Width (mm)" },
      height: { default: 600, label: "Total Height (mm)" },
      innerWidth: { default: 400, label: "Inner Width (mm)" },
      edgeHeight: { default: 300, label: "Edge Height (mm)" },
      radius: { default: 100, label: "Corner Radius (mm)" },
      depth: { default: 100, label: "Thickness (mm)" }
    }
  }
};
async function loader$r({ params }) {
  const { shape } = params;
  if (!shape || !shapeConfigs[shape]) {
    throw new Response("Not Found", { status: 404 });
  }
  return json2({ shape });
}
function Preview3D({
  shape,
  dimensions,
  color
}) {
  const ShapeComponent = reactExports.useMemo(() => {
    switch (shape) {
      case "rectangle":
        return Rectangle;
      case "roundedRectangle":
        return RoundedRectangle;
      case "lShape":
        return LShape;
      case "tShape":
        return TShape;
      case "bolster":
        return Bolster;
      case "circle":
        return Circle;
      case "semicircle":
        return Semicircle;
      case "bullnose":
        return Bullnose;
      case "wedge":
        return Wedge;
      case "wedgeSeat":
        return WedgeSeat;
      case "clippedBolster":
        return ClippedBolster;
      case "trapezium":
        return Trapezium;
      case "boatMattress":
        return BoatMattress;
      case "curvedL":
        return CurvedL;
      case "curvedT":
        return CurvedT;
      default:
        return Rectangle;
    }
  }, [shape]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("ambientLight", { intensity: 0.5 }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("hemisphereLight", { intensity: 0.5, groundColor: "#000000" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("directionalLight", { position: [10, 10, 5], intensity: 1, castShadow: true }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("pointLight", { position: [-10, 10, -10], intensity: 0.5 }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "spotLight",
      {
        position: [0, 10, 0],
        angle: 0.3,
        penumbra: 1,
        intensity: 1,
        castShadow: true
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("group", { position: [0, -0.5, 0], children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ShapeComponent, { ...dimensions, color }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContactShadows,
        {
          position: [0, -0.01, 0],
          opacity: 0.4,
          scale: 20,
          blur: 2.5,
          far: 4.5,
          resolution: 256,
          color: "#000000"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      OrbitControls2,
      {
        makeDefault: true,
        minPolarAngle: 0,
        maxPolarAngle: Math.PI / 1.75
      }
    )
  ] });
}
function ShapeConfigurator() {
  const { shape } = useLoaderData();
  const fetcher = useFetcher();
  const [dimensions, setDimensions] = reactExports.useState(() => {
    const config = shapeConfigs[shape];
    const initial = {};
    Object.entries(config.fields).forEach(([key, field]) => {
      initial[key] = field.default;
    });
    return initial;
  });
  const [foamType, setFoamType] = reactExports.useState("medium-firm-white");
  const [addition, setAddition] = reactExports.useState("none");
  const [hasCover, setHasCover] = reactExports.useState(false);
  const priceBreakdown = reactExports.useMemo(() => {
    return calculatePrice(
      shape,
      dimensions,
      foamType,
      addition,
      hasCover
    );
  }, [shape, dimensions, foamType, addition, hasCover]);
  const foamColor = FOAM_TYPE_CONFIG[foamType].color;
  const handleDimensionChange = (key, value) => {
    setDimensions((prev) => ({ ...prev, [key]: value }));
  };
  const handleAddToCart = () => {
    fetcher.submit(
      JSON.stringify({ shape, dimensions, foamType, addition, hasCover }),
      {
        method: "POST",
        action: "/api/create-custom-foam",
        encType: "application/json"
      }
    );
  };
  reactExports.useEffect(() => {
    var _a2, _b2;
    if (((_a2 = fetcher.data) == null ? void 0 : _a2.success) && ((_b2 = fetcher.data) == null ? void 0 : _b2.variantId)) {
      window.location.href = "/cart?cartOpen=false";
    }
  }, [fetcher.data]);
  const isSubmitting = fetcher.state !== "idle";
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-[#f8fafc] min-h-screen", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-7xl mx-auto px-4 py-8 sm:px-6 lg:px-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("nav", { className: "mb-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Link,
      {
        to: "/foam-cut-to-size",
        className: "text-blue-600 hover:text-blue-700 font-medium flex items-center gap-2 transition-colors",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "svg",
            {
              className: "w-4 h-4",
              fill: "none",
              viewBox: "0 0 24 24",
              stroke: "currentColor",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "path",
                {
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: 2,
                  d: "M10 19l-7-7m0 0l7-7m-7 7h18"
                }
              )
            }
          ),
          "Back to Shapes"
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:grid lg:grid-cols-12 lg:gap-8 items-start", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-8 space-y-8 w-full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-8 border-b border-slate-50 flex justify-between items-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl font-extrabold text-slate-900 capitalize", children: shape.replace(/([A-Z])/g, " $1") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-slate-500 mt-1", children: "Enter your custom measurements below" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-blue-50 text-blue-700 px-4 py-2 rounded-2xl font-bold text-sm", children: "Step 2: Dimensions" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ShapeDiagram,
            {
              shape,
              dimensions,
              onDimensionChange: handleDimensionChange
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-8 bg-slate-50/50 flex flex-wrap gap-4 items-center justify-center border-t border-slate-100", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 bg-white px-4 py-2 rounded-xl shadow-sm border border-slate-200", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-bold text-slate-400 uppercase", children: "Input Unit:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold text-slate-900 border-l pl-2 ml-1", children: "mm" })
            ] }),
            dimensions.depth !== void 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 bg-white p-2 pr-4 rounded-2xl shadow-sm border border-blue-100", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "bg-blue-600 text-white w-10 h-10 flex items-center justify-center rounded-xl font-bold text-sm uppercase", children: "T" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-400 uppercase leading-none mb-1", children: "Thickness" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "number",
                    value: dimensions.depth,
                    onChange: (e2) => handleDimensionChange(
                      "depth",
                      parseFloat(e2.target.value) || 0
                    ),
                    className: "bg-transparent font-bold text-slate-900 focus:outline-none w-16"
                  }
                )
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-8 border-b border-slate-50", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-xl font-bold text-slate-900", children: "3D Visualisation" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-slate-500 mt-1", children: "Rotate and zoom to inspect your custom foam" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "h-[500px] relative group", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Canvas2, { shadows: true, camera: { position: [5, 5, 5], fov: 45 }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Preview3D,
              {
                shape,
                dimensions,
                color: foamColor
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute bottom-6 right-6 flex gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white/80 backdrop-blur-md px-4 py-2 rounded-xl text-[10px] font-bold text-slate-500 border border-white shadow-lg pointer-events-none", children: "LEFT CLICK TO ROTATE • SCROLL TO ZOOM" }) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-4 space-y-6 w-full mt-8 lg:mt-0 sticky top-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white rounded-[2.5rem] p-8 shadow-sm border border-slate-100 space-y-8", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(FoamTypeSelector, { value: foamType, onChange: setFoamType }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-px bg-slate-100" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionSelector, { value: addition, onChange: setAddition }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-px bg-slate-100" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CoverCheckbox, { checked: hasCover, onChange: setHasCover }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-px bg-slate-100" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(PriceBreakdown, { breakdown: priceBreakdown }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              onClick: handleAddToCart,
              disabled: isSubmitting,
              className: "w-full bg-blue-600 text-white py-5 rounded-2xl font-bold text-lg shadow-xl shadow-blue-200 hover:bg-blue-700 transition-all hover:-translate-y-1 active:scale-95 disabled:opacity-50 disabled:translate-y-0",
              children: isSubmitting ? "Processing..." : "Add to Cart"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-center text-xs text-slate-400 font-medium", children: "Free Delivery on orders over £50" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-slate-900 rounded-[2.5rem] p-8 shadow-xl text-white", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "font-bold text-lg mb-4 flex items-center gap-2 text-blue-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "svg",
              {
                className: "w-5 h-5",
                fill: "none",
                viewBox: "0 0 24 24",
                stroke: "currentColor",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    strokeWidth: 2,
                    d: "M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  }
                )
              }
            ),
            "Need Help?"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-slate-400 text-sm leading-relaxed mb-6", children: [
            "Call our foam experts at ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: "0800 043 9990" }),
            " for help with measurements or material selection."
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "w-full border border-slate-700 py-3 rounded-xl text-sm font-bold hover:bg-slate-800 transition-colors", children: "Contact Us" })
        ] })
      ] })
    ] })
  ] }) });
}
const route3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ShapeConfigurator,
  loader: loader$r
}, Symbol.toStringTag, { value: "Module" }));
const RectangleIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("rect", { x: "3", y: "3", width: "18", height: "18", rx: "0" }) });
const RoundedRectangleIcon = ({
  className = "w-10 h-10"
}) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("rect", { x: "3", y: "3", width: "18", height: "18", rx: "4" }) });
const LShapeIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 v21 h21 v-9 h-12 v-12" }) });
const TShapeIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 h21 v6 h-6 v15 h-6 v-15 h-6 v-6" }) });
const BolsterIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 v21 h21 L 12 3" }) });
const ClippedBolsterIcon = ({
  className = "w-10 h-10"
}) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 v21 h21 v-9 L 12 3" }) });
const CircleIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "9" }) });
const SemicircleIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 17a9 9 0 0 1 18 0H3z" }) });
const BullnoseIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M16 6 a3 3 0 0 1 3 3 v6 a3 3 0 0 1-3 3 h-12 V6 h3 z" }) });
const WedgeIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 v18 h18" }) });
const WedgeSeatIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M3 3 v18 h18 v-6" }) });
const TrapeziumIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M4 18 h16 l-4 -12 h-8 z" }) });
const BoatMattressIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M8 4 h8 l4 16 h-16 z" }) });
const CurvedLIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M4 4 h8 v8 h8 v8 h-16 z" }) });
const CurvedTIcon = ({ className = "w-10 h-10" }) => /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { className, viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M4 4 h16 v8 h-4 v8 h-8 v-8 h-4 z" }) });
const shapeIcons = {
  rectangle: RectangleIcon,
  roundedRectangle: RoundedRectangleIcon,
  lShape: LShapeIcon,
  tShape: TShapeIcon,
  bolster: BolsterIcon,
  clippedBolster: ClippedBolsterIcon,
  circle: CircleIcon,
  semicircle: SemicircleIcon,
  bullnose: BullnoseIcon,
  wedge: WedgeIcon,
  wedgeSeat: WedgeSeatIcon,
  trapezium: TrapeziumIcon,
  boatMattress: BoatMattressIcon,
  curvedL: CurvedLIcon,
  curvedT: CurvedTIcon
};
async function loader$q() {
  return json2({});
}
const SHAPES = [
  {
    id: "rectangle",
    name: "Square / Rectangle",
    description: "Perfect for cushions, mattresses, and pads."
  },
  {
    id: "roundedRectangle",
    name: "Rounded Rectangle",
    description: "Softened corners for a more refined look."
  },
  {
    id: "lShape",
    name: "L-Shape Cushion",
    description: "Ideal for corner sofa seating."
  },
  {
    id: "tShape",
    name: "T-Shape Cushion",
    description: "Typically used for sofa back or seat cushions."
  },
  {
    id: "bolster",
    name: "Bolster / Trapezium",
    description: "Great for headboards and specialized padding."
  },
  {
    id: "circle",
    name: "Circle / Cylinder",
    description: "For round stools, pillows and bolsters."
  },
  {
    id: "semicircle",
    name: "Semicircle",
    description: "Half-moon shapes for decorative use."
  },
  {
    id: "bullnose",
    name: "Bullnose Cushion",
    description: "Rounded front edge for extra comfort."
  },
  {
    id: "wedge",
    name: "Wedge",
    description: "Slanted cushions for back support."
  },
  { id: "wedgeSeat", name: "Wedge Seat", description: "Ergonomic seat padding." },
  {
    id: "clippedBolster",
    name: "Clipped Bolster",
    description: "Angled bolster for specific fits."
  },
  {
    id: "trapezium",
    name: "Trapezium",
    description: "Four-sided shape with two parallel sides."
  },
  {
    id: "boatMattress",
    name: "Boat Mattress",
    description: "Tapered mattress for marine use."
  },
  {
    id: "curvedL",
    name: "Curved L-Cushion",
    description: "L-shaped cushion with rounded corners."
  },
  {
    id: "curvedT",
    name: "Curved T-Cushion",
    description: "T-shaped cushion with rounded corners."
  }
];
function ShapeGallery() {
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-[#f8fafc] min-h-screen py-16 px-4 sm:px-6 lg:px-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-7xl mx-auto", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center mb-16", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl font-extrabold text-slate-900 sm:text-5xl sm:tracking-tight lg:text-6xl", children: "Foam Cut To Size" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-5 max-w-xl mx-auto text-xl text-slate-500", children: "Select a shape below to start customizing your perfectly sized foam." })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8", children: SHAPES.map((shape) => {
      const Icon = shapeIcons[shape.id];
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: `/foam-cut-to-size/${shape.id}`,
          className: "group flex flex-col bg-white rounded-3xl shadow-sm hover:shadow-xl transition-all duration-300 overflow-hidden border border-slate-100",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-h-1 aspect-w-1 w-full overflow-hidden bg-slate-50 group-hover:bg-blue-50 transition-colors flex items-center justify-center p-12", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-32 h-32 text-blue-600 group-hover:scale-110 transition-transform duration-500 ease-out", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-full h-full" }) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-8", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-bold text-slate-900 group-hover:text-blue-600 transition-colors", children: shape.name }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-2 text-sm text-slate-500 line-clamp-2", children: shape.description }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-6 flex items-center text-blue-600 font-semibold text-sm", children: [
                "Customize Now",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "svg",
                  {
                    className: "ml-2 w-4 h-4 group-hover:translate-x-1 transition-transform",
                    fill: "none",
                    viewBox: "0 0 24 24",
                    stroke: "currentColor",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "path",
                      {
                        strokeLinecap: "round",
                        strokeLinejoin: "round",
                        strokeWidth: 2,
                        d: "M9 5l7 7-7 7"
                      }
                    )
                  }
                )
              ] })
            ] })
          ]
        },
        shape.id
      );
    }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-20 bg-blue-600 rounded-[2.5rem] p-8 sm:p-12 text-white flex flex-col lg:flex-row items-center justify-between shadow-2xl shadow-blue-200", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:max-w-xl text-center lg:text-left", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-3xl font-bold", children: "Need a custom shape?" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-blue-100 text-lg", children: "If you can't find the shape you're looking for, we can still help! Send us a template or drawing and we'll cut it for you." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "mt-8 lg:mt-0 bg-white text-blue-600 px-8 py-4 rounded-2xl font-bold text-lg hover:bg-blue-50 transition-colors shadow-lg shadow-black/10", children: "Contact Support" })
    ] })
  ] }) });
}
const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ShapeGallery,
  loader: loader$q
}, Symbol.toStringTag, { value: "Module" }));
function formatShapeName(shape) {
  const formatted = shape.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase()).trim();
  return formatted;
}
const ADMIN_API_VERSION = "2024-01";
const tokenCaches = /* @__PURE__ */ new WeakMap();
async function getAccessToken(env) {
  const {
    SHOPIFY_ADMIN_CLIENT_ID,
    SHOPIFY_ADMIN_CLIENT_SECRET,
    SHOPIFY_ADMIN_ACCESS_TOKEN,
    PRIVATE_STOREFRONT_API_TOKEN,
    PUBLIC_STORE_DOMAIN
  } = env;
  if (SHOPIFY_ADMIN_CLIENT_ID && SHOPIFY_ADMIN_CLIENT_SECRET) {
    const cached = tokenCaches.get(env);
    if (cached && cached.expiresAt > Date.now() + 5 * 60 * 1e3) {
      return cached.token;
    }
    const params = new URLSearchParams({
      client_id: SHOPIFY_ADMIN_CLIENT_ID,
      client_secret: SHOPIFY_ADMIN_CLIENT_SECRET,
      grant_type: "client_credentials"
    });
    const response = await fetch(
      `https://${PUBLIC_STORE_DOMAIN}/admin/oauth/access_token`,
      {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params.toString()
      }
    );
    if (response.ok) {
      const { access_token, expires_in } = await response.json();
      tokenCaches.set(env, {
        token: access_token,
        expiresAt: Date.now() + (expires_in || 3600) * 1e3
      });
      return access_token;
    }
  }
  if (SHOPIFY_ADMIN_ACCESS_TOKEN) return SHOPIFY_ADMIN_ACCESS_TOKEN;
  if (PRIVATE_STOREFRONT_API_TOKEN == null ? void 0 : PRIVATE_STOREFRONT_API_TOKEN.startsWith("shpat_")) {
    return PRIVATE_STOREFRONT_API_TOKEN;
  }
  throw new Error("Admin API credentials not configured or invalid");
}
async function createProduct(config, env) {
  var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n2, _o2, _p, _q, _r, _s, _t, _u, _v;
  const token = await getAccessToken(env);
  formatShapeName(config.shape);
  ((_a2 = FOAM_TYPE_CONFIG[config.foamType]) == null ? void 0 : _a2.label) || config.foamType;
  ((_b2 = ADDITION_CONFIG[config.addition]) == null ? void 0 : _b2.label) || config.addition;
  const dimensionsStr = Object.entries(config.dimensions).map(([k2, v5]) => `${k2}: ${v5}mm`).join(", ");
  const productCreateMutation = `
    mutation productCreate($input: ProductInput!) {
      productCreate(input: $input) {
        product {
          id
          title
        }
        userErrors {
          field
          message
        }
      }
    }
  `;
  const createResponse = await fetch(
    `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/graphql.json`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": token
      },
      body: JSON.stringify({
        query: productCreateMutation,
        variables: {
          input: {
            title: `Custom Foam - ${config.shape.replace(
              /([A-Z])/g,
              " $1"
            )} - ${config.foamType.replace(/-/g, " ")}`,
            descriptionHtml: `
              <h3>Custom Foam Specifications</h3>
              <p><strong>Shape:</strong> ${config.shape}</p>
              <p><strong>Dimensions:</strong> ${dimensionsStr}</p>
              <p><strong>Foam Type:</strong> ${config.foamType}</p>
              <p><strong>Addition:</strong> ${config.addition}</p>
              <p><strong>Cover:</strong> ${config.hasCover ? "Yes" : "No"}</p>
            `,
            vendor: "Durafoam",
            productType: "Custom Foam"
          }
        }
      })
    }
  );
  if (!createResponse.ok) {
    const errorText = await createResponse.text();
    throw new Error(
      `Admin API failed: ${createResponse.status} - ${errorText}`
    );
  }
  const createData = await createResponse.json();
  if ((_c = createData.errors) == null ? void 0 : _c.length) {
    throw new Error(createData.errors.map((e2) => e2.message).join(", "));
  }
  if ((_f = (_e2 = (_d = createData.data) == null ? void 0 : _d.productCreate) == null ? void 0 : _e2.userErrors) == null ? void 0 : _f.length) {
    throw new Error(
      createData.data.productCreate.userErrors.map((e2) => e2.message).join(", ")
    );
  }
  const productId = (_i = (_h = (_g = createData.data) == null ? void 0 : _g.productCreate) == null ? void 0 : _h.product) == null ? void 0 : _i.id;
  if (!productId) throw new Error("Failed to create product - No ID returned");
  const getProductQuery = `
    query getProduct($id: ID!) {
      product(id: $id) {
        variants(first: 1) {
          edges {
            node {
              id
            }
          }
        }
      }
    }
  `;
  const getResponse = await fetch(
    `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/graphql.json`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": token
      },
      body: JSON.stringify({
        query: getProductQuery,
        variables: { id: productId }
      })
    }
  );
  const getData = await getResponse.json();
  const defaultVariantId = (_l = (_k = (_j = getData.data) == null ? void 0 : _j.product) == null ? void 0 : _k.variants.edges[0]) == null ? void 0 : _l.node.id;
  let variantId;
  if (defaultVariantId) {
    console.log(
      `[Variant Update] Found default variant ID: ${defaultVariantId}`
    );
    console.log(
      `[Variant Update] Attempting to set price to: ${config.price.toFixed(2)}`
    );
    const updateMutation = `
      mutation productVariantsBulkUpdate($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
        productVariantsBulkUpdate(productId: $productId, variants: $variants) {
          productVariants { id price }
          userErrors { field message }
        }
      }
    `;
    const updateRes = await fetch(
      `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/graphql.json`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Shopify-Access-Token": token
        },
        body: JSON.stringify({
          query: updateMutation,
          variables: {
            productId,
            variants: [
              {
                id: defaultVariantId,
                price: config.price.toFixed(2),
                inventoryPolicy: "CONTINUE"
              }
            ]
          }
        })
      }
    );
    const updateData = await updateRes.json();
    console.log(
      `[Variant Update] Response:`,
      JSON.stringify(updateData, null, 2)
    );
    if ((_m = updateData.errors) == null ? void 0 : _m.length) {
      console.error(`[Variant Update] GraphQL Errors:`, updateData.errors);
      throw new Error(
        `Variant Update Failed (GraphQL): ${updateData.errors.map((e2) => e2.message).join(", ")}`
      );
    }
    if ((_p = (_o2 = (_n2 = updateData.data) == null ? void 0 : _n2.productVariantsBulkUpdate) == null ? void 0 : _o2.userErrors) == null ? void 0 : _p.length) {
      console.error(
        `[Variant Update] User Errors:`,
        updateData.data.productVariantsBulkUpdate.userErrors
      );
      throw new Error(
        `Variant Update Failed: ${updateData.data.productVariantsBulkUpdate.userErrors[0].message}`
      );
    }
    const updatedPrice = (_t = (_s = (_r = (_q = updateData.data) == null ? void 0 : _q.productVariantsBulkUpdate) == null ? void 0 : _r.productVariants) == null ? void 0 : _s[0]) == null ? void 0 : _t.price;
    if (updatedPrice && parseFloat(updatedPrice) !== parseFloat(config.price.toFixed(2))) {
      throw new Error(
        `Variant Update Succeeded but Price Mismatch: Expected ${config.price.toFixed(
          2
        )} but got ${updatedPrice}. Raw Response: ${JSON.stringify(
          updateData
        )}`
      );
    }
    variantId = defaultVariantId;
  } else {
    throw new Error("Failed to create/get variant for product");
  }
  const publishMutation = `
    mutation publishablePublish($id: ID!, $input: [PublicationInput!]!) {
      publishablePublish(id: $id, input: $input) {
        publishable {
          availablePublicationsCount {
            count
          }
        }
        userErrors {
          field
          message
        }
      }
    }
  `;
  const publicationsQuery = `
    query {
      publications(first: 10) {
        edges {
          node {
            id
            name
          }
        }
      }
    }
  `;
  const pubResponse = await fetch(
    `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/graphql.json`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": token
      },
      body: JSON.stringify({ query: publicationsQuery })
    }
  );
  const pubData = await pubResponse.json();
  const availablePubs = ((_v = (_u = pubData.data) == null ? void 0 : _u.publications) == null ? void 0 : _v.edges) || [];
  console.log("Available publications count:", availablePubs.length);
  console.log(
    "Publication names:",
    availablePubs.map((p2) => p2.node.name).join(", ")
  );
  if (availablePubs.length > 0) {
    for (const pub of availablePubs) {
      console.log(`[GraphQL] Publishing to: ${pub.node.name}`);
      try {
        await fetch(
          `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/graphql.json`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-Shopify-Access-Token": token
            },
            body: JSON.stringify({
              query: publishMutation,
              variables: {
                id: productId,
                input: [{ publicationId: pub.node.id }]
              }
            })
          }
        );
      } catch (err) {
        console.error(`[GraphQL] Failed for ${pub.node.name}:`, err);
      }
    }
  }
  try {
    const restProductId = productId.split("/").pop();
    console.log(`[REST] Force publishing product ID: ${restProductId}`);
    const restResponse = await fetch(
      `https://${env.PUBLIC_STORE_DOMAIN}/admin/api/${ADMIN_API_VERSION}/products/${restProductId}.json`,
      {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          "X-Shopify-Access-Token": token
        },
        body: JSON.stringify({
          product: {
            id: restProductId,
            published: true
          }
        })
      }
    );
    const restData = await restResponse.json();
    console.log("[REST] Publish response:", JSON.stringify(restData));
  } catch (err) {
    console.error("[REST] Publication fallback failed:", err);
  }
  console.log("Returning variantId:", variantId);
  return variantId;
}
async function action$5({ request, context: context2 }) {
  if (request.method !== "POST") {
    return json2({ error: "Method not allowed" }, { status: 405 });
  }
  try {
    const { shape, dimensions, foamType, addition, hasCover } = await request.json();
    if (!shape || !dimensions || !foamType || addition === void 0) {
      return json2({ error: "Missing fields" }, { status: 400 });
    }
    const priceBreakdown = calculatePrice(
      shape,
      dimensions,
      foamType,
      addition,
      hasCover
    );
    const env = context2.env;
    const variantId = await createProduct(
      {
        shape,
        dimensions,
        foamType,
        addition,
        hasCover,
        price: priceBreakdown.totalPrice
      },
      env
    );
    const { cart, session } = context2;
    let result;
    await new Promise((resolve2) => setTimeout(resolve2, 1500));
    let attempts = 0;
    const maxAttempts = 6;
    while (attempts < maxAttempts) {
      console.log(
        `[Cart] Attempt ${attempts + 1} to add variant ${variantId} to cart...`
      );
      result = await cart.addLines([
        {
          merchandiseId: variantId,
          quantity: 1
        }
      ]);
      const errors = (result == null ? void 0 : result.errors) || (result == null ? void 0 : result.userErrors);
      if (errors && errors.length > 0) {
        console.warn(`[Cart] Attempt ${attempts + 1} failed:`, errors);
        attempts++;
        if (attempts >= maxAttempts) {
          throw new Error(
            `Failed to add to cart after ${maxAttempts} attempts: ` + JSON.stringify(errors)
          );
        }
        await new Promise((resolve2) => setTimeout(resolve2, 1e3));
      } else {
        console.log(
          `[Cart] Successfully added to cart on attempt ${attempts + 1}`
        );
        await new Promise((resolve2) => setTimeout(resolve2, 2e3));
        break;
      }
    }
    const headers = cart.setCartId(result.cart.id);
    headers.append("Set-Cookie", await session.commit());
    return json2(
      {
        success: true,
        variantId,
        price: priceBreakdown.totalPrice,
        priceBreakdown
      },
      { headers }
    );
  } catch (error2) {
    console.error("Error:", error2);
    return json2(
      { error: error2 instanceof Error ? error2.message : "Failed" },
      { status: 500 }
    );
  }
}
const route5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  action: action$5
}, Symbol.toStringTag, { value: "Module" }));
const ORDER_ITEM_FRAGMENT = `#graphql
  fragment OrderItem on Order {
    totalPrice {
      amount
      currencyCode
    }
    subtotal {
      amount
      currencyCode
    }
    totalShipping {
      amount
      currencyCode
    }
    financialStatus
    fulfillments(first: 1) {
      nodes {
        status
        trackingInformation {
          company
          number
          url
        }
      }
    }
    id
    name
    number
    processedAt
    lineItems(first: 5) {
      nodes {
        id
        title
        quantity
        image {
          url
          altText
        }
        price {
          amount
          currencyCode
        }
      }
    }
    shippingAddress {
      address1
      city
      province
      country
    }
  }
`;
const CUSTOMER_ORDERS_FRAGMENT = `#graphql
  fragment CustomerOrders on Customer {
    orders(
      sortKey: PROCESSED_AT,
      reverse: true,
      first: $first,
      last: $last,
      before: $startCursor,
      after: $endCursor
    ) {
      nodes {
        ...OrderItem
      }
      pageInfo {
        hasPreviousPage
        hasNextPage
        endCursor
        startCursor
      }
    }
  }
  ${ORDER_ITEM_FRAGMENT}
`;
const CUSTOMER_ORDERS_QUERY = `#graphql
  ${CUSTOMER_ORDERS_FRAGMENT}
  query CustomerOrders(
    $endCursor: String
    $first: Int
    $last: Int
    $startCursor: String
  ) {
    customer {
      ...CustomerOrders
    }
  }
`;
const meta$b = () => {
  return [{ title: "Orders" }];
};
async function loader$p({ request, context: context2 }) {
  const paginationVariables = fn(request, {
    pageBy: 20
  });
  const { data, errors } = await context2.customerAccount.query(
    CUSTOMER_ORDERS_QUERY,
    {
      variables: {
        ...paginationVariables
      }
    }
  );
  if ((errors == null ? void 0 : errors.length) || !(data == null ? void 0 : data.customer)) {
    throw Error("Customer orders not found");
  }
  return json2(
    { customer: data.customer },
    {
      headers: {
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
function Orders() {
  const { customer } = useLoaderData();
  const { orders } = customer;
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8 lg:pb-24", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-16", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "sr-only", children: "Recent orders" }),
    orders.nodes.length ? /* @__PURE__ */ jsxRuntimeExports.jsx(OrdersList, { orders }) : /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyOrders, {})
  ] }) }) });
}
function OrdersList({ orders }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ln, { connection: orders, children: ({ nodes, isLoading, PreviousLink, NextLink }) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-20", children: [
      nodes.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PreviousLink, { className: "inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed", children: isLoading ? "Loading..." : "← Previous Orders" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-20", children: nodes.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(OrderItem, { order }, order.id)) }),
      nodes.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(NextLink, { className: "inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed", children: isLoading ? "Loading..." : "Next Orders →" }) })
    ] });
  } });
}
function EmptyOrders() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-12", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mx-auto h-12 w-12 text-gray-400 mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      "svg",
      {
        fill: "none",
        viewBox: "0 0 24 24",
        strokeWidth: "1.5",
        stroke: "currentColor",
        className: "w-12 h-12",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            d: "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 mb-2", children: "No orders yet" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 mb-6", children: "You haven't placed any orders yet." }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Link,
      {
        to: "/collections",
        className: "inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",
        children: "Start Shopping"
      }
    )
  ] });
}
function OrderItem({ order }) {
  var _a2;
  const lineItems = flattenConnection(order.lineItems);
  (_a2 = flattenConnection(order.fulfillments)[0]) == null ? void 0 : _a2.status;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "sr-only", children: [
      "Order placed on",
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx("time", { dateTime: order.processedAt, children: new Date(order.processedAt).toLocaleDateString("en-GB", {
        year: "numeric",
        month: "long",
        day: "numeric"
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg bg-gray-50 px-4 py-6 sm:flex sm:items-center sm:justify-between sm:space-x-6 sm:px-6 lg:space-x-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: "flex-auto divide-y divide-gray-200 text-sm text-gray-600 sm:grid sm:grid-cols-3 sm:gap-x-6 sm:divide-y-0 lg:w-1/2 lg:flex-none lg:gap-x-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-sm:flex max-sm:justify-between max-sm:py-6 max-sm:first:pt-0 max-sm:last:pb-0", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "font-medium text-gray-900", children: "Date placed" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "sm:mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("time", { dateTime: order.processedAt, children: new Date(order.processedAt).toLocaleDateString("en-GB", {
            year: "numeric",
            month: "long",
            day: "numeric"
          }) }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-sm:flex max-sm:justify-between max-sm:py-6 max-sm:first:pt-0 max-sm:last:pb-0", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "font-medium text-gray-900", children: "Order number" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "sm:mt-1", children: order.name || order.number })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-sm:flex max-sm:justify-between max-sm:py-6 max-sm:first:pt-0 max-sm:last:pb-0", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "font-medium text-gray-900", children: "Total amount" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "font-medium text-gray-900 sm:mt-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: order.totalPrice }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6 flex flex-col items-end space-y-2 sm:mt-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: `/account/orders/${btoa(order.id)}`,
          className: "flex w-full items-center justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 sm:w-auto",
          children: [
            "View Order",
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "sr-only", children: [
              "for order ",
              order.name || order.number
            ] })
          ]
        }
      ) })
    ] }),
    lineItems.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "mt-4 w-full text-gray-500 sm:mt-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("caption", { className: "sr-only", children: "Products" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "sr-only text-left text-sm text-gray-500 sm:not-sr-only", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "th",
          {
            scope: "col",
            className: "py-3 pr-8 font-normal sm:w-2/5 lg:w-1/3",
            children: "Product"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "th",
          {
            scope: "col",
            className: "hidden w-1/5 py-3 pr-8 font-normal sm:table-cell",
            children: "Quantity"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "th",
          {
            scope: "col",
            className: "hidden py-3 pr-8 font-normal sm:table-cell",
            children: "Price"
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { className: "divide-y divide-gray-200 border-b border-gray-200 text-sm sm:border-t", children: lineItems.map((product, index) => {
        var _a3;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-6 pr-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mr-6 size-16 rounded object-cover bg-gray-100 flex items-center justify-center", children: ((_a3 = product.image) == null ? void 0 : _a3.url) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "img",
              {
                alt: product.image.altText || product.title,
                src: product.image.url,
                className: "w-full h-full object-cover rounded"
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-400 text-xs font-medium", children: product.title.charAt(0).toUpperCase() }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900", children: product.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 sm:hidden", children: [
                "Qty: ",
                product.quantity
              ] })
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "hidden py-6 pr-8 sm:table-cell", children: product.quantity }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "hidden py-6 pr-8 sm:table-cell", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.price }) }) })
        ] }, index);
      }) })
    ] })
  ] }, order.number);
}
const route6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Orders,
  loader: loader$p,
  meta: meta$b
}, Symbol.toStringTag, { value: "Module" }));
const DEFAULT_SEARCH_TYPES = [
  "ARTICLE",
  "COLLECTION",
  "PAGE",
  "PRODUCT",
  "QUERY"
];
async function loader$o({ request, params, context: context2 }) {
  const search = await fetchPredictiveSearchResults({
    params,
    request,
    context: context2
  });
  return json2(search, {
    headers: { "Cache-Control": `max-age=${search.searchTerm ? 60 : 3600}` }
  });
}
async function fetchPredictiveSearchResults({
  params,
  request,
  context: context2
}) {
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const searchTerm = searchParams.get("q") || "";
  const limit = Number(searchParams.get("limit") || 10);
  const rawTypes = String(searchParams.get("type") || "ANY");
  const searchTypes = rawTypes === "ANY" ? DEFAULT_SEARCH_TYPES : rawTypes.split(",").map((t2) => t2.toUpperCase()).filter((t2) => DEFAULT_SEARCH_TYPES.includes(t2));
  if (!searchTerm) {
    return {
      searchResults: { results: null, totalResults: 0 },
      searchTerm,
      searchTypes
    };
  }
  const data = await context2.storefront.query(PREDICTIVE_SEARCH_QUERY, {
    variables: {
      limit,
      limitScope: "EACH",
      searchTerm,
      types: searchTypes
    }
  });
  if (!data) {
    throw new Error("No data returned from Shopify API");
  }
  const searchResults = normalizePredictiveSearchResults(
    data.predictiveSearch,
    params.locale
  );
  return { searchResults, searchTerm, searchTypes };
}
function normalizePredictiveSearchResults(predictiveSearch, locale) {
  let totalResults = 0;
  if (!predictiveSearch) {
    return {
      results: NO_PREDICTIVE_SEARCH_RESULTS,
      totalResults
    };
  }
  const localePrefix = locale ? `/${locale}` : "";
  const results = [];
  if (predictiveSearch.queries.length) {
    results.push({
      type: "queries",
      items: predictiveSearch.queries.map((query2) => {
        const trackingParams = applyTrackingParams(
          query2,
          `q=${encodeURIComponent(query2.text)}`
        );
        totalResults++;
        return {
          __typename: query2.__typename,
          handle: "",
          id: query2.text,
          image: void 0,
          title: query2.text,
          styledTitle: query2.styledText,
          url: `${localePrefix}/search${trackingParams}`
        };
      })
    });
  }
  if (predictiveSearch.products.length) {
    results.push({
      type: "products",
      items: predictiveSearch.products.map(
        (product) => {
          var _a2, _b2, _c;
          totalResults++;
          const trackingParams = applyTrackingParams(product);
          return {
            __typename: product.__typename,
            handle: product.handle,
            id: product.id,
            image: (_c = (_b2 = (_a2 = product.variants) == null ? void 0 : _a2.nodes) == null ? void 0 : _b2[0]) == null ? void 0 : _c.image,
            title: product.title,
            url: `${localePrefix}/products/${product.handle}${trackingParams}`,
            price: product.variants.nodes[0].price
          };
        }
      )
    });
  }
  if (predictiveSearch.collections.length) {
    results.push({
      type: "collections",
      items: predictiveSearch.collections.map(
        (collection) => {
          totalResults++;
          const trackingParams = applyTrackingParams(collection);
          return {
            __typename: collection.__typename,
            handle: collection.handle,
            id: collection.id,
            image: collection.image,
            title: collection.title,
            url: `${localePrefix}/collections/${collection.handle}${trackingParams}`
          };
        }
      )
    });
  }
  if (predictiveSearch.pages.length) {
    results.push({
      type: "pages",
      items: predictiveSearch.pages.map((page) => {
        totalResults++;
        const trackingParams = applyTrackingParams(page);
        return {
          __typename: page.__typename,
          handle: page.handle,
          id: page.id,
          image: void 0,
          title: page.title,
          url: `${localePrefix}/pages/${page.handle}${trackingParams}`
        };
      })
    });
  }
  if (predictiveSearch.articles.length) {
    results.push({
      type: "articles",
      items: predictiveSearch.articles.map(
        (article) => {
          totalResults++;
          const trackingParams = applyTrackingParams(article);
          return {
            __typename: article.__typename,
            handle: article.handle,
            id: article.id,
            image: article.image,
            title: article.title,
            url: `${localePrefix}/blog/${article.handle}${trackingParams}`
          };
        }
      )
    });
  }
  return { results, totalResults };
}
const PREDICTIVE_SEARCH_QUERY = `#graphql
  fragment PredictiveArticle on Article {
    __typename
    id
    title
    handle
    image {
      url
      altText
      width
      height
    }
    trackingParameters
  }
  fragment PredictiveCollection on Collection {
    __typename
    id
    title
    handle
    image {
      url
      altText
      width
      height
    }
    trackingParameters
  }
  fragment PredictivePage on Page {
    __typename
    id
    title
    handle
    trackingParameters
  }
  fragment PredictiveProduct on Product {
    __typename
    id
    title
    handle
    trackingParameters
    variants(first: 1) {
      nodes {
        id
        image {
          url
          altText
          width
          height
        }
        price {
          amount
          currencyCode
        }
      }
    }
  }
  fragment PredictiveQuery on SearchQuerySuggestion {
    __typename
    text
    styledText
    trackingParameters
  }
  query predictiveSearch(
    $country: CountryCode
    $language: LanguageCode
    $limit: Int!
    $limitScope: PredictiveSearchLimitScope!
    $searchTerm: String!
    $types: [PredictiveSearchType!]
  ) @inContext(country: $country, language: $language) {
    predictiveSearch(
      limit: $limit,
      limitScope: $limitScope,
      query: $searchTerm,
      types: $types,
    ) {
      articles {
        ...PredictiveArticle
      }
      collections {
        ...PredictiveCollection
      }
      pages {
        ...PredictivePage
      }
      products {
        ...PredictiveProduct
      }
      queries {
        ...PredictiveQuery
      }
    }
  }
`;
const route7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$o,
  normalizePredictiveSearchResults
}, Symbol.toStringTag, { value: "Module" }));
const meta$a = ({ data }) => {
  return [{ title: `Durafoam | ${(data == null ? void 0 : data.collection.title) ?? ""}` }];
};
async function loader$n({ request, params, context: context2 }) {
  const { handle } = params;
  const { storefront } = context2;
  const paginationVariables = fn(request, {
    pageBy: 24
  });
  if (!handle) {
    return redirect2("/collections");
  }
  const { collection } = await storefront.query(COLLECTION_QUERY, {
    variables: { handle, ...paginationVariables }
  });
  if (!collection) {
    throw new Response(`Collection ${handle} not found`, {
      status: 404
    });
  }
  return json2({ collection });
}
function Collection() {
  const { collection } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "collection pb-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: "relative py-12 overflow-hidden rounded-[3rem] bg-slate-50 mb-12 px-6 lg:px-20 border border-slate-100", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-gradient-to-br from-primary-400/5 via-transparent to-blue-400/5" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 max-w-4xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: "mb-4 flex space-x-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: "/", className: "hover:text-primary-600 transition-colors", children: "Home" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-300", children: "/" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Link,
            {
              to: "/collections",
              className: "hover:text-primary-600 transition-colors",
              children: "Collections"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-300", children: "/" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600 tracking-normal", children: collection.title })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl sm:text-4xl font-extrabold tracking-tight text-slate-900 font-heading", children: collection.title }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-base text-slate-600 leading-relaxed max-w-2xl", children: collection.description || "Explore our high-quality range of bespoke foam products designed for comfort and durability." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute -right-20 -top-20 w-96 h-96 bg-primary-600/5 rounded-full blur-3xl" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ln, { connection: collection.products, children: ({ nodes, isLoading, PreviousLink, NextLink }) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-4 sm:px-6 lg:px-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center mb-12", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PreviousLink, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "group flex items-center gap-2 px-6 py-3 rounded-2xl bg-white border border-slate-200 text-sm font-bold text-slate-600 hover:border-primary-600 hover:text-primary-600 transition-all cursor-pointer", children: isLoading ? "Loading..." : "↑ Load Previous" }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ProductsGrid, { products: nodes }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center mt-20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(NextLink, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "group flex flex-col items-center gap-4 px-10 py-5 rounded-[2rem] bg-brand-dark text-white shadow-xl hover:bg-slate-800 transition-all hover:-translate-y-1 cursor-pointer", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-extrabold uppercase tracking-widest", children: isLoading ? "Loading..." : "Load More Products" }),
        !isLoading && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "svg",
          {
            className: "w-5 h-5 animate-bounce",
            fill: "none",
            viewBox: "0 0 24 24",
            stroke: "currentColor",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "path",
              {
                strokeLinecap: "round",
                strokeLinejoin: "round",
                strokeWidth: 3,
                d: "M19 14l-7 7m0 0l-7-7m7 7V3"
              }
            )
          }
        )
      ] }) }) })
    ] }) })
  ] });
}
function ProductsGrid({ products }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8", children: products.map((product, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    ProductItem,
    {
      product,
      loading: index < 8 ? "eager" : void 0
    },
    product.id
  )) });
}
function ProductItem({
  product,
  loading: loading2
}) {
  const variant = product.variants.nodes[0];
  const variantUrl = useVariantUrl(product.handle, variant.selectedOptions);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Link, { to: variantUrl, className: "group flex flex-col h-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative aspect-square overflow-hidden rounded-[2.5rem] bg-slate-50 border border-slate-100 transition-all duration-500 group-hover:shadow-premium group-hover:border-primary-100", children: [
      product.featuredImage ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        Image,
        {
          data: product.featuredImage,
          aspectRatio: "1/1",
          sizes: "(min-width: 45em) 25vw, 50vw",
          className: "w-full h-full object-cover transition-transform duration-700 group-hover:scale-110",
          loading: loading2
        }
      ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        "img",
        {
          src: placeholderImg,
          alt: product.title,
          className: "w-full h-full object-cover opacity-30"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-x-0 bottom-0 p-4 translate-y-4 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-500 bg-gradient-to-t from-white/95 via-white/50 to-transparent backdrop-blur-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full py-3 bg-brand-dark text-white text-[10px] font-black uppercase tracking-widest text-center rounded-2xl shadow-lg", children: "View Options" }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6 flex-1 px-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-start gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-bold text-slate-900 group-hover:text-primary-600 transition-colors leading-tight", children: product.title }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1 text-xs font-bold text-slate-400 flex items-center gap-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "w-1.5 h-1.5 rounded-full bg-green-500" }),
          "In Stock & Ready"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-right", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xl font-black text-blue-600", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.priceRange.minVariantPrice }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-[10px] font-bold text-slate-400 uppercase", children: "Start from" })
      ] })
    ] }) })
  ] });
}
const PRODUCT_ITEM_FRAGMENT = `#graphql
  fragment MoneyProductItem on MoneyV2 {
    amount
    currencyCode
  }
  fragment ProductItem on Product {
    id
    handle
    title
    featuredImage {
      id
      altText
      url
      width
      height
    }
    priceRange {
      minVariantPrice {
        ...MoneyProductItem
      }
      maxVariantPrice {
        ...MoneyProductItem
      }
    }
    variants(first: 1) {
      nodes {
        selectedOptions {
          name
          value
        }
      }
    }
  }
`;
const COLLECTION_QUERY = `#graphql
  ${PRODUCT_ITEM_FRAGMENT}
  query Collection(
    $handle: String!
    $country: CountryCode
    $language: LanguageCode
    $first: Int
    $last: Int
    $startCursor: String
    $endCursor: String
  ) @inContext(country: $country, language: $language) {
    collection(handle: $handle) {
      id
      handle
      title
      description
      products(
        first: $first,
        last: $last,
        before: $startCursor,
        after: $endCursor
      ) {
        nodes {
          ...ProductItem
        }
        pageInfo {
          hasPreviousPage
          hasNextPage
          endCursor
          startCursor
        }
      }
    }
  }
`;
const route8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Collection,
  loader: loader$n,
  meta: meta$a
}, Symbol.toStringTag, { value: "Module" }));
const CUSTOMER_ORDER_QUERY = `#graphql
  fragment OrderMoney on MoneyV2 {
    amount
    currencyCode
  }
  fragment DiscountApplication on DiscountApplication {
    value {
      __typename
      ... on MoneyV2 {
        ...OrderMoney
      }
      ... on PricingPercentageValue {
        percentage
      }
    }
  }
  fragment OrderLineItemFull on LineItem {
    id
    title
    quantity
    price {
      ...OrderMoney
    }
    discountAllocations {
      allocatedAmount {
        ...OrderMoney
      }
      discountApplication {
        ...DiscountApplication
      }
    }
    totalDiscount {
      ...OrderMoney
    }
    image {
      altText
      height
      url
      id
      width
    }
    variantTitle
  }
  fragment Order on Order {
    id
    name
    statusPageUrl
    processedAt
    fulfillments(first: 1) {
      nodes {
        status
      }
    }
    totalTax {
      ...OrderMoney
    }
    totalPrice {
      ...OrderMoney
    }
    subtotal {
      ...OrderMoney
    }
    shippingAddress {
      name
      formatted(withName: true)
      formattedArea
    }
    discountApplications(first: 100) {
      nodes {
        ...DiscountApplication
      }
    }
    lineItems(first: 100) {
      nodes {
        ...OrderLineItemFull
      }
    }
  }
  query Order($orderId: ID!) {
    order(id: $orderId) {
      ... on Order {
        ...Order
      }
    }
  }
`;
const meta$9 = ({ data }) => {
  var _a2;
  return [{ title: `Order ${(_a2 = data == null ? void 0 : data.order) == null ? void 0 : _a2.name}` }];
};
async function loader$m({ params, context: context2, request }) {
  var _a2;
  if (!params.id) {
    return redirect2("/account/orders");
  }
  const orderId = atob(params.id);
  const { data, errors } = await context2.customerAccount.query(
    CUSTOMER_ORDER_QUERY,
    {
      variables: { orderId }
    }
  );
  if ((errors == null ? void 0 : errors.length) || !(data == null ? void 0 : data.order)) {
    throw new Error("Order not found");
  }
  const { order } = data;
  const lineItems = flattenConnection(order.lineItems);
  const discountApplications = flattenConnection(order.discountApplications);
  const fulfillmentStatus = flattenConnection(order.fulfillments)[0].status;
  const firstDiscount = (_a2 = discountApplications[0]) == null ? void 0 : _a2.value;
  const discountValue = (firstDiscount == null ? void 0 : firstDiscount.__typename) === "MoneyV2" && firstDiscount;
  const discountPercentage = (firstDiscount == null ? void 0 : firstDiscount.__typename) === "PricingPercentageValue" && (firstDiscount == null ? void 0 : firstDiscount.percentage);
  return json2(
    {
      order,
      lineItems,
      discountValue,
      discountPercentage,
      fulfillmentStatus
    },
    {
      headers: {
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
function OrderRoute() {
  const {
    order,
    lineItems,
    discountValue,
    discountPercentage,
    fulfillmentStatus
  } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "account-order", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { children: [
      "Order ",
      order.name
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { children: [
      "Placed on ",
      new Date(order.processedAt).toDateString()
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Product" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Price" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Quantity" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Total" })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: lineItems.map((lineItem, lineItemIndex) => (
          // eslint-disable-next-line react/no-array-index-key
          /* @__PURE__ */ jsxRuntimeExports.jsx(OrderLineRow, { lineItem }, lineItemIndex)
        )) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("tfoot", { children: [
          (discountValue && discountValue.amount || discountPercentage) && /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", colSpan: 3, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Discounts" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Discounts" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: discountPercentage ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
              "-",
              discountPercentage,
              "% OFF"
            ] }) : discountValue && /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: discountValue }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", colSpan: 3, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Subtotal" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Subtotal" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: order.subtotal }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", colSpan: 3, children: "Tax" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Tax" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: order.totalTax }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", colSpan: 3, children: "Total" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "row", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Total" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: order.totalPrice }) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { children: "Shipping Address" }),
        (order == null ? void 0 : order.shippingAddress) ? /* @__PURE__ */ jsxRuntimeExports.jsxs("address", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: order.shippingAddress.name }),
          order.shippingAddress.formatted ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: order.shippingAddress.formatted }) : "",
          order.shippingAddress.formattedArea ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: order.shippingAddress.formattedArea }) : ""
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "No shipping address defined" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { children: "Status" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: fulfillmentStatus }) })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { target: "_blank", href: order.statusPageUrl, rel: "noreferrer", children: "View Order Status →" }) })
  ] });
}
function OrderLineRow({ lineItem }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      (lineItem == null ? void 0 : lineItem.image) && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Image, { data: lineItem.image, width: 96, height: 96 }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: lineItem.title }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("small", { children: lineItem.variantTitle })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: lineItem.price }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: lineItem.quantity }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: lineItem.totalDiscount }) })
  ] }, lineItem.id);
}
const route9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: OrderRoute,
  loader: loader$m,
  meta: meta$9
}, Symbol.toStringTag, { value: "Module" }));
async function loader$l({ context: context2 }) {
  return context2.customerAccount.authorize();
}
const route10 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$l
}, Symbol.toStringTag, { value: "Module" }));
async function loader$k({ context: context2, request }) {
  const paginationVariables = fn(request, {
    pageBy: 10
  });
  const { collections } = await context2.storefront.query(COLLECTIONS_QUERY, {
    variables: paginationVariables
  });
  return json2({ collections });
}
function Collections() {
  const { collections } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pb-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: "relative py-16 overflow-hidden rounded-[3rem] bg-slate-50 mb-12 px-6 lg:px-20 border border-slate-100", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-gradient-to-br from-primary-400/5 via-transparent to-blue-400/5" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 max-w-4xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: "mb-4 flex space-x-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: "/", className: "hover:text-primary-600 transition-colors", children: "Home" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-300", children: "/" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600 tracking-normal", children: "Collections" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl sm:text-4xl font-extrabold tracking-tight text-slate-900 font-heading", children: "Our Collections" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-base text-slate-600 leading-relaxed max-w-2xl", children: "Find exactly what you're looking for with our specialized foam categories, curated for your comfort and projects." })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ln, { connection: collections, children: ({ nodes, isLoading, PreviousLink, NextLink }) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-4 sm:px-6 lg:px-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center mb-12", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PreviousLink, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "group flex items-center gap-2 px-6 py-3 rounded-2xl bg-white border border-slate-200 text-sm font-bold text-slate-600 hover:border-primary-600 hover:text-primary-600 transition-all cursor-pointer", children: isLoading ? "Loading..." : "↑ Load Previous" }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CollectionsGrid, { collections: nodes }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center mt-20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(NextLink, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "group flex flex-col items-center gap-4 px-10 py-5 rounded-[2rem] bg-brand-dark text-white shadow-xl hover:bg-slate-800 transition-all hover:-translate-y-1 cursor-pointer", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-extrabold uppercase tracking-widest", children: isLoading ? "Loading..." : "Load More Collections" }),
        !isLoading && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "svg",
          {
            className: "w-5 h-5 animate-bounce",
            fill: "none",
            viewBox: "0 0 24 24",
            stroke: "currentColor",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "path",
              {
                strokeLinecap: "round",
                strokeLinejoin: "round",
                strokeWidth: 3,
                d: "M19 14l-7 7m0 0l-7-7m7 7V3"
              }
            )
          }
        )
      ] }) }) })
    ] }) })
  ] });
}
function CollectionsGrid({ collections }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8", children: collections.map((collection, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    CollectionItem,
    {
      collection,
      index
    },
    collection.id
  )) });
}
function CollectionItem({
  collection,
  index
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    Link,
    {
      to: `/collections/${collection.handle}`,
      prefetch: "intent",
      className: "group relative overflow-hidden rounded-[2.5rem] shadow-sm transition-all duration-500 hover:shadow-premium hover:-translate-y-1 block h-80 sm:h-96",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-slate-100", children: (collection == null ? void 0 : collection.image) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          Image,
          {
            alt: collection.image.altText || collection.title,
            aspectRatio: "4/3",
            data: collection.image,
            loading: index < 3 ? "eager" : void 0,
            sizes: "(min-width: 1024px) 33vw, (min-width: 768px) 50vw, 100vw",
            className: "w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
          }
        ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          "img",
          {
            src: placeholderImg,
            alt: collection.title,
            className: "w-full h-full object-cover opacity-50 bg-slate-50"
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute inset-0 bg-gradient-to-t from-brand-dark/90 via-brand-dark/20 to-transparent p-8 flex flex-col justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-white mb-2 leading-tight group-hover:text-primary-400 transition-colors", children: collection.title }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white/70 text-sm font-bold uppercase tracking-widest opacity-0 group-hover:opacity-100 transition-all duration-500 translate-y-4 group-hover:translate-y-0", children: "Explore Collection →" })
        ] })
      ]
    }
  );
}
const COLLECTIONS_QUERY = `#graphql
  fragment Collection on Collection {
    id
    title
    handle
    image {
      id
      url
      altText
      width
      height
    }
  }
  query StoreCollections(
    $country: CountryCode
    $endCursor: String
    $first: Int
    $language: LanguageCode
    $last: Int
    $startCursor: String
  ) @inContext(country: $country, language: $language) {
    collections(
      first: $first,
      last: $last,
      before: $startCursor,
      after: $endCursor
    ) {
      nodes {
        ...Collection
      }
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
    }
  }
`;
const route11 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Collections,
  loader: loader$k
}, Symbol.toStringTag, { value: "Module" }));
const UPDATE_ADDRESS_MUTATION = `#graphql
  mutation customerAddressUpdate(
    $address: CustomerAddressInput!
    $addressId: ID!
    $defaultAddress: Boolean
 ) {
    customerAddressUpdate(
      address: $address
      addressId: $addressId
      defaultAddress: $defaultAddress
    ) {
      customerAddress {
        id
      }
      userErrors {
        code
        field
        message
      }
    }
  }
`;
const DELETE_ADDRESS_MUTATION = `#graphql
  mutation customerAddressDelete(
    $addressId: ID!,
  ) {
    customerAddressDelete(addressId: $addressId) {
      deletedAddressId
      userErrors {
        code
        field
        message
      }
    }
  }
`;
const CREATE_ADDRESS_MUTATION = `#graphql
  mutation customerAddressCreate(
    $address: CustomerAddressInput!
    $defaultAddress: Boolean
  ) {
    customerAddressCreate(
      address: $address
      defaultAddress: $defaultAddress
    ) {
      customerAddress {
        id
      }
      userErrors {
        code
        field
        message
      }
    }
  }
`;
const meta$8 = () => {
  return [{ title: "Addresses" }];
};
async function loader$j({ context: context2 }) {
  await context2.customerAccount.handleAuthStatus();
  return json2(
    {},
    {
      headers: {
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
async function action$4({ request, context: context2 }) {
  var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m;
  const { customerAccount } = context2;
  try {
    const form = await request.formData();
    const addressId = form.has("addressId") ? String(form.get("addressId")) : null;
    if (!addressId) {
      throw new Error("You must provide an address id.");
    }
    const isLoggedIn = await customerAccount.isLoggedIn();
    if (!isLoggedIn) {
      return json2(
        { error: { [addressId]: "Unauthorized" } },
        {
          status: 401,
          headers: {
            "Set-Cookie": await context2.session.commit()
          }
        }
      );
    }
    const defaultAddress = form.has("defaultAddress") ? String(form.get("defaultAddress")) === "on" : false;
    const address = {};
    const keys = [
      "address1",
      "address2",
      "city",
      "company",
      "territoryCode",
      "firstName",
      "lastName",
      "phoneNumber",
      "zoneCode",
      "zip"
    ];
    for (const key of keys) {
      const value = form.get(key);
      if (typeof value === "string") {
        address[key] = value;
      }
    }
    switch (request.method) {
      case "POST": {
        try {
          const { data, errors } = await customerAccount.mutate(
            CREATE_ADDRESS_MUTATION,
            {
              variables: { address, defaultAddress }
            }
          );
          if (errors == null ? void 0 : errors.length) {
            throw new Error(errors[0].message);
          }
          if ((_b2 = (_a2 = data == null ? void 0 : data.customerAddressCreate) == null ? void 0 : _a2.userErrors) == null ? void 0 : _b2.length) {
            throw new Error((_c = data == null ? void 0 : data.customerAddressCreate) == null ? void 0 : _c.userErrors[0].message);
          }
          if (!((_d = data == null ? void 0 : data.customerAddressCreate) == null ? void 0 : _d.customerAddress)) {
            throw new Error("Customer address create failed.");
          }
          return json2(
            {
              error: null,
              createdAddress: (_e2 = data == null ? void 0 : data.customerAddressCreate) == null ? void 0 : _e2.customerAddress,
              defaultAddress
            },
            {
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        } catch (error2) {
          if (error2 instanceof Error) {
            return json2(
              { error: { [addressId]: error2.message } },
              {
                status: 400,
                headers: {
                  "Set-Cookie": await context2.session.commit()
                }
              }
            );
          }
          return json2(
            { error: { [addressId]: error2 } },
            {
              status: 400,
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        }
      }
      case "PUT": {
        try {
          const { data, errors } = await customerAccount.mutate(
            UPDATE_ADDRESS_MUTATION,
            {
              variables: {
                address,
                addressId: decodeURIComponent(addressId),
                defaultAddress
              }
            }
          );
          if (errors == null ? void 0 : errors.length) {
            throw new Error(errors[0].message);
          }
          if ((_g = (_f = data == null ? void 0 : data.customerAddressUpdate) == null ? void 0 : _f.userErrors) == null ? void 0 : _g.length) {
            throw new Error((_h = data == null ? void 0 : data.customerAddressUpdate) == null ? void 0 : _h.userErrors[0].message);
          }
          if (!((_i = data == null ? void 0 : data.customerAddressUpdate) == null ? void 0 : _i.customerAddress)) {
            throw new Error("Customer address update failed.");
          }
          return json2(
            {
              error: null,
              updatedAddress: address,
              defaultAddress
            },
            {
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        } catch (error2) {
          if (error2 instanceof Error) {
            return json2(
              { error: { [addressId]: error2.message } },
              {
                status: 400,
                headers: {
                  "Set-Cookie": await context2.session.commit()
                }
              }
            );
          }
          return json2(
            { error: { [addressId]: error2 } },
            {
              status: 400,
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        }
      }
      case "DELETE": {
        try {
          const { data, errors } = await customerAccount.mutate(
            DELETE_ADDRESS_MUTATION,
            {
              variables: { addressId: decodeURIComponent(addressId) }
            }
          );
          if (errors == null ? void 0 : errors.length) {
            throw new Error(errors[0].message);
          }
          if ((_k = (_j = data == null ? void 0 : data.customerAddressDelete) == null ? void 0 : _j.userErrors) == null ? void 0 : _k.length) {
            throw new Error((_l = data == null ? void 0 : data.customerAddressDelete) == null ? void 0 : _l.userErrors[0].message);
          }
          if (!((_m = data == null ? void 0 : data.customerAddressDelete) == null ? void 0 : _m.deletedAddressId)) {
            throw new Error("Customer address delete failed.");
          }
          return json2(
            { error: null, deletedAddress: addressId },
            {
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        } catch (error2) {
          if (error2 instanceof Error) {
            return json2(
              { error: { [addressId]: error2.message } },
              {
                status: 400,
                headers: {
                  "Set-Cookie": await context2.session.commit()
                }
              }
            );
          }
          return json2(
            { error: { [addressId]: error2 } },
            {
              status: 400,
              headers: {
                "Set-Cookie": await context2.session.commit()
              }
            }
          );
        }
      }
      default: {
        return json2(
          { error: { [addressId]: "Method not allowed" } },
          {
            status: 405,
            headers: {
              "Set-Cookie": await context2.session.commit()
            }
          }
        );
      }
    }
  } catch (error2) {
    if (error2 instanceof Error) {
      return json2(
        { error: error2.message },
        {
          status: 400,
          headers: {
            "Set-Cookie": await context2.session.commit()
          }
        }
      );
    }
    return json2(
      { error: error2 },
      {
        status: 400,
        headers: {
          "Set-Cookie": await context2.session.commit()
        }
      }
    );
  }
}
function Addresses() {
  const { customer } = useOutletContext();
  const { defaultAddress, addresses } = customer;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "account-addresses", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: "Addresses" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    !addresses.nodes.length ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "You have no addresses saved." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("legend", { children: "Create address" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(NewAddressForm, {})
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx("hr", {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ExistingAddresses,
        {
          addresses,
          defaultAddress
        }
      )
    ] })
  ] });
}
function NewAddressForm() {
  const newAddress = {
    address1: "",
    address2: "",
    city: "",
    company: "",
    territoryCode: "",
    firstName: "",
    id: "new",
    lastName: "",
    phoneNumber: "",
    zoneCode: "",
    zip: ""
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    AddressForm,
    {
      addressId: "NEW_ADDRESS_ID",
      address: newAddress,
      defaultAddress: null,
      children: ({ stateForMethod }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          disabled: stateForMethod("POST") !== "idle",
          formMethod: "POST",
          type: "submit",
          children: stateForMethod("POST") !== "idle" ? "Creating" : "Create"
        }
      ) })
    }
  );
}
function ExistingAddresses({
  addresses,
  defaultAddress
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("legend", { children: "Existing addresses" }),
    addresses.nodes.map((address) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      AddressForm,
      {
        addressId: address.id,
        address,
        defaultAddress,
        children: ({ stateForMethod }) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              disabled: stateForMethod("PUT") !== "idle",
              formMethod: "PUT",
              type: "submit",
              children: stateForMethod("PUT") !== "idle" ? "Saving" : "Save"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              disabled: stateForMethod("DELETE") !== "idle",
              formMethod: "DELETE",
              type: "submit",
              children: stateForMethod("DELETE") !== "idle" ? "Deleting" : "Delete"
            }
          )
        ] })
      },
      address.id
    ))
  ] });
}
function AddressForm({
  addressId,
  address,
  defaultAddress,
  children
}) {
  var _a2;
  const { state, formMethod } = useNavigation();
  const action2 = useActionData();
  const error2 = (_a2 = action2 == null ? void 0 : action2.error) == null ? void 0 : _a2[addressId];
  const isDefaultAddress = (defaultAddress == null ? void 0 : defaultAddress.id) === addressId;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Form, { id: addressId, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("fieldset", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("input", { type: "hidden", name: "addressId", defaultValue: addressId }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "firstName", children: "First name*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "First name",
        autoComplete: "given-name",
        defaultValue: (address == null ? void 0 : address.firstName) ?? "",
        id: "firstName",
        name: "firstName",
        placeholder: "First name",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "lastName", children: "Last name*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Last name",
        autoComplete: "family-name",
        defaultValue: (address == null ? void 0 : address.lastName) ?? "",
        id: "lastName",
        name: "lastName",
        placeholder: "Last name",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "company", children: "Company" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Company",
        autoComplete: "organization",
        defaultValue: (address == null ? void 0 : address.company) ?? "",
        id: "company",
        name: "company",
        placeholder: "Company",
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "address1", children: "Address line*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Address line 1",
        autoComplete: "address-line1",
        defaultValue: (address == null ? void 0 : address.address1) ?? "",
        id: "address1",
        name: "address1",
        placeholder: "Address line 1*",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "address2", children: "Address line 2" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Address line 2",
        autoComplete: "address-line2",
        defaultValue: (address == null ? void 0 : address.address2) ?? "",
        id: "address2",
        name: "address2",
        placeholder: "Address line 2",
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "city", children: "City*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "City",
        autoComplete: "address-level2",
        defaultValue: (address == null ? void 0 : address.city) ?? "",
        id: "city",
        name: "city",
        placeholder: "City",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "zoneCode", children: "State / Province*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "State/Province",
        autoComplete: "address-level1",
        defaultValue: (address == null ? void 0 : address.zoneCode) ?? "",
        id: "zoneCode",
        name: "zoneCode",
        placeholder: "State / Province",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "zip", children: "Zip / Postal Code*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Zip",
        autoComplete: "postal-code",
        defaultValue: (address == null ? void 0 : address.zip) ?? "",
        id: "zip",
        name: "zip",
        placeholder: "Zip / Postal Code",
        required: true,
        type: "text"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "territoryCode", children: "Country Code*" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "territoryCode",
        autoComplete: "country",
        defaultValue: (address == null ? void 0 : address.territoryCode) ?? "",
        id: "territoryCode",
        name: "territoryCode",
        placeholder: "Country",
        required: true,
        type: "text",
        maxLength: 2
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "phoneNumber", children: "Phone" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        "aria-label": "Phone Number",
        autoComplete: "tel",
        defaultValue: (address == null ? void 0 : address.phoneNumber) ?? "",
        id: "phoneNumber",
        name: "phoneNumber",
        placeholder: "+16135551111",
        pattern: "^\\+?[1-9]\\d{3,14}$",
        type: "tel"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          defaultChecked: isDefaultAddress,
          id: "defaultAddress",
          name: "defaultAddress",
          type: "checkbox"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "defaultAddress", children: "Set as default address" })
    ] }),
    error2 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("mark", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("small", { children: error2 }) }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    children({
      stateForMethod: (method) => formMethod === method ? state : "idle"
    })
  ] }) });
}
const route12 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AddressForm,
  action: action$4,
  default: Addresses,
  loader: loader$j,
  meta: meta$8
}, Symbol.toStringTag, { value: "Module" }));
const meta$7 = ({ data }) => {
  return [{ title: `Hydrogen | ${(data == null ? void 0 : data.policy.title) ?? ""}` }];
};
async function loader$i({ params, context: context2 }) {
  var _a2, _b2;
  if (!params.handle) {
    throw new Response("No handle was passed in", { status: 404 });
  }
  const policyName = params.handle.replace(
    /-([a-z])/g,
    (_2, m1) => m1.toUpperCase()
  );
  const data = await context2.storefront.query(POLICY_CONTENT_QUERY, {
    variables: {
      privacyPolicy: false,
      shippingPolicy: false,
      termsOfService: false,
      refundPolicy: false,
      [policyName]: true,
      language: (_a2 = context2.storefront.i18n) == null ? void 0 : _a2.language
    }
  });
  const policy = (_b2 = data.shop) == null ? void 0 : _b2[policyName];
  if (!policy) {
    throw new Response("Could not find the policy", { status: 404 });
  }
  return json2({ policy });
}
function Policy() {
  const { policy } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "policy", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: "/policies", children: "← Back to Policies" }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: policy.title }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { dangerouslySetInnerHTML: { __html: policy.body } })
  ] });
}
const POLICY_CONTENT_QUERY = `#graphql
  fragment Policy on ShopPolicy {
    body
    handle
    id
    title
    url
  }
  query Policy(
    $country: CountryCode
    $language: LanguageCode
    $privacyPolicy: Boolean!
    $refundPolicy: Boolean!
    $shippingPolicy: Boolean!
    $termsOfService: Boolean!
  ) @inContext(language: $language, country: $country) {
    shop {
      privacyPolicy @include(if: $privacyPolicy) {
        ...Policy
      }
      shippingPolicy @include(if: $shippingPolicy) {
        ...Policy
      }
      termsOfService @include(if: $termsOfService) {
        ...Policy
      }
      refundPolicy @include(if: $refundPolicy) {
        ...Policy
      }
    }
  }
`;
const route13 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Policy,
  loader: loader$i,
  meta: meta$7
}, Symbol.toStringTag, { value: "Module" }));
function Toast({ show, message, onClose }) {
  reactExports.useEffect(() => {
    if (show) {
      const timer = setTimeout(() => {
        onClose();
      }, 3e3);
      return () => clearTimeout(timer);
    }
  }, [show, onClose]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      "aria-live": "assertive",
      className: "pointer-events-none fixed inset-0 z-50 flex items-end px-4 py-6 sm:items-start sm:p-6",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex w-full flex-col items-center space-y-4 sm:items-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Ke$3,
        {
          show,
          as: reactExports.Fragment,
          enter: "transform ease-out duration-300 transition",
          enterFrom: "translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2",
          enterTo: "translate-y-0 opacity-100 sm:translate-x-0",
          leave: "transition ease-in duration-100",
          leaveFrom: "opacity-100",
          leaveTo: "opacity-0",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pointer-events-auto w-full max-w-sm overflow-hidden rounded-2xl bg-white shadow-premium-lg ring-1 ring-black ring-opacity-5 border border-slate-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ForwardRef$l,
              {
                className: "h-6 w-6 text-green-500",
                "aria-hidden": "true"
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ml-3 w-0 flex-1 pt-0.5", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-bold text-slate-900", children: "Success!" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-slate-500", children: message })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-4 flex flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                className: "inline-flex rounded-md bg-white text-slate-400 hover:text-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",
                onClick: onClose,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "sr-only", children: "Close" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$8, { className: "h-5 w-5", "aria-hidden": "true" })
                ]
              }
            ) })
          ] }) }) })
        }
      ) })
    }
  );
}
function Magnifier({
  data,
  sizes = "(min-width: 45em) 50vw, 100vw",
  className = "",
  zoomScale = 2.5
}) {
  var _a2, _b2;
  const [position, setPosition] = reactExports.useState({ x: 0, y: 0 });
  const [showMagnifier, setShowMagnifier] = reactExports.useState(false);
  const [cursorPosition, setCursorPosition] = reactExports.useState({ x: 0, y: 0 });
  const containerRef = reactExports.useRef(null);
  const handleMouseMove = (e2) => {
    if (!containerRef.current) return;
    const { left, top, width, height } = containerRef.current.getBoundingClientRect();
    const x = (e2.pageX - left - window.scrollX) / width * 100;
    const y2 = (e2.pageY - top - window.scrollY) / height * 100;
    setCursorPosition({
      x: e2.pageX - left - window.scrollX,
      y: e2.pageY - top - window.scrollY
    });
    setPosition({ x, y: y2 });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      ref: containerRef,
      className: `relative overflow-hidden cursor-zoom-in ${className}`,
      onMouseEnter: () => setShowMagnifier(true),
      onMouseLeave: () => setShowMagnifier(false),
      onMouseMove: handleMouseMove,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Image,
          {
            data,
            sizes,
            className: "h-full w-full object-cover object-center"
          }
        ),
        showMagnifier && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "absolute pointer-events-none border-2 border-white shadow-[0_0_30px_rgba(0,0,0,0.4)] rounded-full bg-no-repeat z-[60] overflow-hidden hidden sm:block animate-magnifier-in",
            style: {
              width: "300px",
              height: "300px",
              left: `${cursorPosition.x - 150}px`,
              top: `${cursorPosition.y - 150}px`,
              backgroundImage: `url(${data.url})`,
              backgroundSize: `${((_a2 = containerRef.current) == null ? void 0 : _a2.offsetWidth) * zoomScale}px ${((_b2 = containerRef.current) == null ? void 0 : _b2.offsetHeight) * zoomScale}px`,
              backgroundPosition: `${position.x}% ${position.y}%`
            }
          }
        )
      ]
    }
  );
}
function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}
const meta$6 = ({ data }) => {
  return [{ title: `Hydrogen | ${(data == null ? void 0 : data.product.title) ?? ""}` }];
};
async function loader$h({ params, request, context: context2 }) {
  const { handle } = params;
  const { storefront } = context2;
  const selectedOptions = Zn(request).filter(
    (option) => (
      // Filter out Shopify predictive search query params
      !option.name.startsWith("_sid") && !option.name.startsWith("_pos") && !option.name.startsWith("_psq") && !option.name.startsWith("_ss") && !option.name.startsWith("_v") && // Filter out third party tracking params
      !option.name.startsWith("fbclid")
    )
  );
  if (!handle) {
    throw new Error("Expected product handle to be defined");
  }
  const { product } = await storefront.query(PRODUCT_QUERY, {
    variables: { handle, selectedOptions }
  });
  if (!(product == null ? void 0 : product.id)) {
    throw new Response(null, { status: 404 });
  }
  const firstVariant = product.variants.nodes[0];
  const firstVariantIsDefault = Boolean(
    firstVariant.selectedOptions.find(
      (option) => option.name === "Title" && option.value === "Default Title"
    )
  );
  if (firstVariantIsDefault) {
    product.selectedVariant = firstVariant;
  } else {
    if (!product.selectedVariant) {
      throw redirectToFirstVariant({ product, request });
    }
  }
  const variants = storefront.query(VARIANTS_QUERY, {
    variables: { handle }
  });
  return defer2({ product, variants });
}
function redirectToFirstVariant({
  product,
  request
}) {
  const url = new URL(request.url);
  const firstVariant = product.variants.nodes[0];
  return redirect2(
    getVariantUrl({
      pathname: url.pathname,
      handle: product.handle,
      selectedOptions: firstVariant.selectedOptions,
      searchParams: new URLSearchParams(url.search)
    }),
    {
      status: 302
    }
  );
}
function Product() {
  const { product, variants } = useLoaderData();
  const { selectedVariant } = product;
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-10 pb-24", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:grid lg:grid-cols-12 lg:items-start lg:gap-x-12", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-7 sticky top-28", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      ProductImage,
      {
        image: selectedVariant == null ? void 0 : selectedVariant.image,
        images: product.images
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-10 px-0 sm:mt-16 lg:mt-0 lg:col-span-5", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      ProductMain,
      {
        selectedVariant,
        product,
        variants
      }
    ) })
  ] }) });
}
function ProductImage({
  image,
  images
}) {
  if (!image || !images || images.nodes.length === 0) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-square w-full overflow-hidden rounded-3xl bg-slate-50 flex items-center justify-center border border-slate-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        src: placeholderImg,
        alt: "Product Placeholder",
        className: "h-full w-full object-cover object-center opacity-30 grayscale"
      }
    ) });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Be, { className: "flex flex-col-reverse lg:flex-row gap-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-24", children: /* @__PURE__ */ jsxRuntimeExports.jsx(We, { className: "flex lg:flex-col gap-4 overflow-x-auto lg:overflow-visible pb-2 lg:pb-0 scrollbar-hide", children: images.nodes.map((img) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      dt,
      {
        className: "group relative flex h-24 w-24 shrink-0 cursor-pointer items-center justify-center rounded-xl bg-white focus:outline-none ring-2 ring-transparent group-data-[selected]:ring-blue-600 transition-all duration-300 border border-slate-100",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute inset-0 overflow-hidden rounded-xl border border-slate-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Image,
            {
              alt: img.altText || "Product Image",
              aspectRatio: "1/1",
              data: img,
              sizes: "100px",
              className: "h-full w-full object-cover object-center transition-transform duration-500 group-hover:scale-110"
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              "aria-hidden": "true",
              className: "pointer-events-none absolute inset-0 rounded-xl ring-2 ring-transparent ring-offset-2 group-data-[selected]:ring-blue-600"
            }
          )
        ]
      },
      img.id
    )) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(je, { className: "flex-1 aspect-square w-full overflow-hidden rounded-[2rem] shadow-premium-lg border border-slate-100 bg-white", children: images.nodes.map((img) => /* @__PURE__ */ jsxRuntimeExports.jsx(Ke, { className: "h-full w-full outline-none", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Magnifier, { data: img, className: "h-full w-full" }) }, img.id)) })
  ] });
}
function ProductMain({
  selectedVariant,
  product,
  variants
}) {
  const { title, descriptionHtml, vendor } = product;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col h-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-3 py-1 rounded-full bg-blue-50 text-blue-600 text-[10px] font-bold uppercase tracking-widest border border-blue-100", children: "In Stock" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-400 text-xs font-medium uppercase tracking-wider italic", children: vendor })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl sm:text-5xl font-extrabold tracking-tight text-slate-900 mb-6 leading-[1.1] font-outfit", children: title }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-end gap-3 mb-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ProductPrice, { selectedVariant }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-400 text-sm mb-1 font-medium", children: "Incl. VAT" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full h-px bg-slate-100 mb-8" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      reactExports.Suspense,
      {
        fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-48 animate-pulse bg-slate-50 rounded-2xl" }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: variants, children: (data) => {
          var _a2;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ProductForm,
            {
              product,
              selectedVariant,
              variants: ((_a2 = data.product) == null ? void 0 : _a2.variants.nodes) || []
            }
          );
        } })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-3 gap-4 mt-12 mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center text-center p-4 rounded-2xl bg-slate-50 border border-slate-100 group hover:border-blue-200 transition-colors", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$a, { className: "h-6 w-6 text-blue-600 mb-2 group-hover:scale-110 transition-transform" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-800 uppercase", children: "Fast Delivery" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center text-center p-4 rounded-2xl bg-slate-50 border border-slate-100 group hover:border-blue-200 transition-colors", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$c, { className: "h-6 w-6 text-blue-600 mb-2 group-hover:scale-110 transition-transform" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-800 uppercase", children: "10Y Warranty" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center text-center p-4 rounded-2xl bg-slate-50 border border-slate-100 group hover:border-blue-200 transition-colors", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$n, { className: "h-6 w-6 text-blue-600 mb-2 group-hover:scale-110 transition-transform" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-slate-800 uppercase", children: "Easy Returns" })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-10 overflow-hidden rounded-3xl border border-slate-100 shadow-sm transition-all duration-300 hover:shadow-md", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Xe, { defaultOpen: true, children: ({ open }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(xe, { className: "flex w-full items-center justify-between px-6 py-5 text-left bg-white transition-colors hover:bg-slate-50", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-bold uppercase tracking-wider text-slate-900", children: "Product Details" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ForwardRef$d,
          {
            className: `${open ? "rotate-45 transform" : ""} h-5 w-5 text-slate-500 transition-transform duration-300`
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Le$1, { className: "px-8 pb-8 pt-2 bg-white prose prose-slate prose-sm max-w-none", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          dangerouslySetInnerHTML: { __html: descriptionHtml },
          className: "description-content space-y-4 text-slate-600 leading-relaxed"
        }
      ) })
    ] }) }) })
  ] });
}
function ProductPrice({
  selectedVariant
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-4xl font-bold tracking-tight text-blue-600 font-outfit", children: (selectedVariant == null ? void 0 : selectedVariant.price) && /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: selectedVariant == null ? void 0 : selectedVariant.price }) }),
    (selectedVariant == null ? void 0 : selectedVariant.compareAtPrice) && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl text-slate-400 line-through font-medium", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: selectedVariant.compareAtPrice }) })
  ] });
}
function ProductForm({
  product,
  selectedVariant,
  variants
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-10", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Xn,
      {
        handle: product.handle,
        options: product.options,
        variants,
        children: ({ option }) => /* @__PURE__ */ jsxRuntimeExports.jsx(ProductOptions, { option }, option.name)
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col sm:flex-row gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        AddToCartButton,
        {
          disabled: !selectedVariant || !selectedVariant.availableForSale,
          lines: selectedVariant ? [
            {
              merchandiseId: selectedVariant.id,
              quantity: 1
            }
          ] : [],
          children: (selectedVariant == null ? void 0 : selectedVariant.availableForSale) ? "Add to Cart" : "Sold Out"
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "flex items-center justify-center p-4 rounded-xl border border-slate-100 hover:bg-slate-50 transition-all text-slate-400 hover:text-red-500 group", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$h, { className: "h-6 w-6 group-active:fill-red-500" }) })
    ] })
  ] });
}
function ProductOptions({ option }) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xs font-bold uppercase tracking-widest text-slate-500", children: option.name }),
      option.name === "Size" && /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "text-[10px] font-bold uppercase text-blue-600 hover:underline", children: "Size Guide" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-3", children: option.values.map(({ value, isAvailable, isActive, to }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Link,
      {
        prefetch: "intent",
        preventScrollReset: true,
        replace: true,
        to,
        "aria-disabled": !isAvailable,
        className: classNames(
          "relative min-w-[3rem] px-5 py-3 text-sm font-bold uppercase tracking-wide transition-all duration-300 rounded-xl border-2",
          isActive ? "border-blue-600 bg-blue-50 text-blue-700 shadow-md transform scale-105" : isAvailable ? "border-slate-100 bg-white text-slate-700 hover:border-blue-200 hover:bg-slate-50" : "border-slate-50 bg-slate-50 text-slate-300 cursor-not-allowed overflow-hidden grayscale"
        ),
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "relative z-10", children: value }),
          !isAvailable && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 flex items-center justify-center opacity-10", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-[150%] h-px bg-slate-400 -rotate-45" }) })
        ]
      },
      option.name + value
    )) })
  ] });
}
function AddToCartButton({
  analytics,
  children,
  disabled,
  lines,
  onClick
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(J$1, { route: "/cart", inputs: { lines }, action: J$1.ACTIONS.LinesAdd, children: (fetcher) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    AddToCartButtonInner,
    {
      fetcher,
      disabled,
      onClick,
      analytics,
      children
    }
  ) });
}
function AddToCartButtonInner({
  fetcher,
  children,
  disabled,
  onClick,
  analytics
}) {
  const [showToast, setShowToast] = reactExports.useState(false);
  const isLoading = fetcher.state !== "idle";
  reactExports.useEffect(() => {
    if (fetcher.state === "idle" && fetcher.data && !fetcher.data.errors && fetcher.data.cart) {
      setShowToast(true);
    }
  }, [fetcher.state, fetcher.data]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("input", { name: "analytics", type: "hidden", value: JSON.stringify(analytics) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "submit",
        onClick,
        className: classNames(
          "relative flex w-full items-center justify-center rounded-xl bg-blue-600 px-8 py-4 text-base font-bold text-white shadow-premium transition-all duration-300 hover:bg-blue-700 hover:shadow-premium-lg active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed overflow-hidden",
          isLoading ? "cursor-wait" : ""
        ),
        disabled: disabled || isLoading,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: classNames(
                "flex items-center gap-3 transition-all duration-300",
                isLoading ? "opacity-0 scale-90" : "opacity-100 scale-100"
              ),
              children
            }
          ),
          isLoading && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "svg",
            {
              className: "animate-spin h-6 w-6 text-white",
              xmlns: "http://www.w3.org/2000/svg",
              fill: "none",
              viewBox: "0 0 24 24",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "circle",
                  {
                    className: "opacity-25",
                    cx: "12",
                    cy: "12",
                    r: "10",
                    stroke: "currentColor",
                    strokeWidth: "4"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "path",
                  {
                    className: "opacity-75",
                    fill: "currentColor",
                    d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  }
                )
              ]
            }
          ) })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Toast,
      {
        show: showToast,
        message: "Great choice! The item has been added to your cart.",
        onClose: () => setShowToast(false)
      }
    )
  ] });
}
const PRODUCT_VARIANT_FRAGMENT = `#graphql
  fragment ProductVariant on ProductVariant {
    availableForSale
    compareAtPrice {
      amount
      currencyCode
    }
    id
    image {
      __typename
      id
      url
      altText
      width
      height
    }
    price {
      amount
      currencyCode
    }
    product {
      title
      handle
    }
    selectedOptions {
      name
      value
    }
    sku
    title
    unitPrice {
      amount
      currencyCode
    }
  }
`;
const PRODUCT_FRAGMENT = `#graphql
  fragment Product on Product {
    id
    title
    vendor
    handle
    descriptionHtml
    description
    images(first: 5) {
      nodes {
        __typename
        id
        url
        altText
        width
        height
      }
    }
    options {
      name
      values
    }
    selectedVariant: variantBySelectedOptions(selectedOptions: $selectedOptions, ignoreUnknownOptions: true, caseInsensitiveMatch: true) {
      ...ProductVariant
    }
    variants(first: 1) {
      nodes {
        ...ProductVariant
      }
    }
    seo {
      description
      title
    }
  }
  ${PRODUCT_VARIANT_FRAGMENT}
`;
const PRODUCT_QUERY = `#graphql
  query Product(
    $country: CountryCode
    $handle: String!
    $language: LanguageCode
    $selectedOptions: [SelectedOptionInput!]!
  ) @inContext(country: $country, language: $language) {
    product(handle: $handle) {
      ...Product
    }
  }
  ${PRODUCT_FRAGMENT}
`;
const PRODUCT_VARIANTS_FRAGMENT = `#graphql
  fragment ProductVariants on Product {
    variants(first: 250) {
      nodes {
        ...ProductVariant
      }
    }
  }
  ${PRODUCT_VARIANT_FRAGMENT}
`;
const VARIANTS_QUERY = `#graphql
  ${PRODUCT_VARIANTS_FRAGMENT}
  query ProductVariants(
    $country: CountryCode
    $language: LanguageCode
    $handle: String!
  ) @inContext(country: $country, language: $language) {
    product(handle: $handle) {
      ...ProductVariants
    }
  }
`;
const route14 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Product,
  loader: loader$h,
  meta: meta$6
}, Symbol.toStringTag, { value: "Module" }));
const CUSTOMER_UPDATE_MUTATION = `#graphql
  # https://shopify.dev/docs/api/customer/latest/mutations/customerUpdate
  mutation customerUpdate(
    $customer: CustomerUpdateInput!
  ){
    customerUpdate(input: $customer) {
      customer {
        firstName
        lastName
        emailAddress {
          emailAddress
        }
        phoneNumber {
          phoneNumber
        }
      }
      userErrors {
        code
        field
        message
      }
    }
  }
`;
const meta$5 = () => {
  return [{ title: "Profile" }];
};
async function loader$g({ context: context2 }) {
  await context2.customerAccount.handleAuthStatus();
  return json2(
    {},
    {
      headers: {
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
async function action$3({ request, context: context2 }) {
  var _a2, _b2;
  const { customerAccount } = context2;
  if (request.method !== "PUT") {
    return json2({ error: "Method not allowed" }, { status: 405 });
  }
  const form = await request.formData();
  try {
    const customer = {};
    const validInputKeys = ["firstName", "lastName"];
    for (const [key, value] of form.entries()) {
      if (!validInputKeys.includes(key)) {
        continue;
      }
      if (typeof value === "string" && value.length) {
        customer[key] = value;
      }
    }
    const { data, errors } = await customerAccount.mutate(
      CUSTOMER_UPDATE_MUTATION,
      {
        variables: {
          customer
        }
      }
    );
    if (errors == null ? void 0 : errors.length) {
      throw new Error(errors[0].message);
    }
    if (!((_a2 = data == null ? void 0 : data.customerUpdate) == null ? void 0 : _a2.customer)) {
      throw new Error("Customer profile update failed.");
    }
    return json2(
      {
        error: null,
        customer: (_b2 = data == null ? void 0 : data.customerUpdate) == null ? void 0 : _b2.customer
      },
      {
        headers: {
          "Set-Cookie": await context2.session.commit()
        }
      }
    );
  } catch (error2) {
    return json2(
      { error: error2.message, customer: null },
      {
        status: 400,
        headers: {
          "Set-Cookie": await context2.session.commit()
        }
      }
    );
  }
}
function AccountProfile() {
  const account = useOutletContext();
  const { state } = useNavigation();
  const action2 = useActionData();
  const customer = (action2 == null ? void 0 : action2.customer) ?? (account == null ? void 0 : account.customer);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "account-profile", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: "My profile" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Form, { method: "PUT", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("legend", { children: "Personal information" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("fieldset", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "firstName", children: "First name" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            id: "firstName",
            name: "firstName",
            type: "text",
            autoComplete: "given-name",
            placeholder: "First name",
            "aria-label": "First name",
            defaultValue: customer.firstName ?? "",
            minLength: 2
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "lastName", children: "Last name" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            id: "lastName",
            name: "lastName",
            type: "text",
            autoComplete: "family-name",
            placeholder: "Last name",
            "aria-label": "Last name",
            defaultValue: customer.lastName ?? "",
            minLength: 2
          }
        )
      ] }),
      (action2 == null ? void 0 : action2.error) ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("mark", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("small", { children: action2.error }) }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "submit", disabled: state !== "idle", children: state !== "idle" ? "Updating" : "Update" })
    ] })
  ] });
}
const route15 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  action: action$3,
  default: AccountProfile,
  loader: loader$g,
  meta: meta$5
}, Symbol.toStringTag, { value: "Module" }));
async function loader$f() {
  return redirect2("/");
}
async function action$2({ context: context2 }) {
  return context2.customerAccount.logout();
}
const route16 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  action: action$2,
  loader: loader$f
}, Symbol.toStringTag, { value: "Module" }));
async function loader$e({ context: context2 }) {
  const data = await context2.storefront.query(POLICIES_QUERY);
  const policies = Object.values(data.shop || {});
  if (!policies.length) {
    throw new Response("No policies found", { status: 404 });
  }
  return json2({ policies });
}
function Policies() {
  const { policies } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "policies", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: "Policies" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: policies.map((policy) => {
      if (!policy) return null;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("fieldset", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: `/policies/${policy.handle}`, children: policy.title }) }, policy.id);
    }) })
  ] });
}
const POLICIES_QUERY = `#graphql
  fragment PolicyItem on ShopPolicy {
    id
    title
    handle
  }
  query Policies ($country: CountryCode, $language: LanguageCode)
    @inContext(country: $country, language: $language) {
    shop {
      privacyPolicy {
        ...PolicyItem
      }
      shippingPolicy {
        ...PolicyItem
      }
      termsOfService {
        ...PolicyItem
      }
      refundPolicy {
        ...PolicyItem
      }
      subscriptionPolicy {
        id
        title
        handle
      }
    }
  }
`;
const route17 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Policies,
  loader: loader$e
}, Symbol.toStringTag, { value: "Module" }));
async function loader$d() {
  return redirect2("/account/orders");
}
const route18 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$d
}, Symbol.toStringTag, { value: "Module" }));
async function loader$c({ request, context: context2 }) {
  return context2.customerAccount.login();
}
const route19 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$c
}, Symbol.toStringTag, { value: "Module" }));
async function loader$b({ request, context: context2, params }) {
  const { cart } = context2;
  const { code } = params;
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  let redirectParam = searchParams.get("redirect") || searchParams.get("return_to") || "/";
  if (redirectParam.includes("//")) {
    redirectParam = "/";
  }
  searchParams.delete("redirect");
  searchParams.delete("return_to");
  const redirectUrl = `${redirectParam}?${searchParams}`;
  if (!code) {
    return redirect2(redirectUrl);
  }
  const result = await cart.updateDiscountCodes([code]);
  const headers = cart.setCartId(result.cart.id);
  return redirect2(redirectUrl, {
    status: 303,
    headers
  });
}
const route20 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$b
}, Symbol.toStringTag, { value: "Module" }));
const meta$4 = ({ data }) => {
  return [{ title: `Durafoam | ${(data == null ? void 0 : data.page.title) ?? ""}` }];
};
async function loader$a({ params, context: context2 }) {
  if (!params.handle) {
    throw new Error("Missing page handle");
  }
  const { page } = await context2.storefront.query(PAGE_QUERY, {
    variables: {
      handle: params.handle
    }
  });
  if (!page) {
    throw new Response("Not Found", { status: 404 });
  }
  return json2({ page, handle: params.handle });
}
function Page() {
  const { page, handle } = useLoaderData();
  const isContactPage = handle === "contact";
  if (isContactPage) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pb-24", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: "relative py-16 overflow-hidden rounded-[3rem] bg-slate-900 mb-12 px-6 lg:px-20 text-white shadow-2xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-[url('https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&fit=crop&q=80')] opacity-20 bg-cover bg-center mix-blend-overlay" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-gradient-to-t from-slate-900 via-slate-900/60 to-transparent" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 max-w-4xl", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: "mb-4 flex space-x-2 text-[10px] font-bold text-white/40 uppercase tracking-widest", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: "/", className: "hover:text-primary-400 transition-colors", children: "Home" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "/" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-400", children: "Contact Us" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "text-4xl sm:text-5xl font-extrabold tracking-tight font-heading leading-tight", children: [
            "Get in ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-400", children: "Touch." })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-lg text-slate-300 leading-relaxed max-w-2xl", children: "Whether it's a bespoke foam configuration or a large-scale commercial project, our team of experts is ready to assist you." })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid lg:grid-cols-12 gap-8 lg:gap-12 px-4 sm:px-6 lg:px-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-5 space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 sm:p-8 rounded-[2rem] bg-white border border-slate-100 shadow-sm hover:shadow-premium transition-all duration-500 group", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-2xl bg-primary-50 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$e, { className: "w-5 h-5 text-primary-600" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-bold text-slate-900 mb-1", children: "Call Us" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-slate-500 mb-3", children: "Available Mon-Fri, 9am - 5pm" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: "tel:+441592328630",
                className: "text-lg font-extrabold text-primary-600 hover:text-primary-700 transition-colors",
                children: "01592 328630"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 sm:p-8 rounded-[2rem] bg-white border border-slate-100 shadow-sm hover:shadow-premium transition-all duration-500 group", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-2xl bg-blue-50 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$j, { className: "w-5 h-5 text-blue-600" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-bold text-slate-900 mb-1", children: "Email Us" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-slate-500 mb-3", children: "We usually respond within 24 hours" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: "mailto:info@durafoam.co.uk",
                className: "text-lg font-extrabold text-blue-600 hover:text-blue-700 transition-colors",
                children: "info@durafoam.co.uk"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 sm:p-8 rounded-[2rem] bg-white border border-slate-100 shadow-sm hover:shadow-premium transition-all duration-500 group", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$f, { className: "w-5 h-5 text-slate-600" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-bold text-slate-900 mb-1", children: "Visit Our Factory" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-slate-500 leading-relaxed italic", children: [
              "63 Cavendish Way, ",
              /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
              "Glenrothes, Fife, KY6 2SB"
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-7", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-[2.5rem] bg-slate-50 p-6 sm:p-10 border border-slate-100", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-extrabold text-slate-900 mb-6 font-heading italic", children: "Send a Message" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { className: "space-y-5", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid sm:grid-cols-2 gap-5", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-[10px] font-black uppercase tracking-widest text-slate-400 ml-1", children: "Full Name" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "text",
                    className: "w-full px-5 py-3.5 text-sm rounded-xl border-none ring-1 ring-slate-200 focus:ring-2 focus:ring-primary-600 outline-none transition-all",
                    placeholder: "John Doe"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-[10px] font-black uppercase tracking-widest text-slate-400 ml-1", children: "Email Address" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "email",
                    className: "w-full px-5 py-3.5 text-sm rounded-xl border-none ring-1 ring-slate-200 focus:ring-2 focus:ring-primary-600 outline-none transition-all",
                    placeholder: "john@example.com"
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-[10px] font-black uppercase tracking-widest text-slate-400 ml-1", children: "Message" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  rows: 4,
                  className: "w-full px-5 py-3.5 text-sm rounded-xl border-none ring-1 ring-slate-200 focus:ring-2 focus:ring-primary-600 outline-none transition-all resize-none",
                  placeholder: "Tell us about your project..."
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "w-full sm:w-auto px-10 py-4 text-sm bg-brand-dark text-white font-extrabold rounded-xl shadow-xl hover:bg-slate-800 transition-all hover:-translate-y-1 active:scale-95", children: "Submit Inquiry" })
          ] })
        ] }) })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pb-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: "py-16 text-center max-w-4xl mx-auto px-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl sm:text-5xl font-extrabold tracking-tight text-slate-900 font-heading", children: page.title }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-6 flex justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-1 w-16 bg-primary-600 rounded-full" }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("main", { className: "max-w-4xl mx-auto px-4 sm:px-6 lg:px-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx("article", { className: "prose prose-slate max-w-none bg-white p-6 sm:p-12 rounded-[2.5rem] shadow-sm ring-1 ring-slate-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { dangerouslySetInnerHTML: { __html: page.body } }) }) })
  ] });
}
const PAGE_QUERY = `#graphql
  query Page(
    $language: LanguageCode,
    $country: CountryCode,
    $handle: String!
  )
  @inContext(language: $language, country: $country) {
    page(handle: $handle) {
      id
      title
      body
      seo {
        description
        title
      }
    }
  }
`;
const route21 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Page,
  loader: loader$a,
  meta: meta$4
}, Symbol.toStringTag, { value: "Module" }));
const MAX_URLS = 250;
async function loader$9({
  request,
  context: { storefront }
}) {
  const data = await storefront.query(SITEMAP_QUERY, {
    variables: {
      urlLimits: MAX_URLS,
      language: storefront.i18n.language
    }
  });
  if (!data) {
    throw new Response("No data found", { status: 404 });
  }
  const sitemap = generateSitemap({ data, baseUrl: new URL(request.url).origin });
  return new Response(sitemap, {
    headers: {
      "Content-Type": "application/xml",
      "Cache-Control": `max-age=${60 * 60 * 24}`
    }
  });
}
function xmlEncode(string) {
  return string.replace(/[&<>'"]/g, (char) => `&#${char.charCodeAt(0)};`);
}
function generateSitemap({
  data,
  baseUrl
}) {
  const products = flattenConnection(data.products).filter((product) => product.onlineStoreUrl).map((product) => {
    var _a2;
    const url = `${baseUrl}/products/${xmlEncode(product.handle)}`;
    const productEntry = {
      url,
      lastMod: product.updatedAt,
      changeFreq: "daily"
    };
    if ((_a2 = product.featuredImage) == null ? void 0 : _a2.url) {
      productEntry.image = {
        url: xmlEncode(product.featuredImage.url)
      };
      if (product.title) {
        productEntry.image.title = xmlEncode(product.title);
      }
      if (product.featuredImage.altText) {
        productEntry.image.caption = xmlEncode(product.featuredImage.altText);
      }
    }
    return productEntry;
  });
  const collections = flattenConnection(data.collections).filter((collection) => collection.onlineStoreUrl).map((collection) => {
    const url = `${baseUrl}/collections/${collection.handle}`;
    return {
      url,
      lastMod: collection.updatedAt,
      changeFreq: "daily"
    };
  });
  const pages = flattenConnection(data.pages).filter((page) => page.onlineStoreUrl).map((page) => {
    const url = `${baseUrl}/pages/${page.handle}`;
    return {
      url,
      lastMod: page.updatedAt,
      changeFreq: "weekly"
    };
  });
  const urls = [...products, ...collections, ...pages];
  return `
    <urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
    >
      ${urls.map(renderUrlTag).join("")}
    </urlset>`;
}
function renderUrlTag({ url, lastMod, changeFreq, image }) {
  const imageTag = image ? `<image:image>
        <image:loc>${image.url}</image:loc>
        <image:title>${image.title ?? ""}</image:title>
        <image:caption>${image.caption ?? ""}</image:caption>
      </image:image>`.trim() : "";
  return `
    <url>
      <loc>${url}</loc>
      <lastmod>${lastMod}</lastmod>
      <changefreq>${changeFreq}</changefreq>
      ${imageTag}
    </url>
  `.trim();
}
const SITEMAP_QUERY = `#graphql
  query Sitemap($urlLimits: Int, $language: LanguageCode)
  @inContext(language: $language) {
    products(
      first: $urlLimits
      query: "published_status:'online_store:visible'"
    ) {
      nodes {
        updatedAt
        handle
        onlineStoreUrl
        title
        featuredImage {
          url
          altText
        }
      }
    }
    collections(
      first: $urlLimits
      query: "published_status:'online_store:visible'"
    ) {
      nodes {
        updatedAt
        handle
        onlineStoreUrl
      }
    }
    pages(first: $urlLimits, query: "published_status:'published'") {
      nodes {
        updatedAt
        handle
        onlineStoreUrl
      }
    }
  }
`;
const route22 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$9
}, Symbol.toStringTag, { value: "Module" }));
const meta$3 = () => {
  return [{ title: `Hydrogen | Blogs` }];
};
const loader$8 = async ({
  request,
  context: { storefront }
}) => {
  const paginationVariables = fn(request, {
    pageBy: 10
  });
  const { blogs } = await storefront.query(BLOGS_QUERY, {
    variables: {
      ...paginationVariables
    }
  });
  return json2({ blogs });
};
function Blogs() {
  const { blogs } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "blogs", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: "Blogs" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "blogs-grid", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ln, { connection: blogs, children: ({ nodes, isLoading, PreviousLink, NextLink }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(PreviousLink, { children: isLoading ? "Loading..." : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "↑ Load previous" }) }),
        nodes.map((blog) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            Link,
            {
              className: "blog",
              prefetch: "intent",
              to: `/blogs/${blog.handle}`,
              children: /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: blog.title })
            },
            blog.handle
          );
        }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(NextLink, { children: isLoading ? "Loading..." : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Load more ↓" }) })
      ] });
    } }) })
  ] });
}
const BLOGS_QUERY = `#graphql
  query Blogs(
    $country: CountryCode
    $endCursor: String
    $first: Int
    $language: LanguageCode
    $last: Int
    $startCursor: String
  ) @inContext(country: $country, language: $language) {
    blogs(
      first: $first,
      last: $last,
      before: $startCursor,
      after: $endCursor
    ) {
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
      nodes {
        title
        handle
        seo {
          title
          description
        }
      }
    }
  }
`;
const route23 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Blogs,
  loader: loader$8,
  meta: meta$3
}, Symbol.toStringTag, { value: "Module" }));
async function loader$7({ request, context: context2 }) {
  const url = new URL(request.url);
  const { shop } = await context2.storefront.query(ROBOTS_QUERY);
  const shopId = parseGid(shop.id).id;
  const body = robotsTxtData({ url: url.origin, shopId });
  return new Response(body, {
    status: 200,
    headers: {
      "Content-Type": "text/plain",
      "Cache-Control": `max-age=${60 * 60 * 24}`
    }
  });
}
function robotsTxtData({ url, shopId }) {
  const sitemapUrl = url ? `${url}/sitemap.xml` : void 0;
  return `
User-agent: *
${generalDisallowRules({ sitemapUrl, shopId })}

# Google adsbot ignores robots.txt unless specifically named!
User-agent: adsbot-google
Disallow: /checkouts/
Disallow: /checkout
Disallow: /carts
Disallow: /orders
${shopId ? `Disallow: /${shopId}/checkouts` : ""}
${shopId ? `Disallow: /${shopId}/orders` : ""}
Disallow: /*?*oseid=*
Disallow: /*preview_theme_id*
Disallow: /*preview_script_id*

User-agent: Nutch
Disallow: /

User-agent: AhrefsBot
Crawl-delay: 10
${generalDisallowRules({ sitemapUrl, shopId })}

User-agent: AhrefsSiteAudit
Crawl-delay: 10
${generalDisallowRules({ sitemapUrl, shopId })}

User-agent: MJ12bot
Crawl-Delay: 10

User-agent: Pinterest
Crawl-delay: 1
`.trim();
}
function generalDisallowRules({
  shopId,
  sitemapUrl
}) {
  return `Disallow: /admin
Disallow: /cart
Disallow: /orders
Disallow: /checkouts/
Disallow: /checkout
${shopId ? `Disallow: /${shopId}/checkouts` : ""}
${shopId ? `Disallow: /${shopId}/orders` : ""}
Disallow: /carts
Disallow: /account
Disallow: /collections/*sort_by*
Disallow: /*/collections/*sort_by*
Disallow: /collections/*+*
Disallow: /collections/*%2B*
Disallow: /collections/*%2b*
Disallow: /*/collections/*+*
Disallow: /*/collections/*%2B*
Disallow: /*/collections/*%2b*
Disallow: */collections/*filter*&*filter*
Disallow: /blogs/*+*
Disallow: /blogs/*%2B*
Disallow: /blogs/*%2b*
Disallow: /*/blogs/*+*
Disallow: /*/blogs/*%2B*
Disallow: /*/blogs/*%2b*
Disallow: /*?*oseid=*
Disallow: /*preview_theme_id*
Disallow: /*preview_script_id*
Disallow: /policies/
Disallow: /*/*?*ls=*&ls=*
Disallow: /*/*?*ls%3D*%3Fls%3D*
Disallow: /*/*?*ls%3d*%3fls%3d*
Disallow: /search
Allow: /search/
Disallow: /search/?*
Disallow: /apple-app-site-association
Disallow: /.well-known/shopify/monorail
${sitemapUrl ? `Sitemap: ${sitemapUrl}` : ""}`;
}
const ROBOTS_QUERY = `#graphql
  query StoreRobots($country: CountryCode, $language: LanguageCode)
   @inContext(country: $country, language: $language) {
    shop {
      id
    }
  }
`;
const route24 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$7
}, Symbol.toStringTag, { value: "Module" }));
async function loader$6({ request, context: context2, params }) {
  var _a2;
  const { cart } = context2;
  const { lines } = params;
  if (!lines) return redirect2("/cart");
  const linesMap = lines.split(",").map((line) => {
    const lineDetails = line.split(":");
    const variantId = lineDetails[0];
    const quantity = parseInt(lineDetails[1], 10);
    return {
      merchandiseId: `gid://shopify/ProductVariant/${variantId}`,
      quantity
    };
  });
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const discount = searchParams.get("discount");
  const discountArray = discount ? [discount] : [];
  const result = await cart.create({
    lines: linesMap,
    discountCodes: discountArray
  });
  const cartResult = result.cart;
  if (((_a2 = result.errors) == null ? void 0 : _a2.length) || !cartResult) {
    throw new Response("Link may be expired. Try checking the URL.", {
      status: 410
    });
  }
  const headers = cart.setCartId(cartResult.id);
  if (cartResult.checkoutUrl) {
    return redirect2(cartResult.checkoutUrl, { headers });
  } else {
    throw new Error("No checkout URL found");
  }
}
function Component() {
  return null;
}
const route25 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Component,
  loader: loader$6
}, Symbol.toStringTag, { value: "Module" }));
async function loader$5({ context: context2 }) {
  await context2.customerAccount.handleAuthStatus();
  return redirect2("/account", {
    headers: {
      "Set-Cookie": await context2.session.commit()
    }
  });
}
const route26 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loader: loader$5
}, Symbol.toStringTag, { value: "Module" }));
function FormInput({
  id,
  name,
  label,
  type = "number",
  value,
  onChange,
  min = "0.1",
  step = "0.1",
  placeholder,
  trailingAddon
}) {
  if (trailingAddon) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "label",
        {
          htmlFor: id,
          className: "block text-sm/6 font-medium text-gray-900",
          children: label
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center rounded-md bg-white outline outline-1 -outline-offset-1 outline-gray-300 focus-within:outline focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-indigo-600", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            id,
            name,
            type,
            value,
            onChange: (e2) => onChange(Number(e2.target.value)),
            min,
            step,
            placeholder,
            "aria-describedby": `${id}-addon`,
            className: "block w-0 min-w-0 flex-1 border-0 bg-transparent py-1.5 pl-3 pr-2 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-0 sm:text-sm/6"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            id: `${id}-addon`,
            className: "flex-shrink-0 select-none px-3 py-1.5 text-base text-gray-500 sm:text-sm/6",
            children: trailingAddon
          }
        )
      ] }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: id, className: "block text-sm/6 font-medium text-gray-900", children: label }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        id,
        name,
        type,
        value,
        onChange: (e2) => onChange(Number(e2.target.value)),
        min,
        step,
        placeholder,
        className: "block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 sm:text-sm/6"
      }
    ) })
  ] });
}
const DimensionArrow = ({
  start,
  end,
  label,
  color = "#000000"
}) => {
  const points = reactExports.useMemo(
    () => [new Vector3(...start), new Vector3(...end)],
    [start, end]
  );
  const middle = [
    (start[0] + end[0]) / 2,
    (start[1] + end[1]) / 2,
    (start[2] + end[2]) / 2
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("group", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Line4,
      {
        points,
        color,
        lineWidth: 1.5,
        dashed: false
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "mesh",
      {
        position: start,
        quaternion: new Quaternion().setFromUnitVectors(
          new Vector3(0, 1, 0),
          new Vector3(...end).sub(new Vector3(...start)).normalize()
        ),
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("coneGeometry", { args: [0.015, 0.05, 8] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("meshBasicMaterial", { color })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "mesh",
      {
        position: end,
        quaternion: new Quaternion().setFromUnitVectors(
          new Vector3(0, -1, 0),
          new Vector3(...end).sub(new Vector3(...start)).normalize()
        ),
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("coneGeometry", { args: [0.015, 0.05, 8] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("meshBasicMaterial", { color })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Html, { position: middle, center: true, distanceFactor: 2, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white/90 backdrop-blur border border-slate-200 px-1.5 py-0.5 rounded shadow-sm text-[10px] font-bold text-slate-900 pointer-events-none", children: label }) })
  ] });
};
const Preview = ({
  shape,
  dimensions,
  color
}) => {
  const ShapeComponent = reactExports.useMemo(() => {
    const s2 = shape;
    switch (s2) {
      case "rectangle":
        return Rectangle;
      case "roundedRectangle":
        return RoundedRectangle;
      case "lShape":
        return LShape;
      case "tShape":
        return TShape;
      case "bolster":
        return Bolster;
      case "circle":
        return Circle;
      case "semicircle":
        return Semicircle;
      case "bullnose":
        return Bullnose;
      case "wedge":
        return Wedge;
      case "wedgeSeat":
        return WedgeSeat;
      case "clippedBolster":
        return ClippedBolster;
      case "trapezium":
        return Trapezium;
      case "boatMattress":
        return BoatMattress;
      case "curvedL":
        return CurvedL;
      case "curvedT":
        return CurvedT;
      default:
        return Rectangle;
    }
  }, [shape]);
  const scaledDimensions = reactExports.useMemo(() => {
    const scaled = {};
    Object.entries(dimensions).forEach(([key, value]) => {
      scaled[key] = value * 1e-3;
    });
    return scaled;
  }, [dimensions]);
  const labels = reactExports.useMemo(() => {
    const items = [];
    const offset = 0.08;
    let w2 = 0, h2 = 0, d2 = scaledDimensions.depth || 0.1;
    switch (shape) {
      case "rectangle":
      case "roundedRectangle":
      case "trapezium":
      case "bullnose":
      case "wedge":
      case "wedgeSeat":
      case "curvedL":
      case "curvedT":
        w2 = scaledDimensions.width || 0.8;
        h2 = scaledDimensions.height || 0.6;
        break;
      case "lShape":
      case "tShape":
      case "bolster":
      case "clippedBolster":
        w2 = scaledDimensions.bottomWidth || 0.8;
        h2 = scaledDimensions.height || 0.6;
        break;
      case "circle":
      case "semicircle":
        w2 = scaledDimensions.diameter || 0.6;
        h2 = shape === "circle" ? w2 : w2 / 2;
        break;
      case "boatMattress":
        w2 = Math.max(
          scaledDimensions.topWidth || 0,
          scaledDimensions.bottomWidth || 0
        );
        h2 = scaledDimensions.width || 1.8;
        break;
    }
    if (shape === "circle" || shape === "semicircle") {
      if (dimensions.diameter) {
        items.push({
          text: `Ø ${dimensions.diameter}mm`,
          start: [-w2 / 2, -h2 / 2 - offset, d2 / 2],
          end: [w2 / 2, -h2 / 2 - offset, d2 / 2]
        });
      }
    } else {
      const displayWidth = dimensions.width || dimensions.bottomWidth;
      if (displayWidth) {
        items.push({
          text: `${displayWidth}mm`,
          start: [-w2 / 2, -h2 / 2 - offset, d2 / 2],
          end: [w2 / 2, -h2 / 2 - offset, d2 / 2]
        });
      }
      const displayHeight = dimensions.height || (shape === "boatMattress" ? dimensions.width : 0);
      if (displayHeight) {
        items.push({
          text: `${displayHeight}mm`,
          start: [-w2 / 2 - offset, -h2 / 2, d2 / 2],
          end: [-w2 / 2 - offset, h2 / 2, d2 / 2]
        });
      }
    }
    if (dimensions.depth) {
      items.push({
        text: `${dimensions.depth}mm`,
        start: [w2 / 2 + offset, -h2 / 2, -d2 / 2],
        end: [w2 / 2 + offset, -h2 / 2, d2 / 2]
      });
    }
    if (shape === "lShape" || shape === "tShape" || shape === "trapezium" || shape === "boatMattress" || shape === "bolster" || shape === "clippedBolster") {
      if (dimensions.topWidth) {
        const tw = scaledDimensions.topWidth || 0.3;
        const topY = shape === "boatMattress" ? -h2 / 2 : h2 / 2;
        items.push({
          text: `${dimensions.topWidth}mm`,
          start: [-tw / 2, topY + offset, d2 / 2],
          end: [tw / 2, topY + offset, d2 / 2]
        });
      }
      if (dimensions.edgeHeight) {
        const eh = scaledDimensions.edgeHeight || 0.2;
        items.push({
          text: `${dimensions.edgeHeight}mm`,
          start: [w2 / 2 + offset * 2, -h2 / 2, d2 / 2],
          end: [w2 / 2 + offset * 2, -h2 / 2 + eh, d2 / 2]
        });
      }
    }
    return items;
  }, [shape, dimensions, scaledDimensions]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Stage,
    {
      shadows: "contact",
      adjustCamera: true,
      intensity: 0.5,
      environment: null,
      center: false,
      children: /* @__PURE__ */ jsxRuntimeExports.jsx("group", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Center, { precise: true, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ShapeComponent, { ...scaledDimensions, color }),
        labels.map((label, i2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          DimensionArrow,
          {
            start: label.start,
            end: label.end,
            label: label.text
          },
          `${shape}-${i2}`
        ))
      ] }) }, shape)
    }
  );
};
function Designer() {
  var _a2;
  const fetcher = useFetcher();
  const [shape, setShape] = reactExports.useState("rectangle");
  const [dimensions, setDimensions] = reactExports.useState(() => {
    const allDefaults = {};
    Object.values(shapeConfigs).forEach((config) => {
      Object.entries(config.fields).forEach(([key, field]) => {
        allDefaults[key] = field.default;
      });
    });
    return allDefaults;
  });
  const [foamType, setFoamType] = reactExports.useState("medium-firm-white");
  const [addition, setAddition] = reactExports.useState("none");
  const [hasCover, setHasCover] = reactExports.useState(false);
  const priceBreakdown = reactExports.useMemo(() => {
    return calculatePrice(shape, dimensions, foamType, addition, hasCover);
  }, [shape, dimensions, foamType, addition, hasCover]);
  const foamColor = FOAM_TYPE_CONFIG[foamType].color;
  reactExports.useCallback(() => {
  }, []);
  const updateDimension = (key, value) => {
    setDimensions((prev) => ({ ...prev, [key]: value }));
  };
  const handleAddToCart = () => {
    fetcher.submit(
      JSON.stringify({ shape, dimensions, foamType, addition, hasCover }),
      {
        method: "POST",
        action: "/api/create-custom-foam",
        encType: "application/json"
      }
    );
  };
  reactExports.useEffect(() => {
    var _a3;
    if ((_a3 = fetcher.data) == null ? void 0 : _a3.success) {
      window.location.href = "/cart?cartOpen=false";
    }
  }, [fetcher.data]);
  const isSubmitting = fetcher.state !== "idle";
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-slate-50 min-h-screen", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:grid lg:grid-cols-2 lg:items-start lg:gap-x-12", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:sticky lg:top-24 space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative aspect-[4/5] bg-white rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50 overflow-hidden group", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Canvas2,
          {
            shadows: true,
            camera: { position: [2, 2, 2], fov: 45, near: 0.1, far: 2e3 },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("color", { attach: "background", args: ["#ffffff"] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Preview,
                {
                  shape,
                  dimensions,
                  color: foamColor
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                OrbitControls2,
                {
                  makeDefault: true,
                  minPolarAngle: 0,
                  maxPolarAngle: Math.PI / 1.75
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute bottom-4 left-1/2 -translate-x-1/2 bg-white/80 backdrop-blur px-4 py-2 rounded-full border border-slate-200 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs font-medium text-slate-600", children: "Drag to rotate • Scroll to zoom" }) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(PriceBreakdown, { breakdown: priceBreakdown }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: handleAddToCart,
          disabled: isSubmitting,
          className: "flex-1 px-8 py-4 text-base font-semibold text-white bg-indigo-600 border border-transparent rounded-2xl hover:bg-indigo-700 shadow-lg shadow-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all active:scale-[0.98]",
          children: isSubmitting ? "Adding to Cart..." : "Add to Cart"
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-10 px-4 sm:mt-16 sm:px-0 lg:mt-0 space-y-10", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl", children: "Custom Foam Designer" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-3 text-lg text-slate-500", children: "Configure your custom foam in 3D. Choose from multiple shapes and professional foam types." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "space-y-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-lg font-semibold text-slate-900 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex h-6 w-6 items-center justify-center rounded-full bg-indigo-600 text-[10px] font-bold text-white", children: "1" }),
            "Select Shape"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-3 sm:grid-cols-5 gap-3", children: Object.keys(shapeConfigs).map((shapeKey) => {
            const Icon = shapeIcons[shapeKey];
            const isSelected = shape === shapeKey;
            return /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => setShape(shapeKey),
                className: `flex flex-col items-center justify-center p-3 rounded-2xl border-2 transition-all ${isSelected ? "border-indigo-600 bg-indigo-50 text-indigo-600 shadow-sm" : "border-slate-100 bg-white text-slate-400 hover:border-slate-200 hover:bg-slate-50"}`,
                children: [
                  Icon && /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 mb-2" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-bold text-center uppercase tracking-tighter truncate w-full", children: shapeKey.replace(/([A-Z])/g, " $1") })
                ]
              },
              shapeKey
            );
          }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-lg font-semibold text-slate-900 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex h-6 w-6 items-center justify-center rounded-full bg-indigo-600 text-[10px] font-bold text-white", children: "2" }),
            "Specify Dimensions"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ShapeDiagram,
            {
              shape,
              dimensions,
              onDimensionChange: updateDimension
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4", children: Object.entries(shapeConfigs[shape].fields).map(
            ([key, field]) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              FormInput,
              {
                id: key,
                name: key,
                label: field.label,
                value: dimensions[key],
                onChange: (value) => updateDimension(key, value),
                trailingAddon: "mm"
              },
              key
            )
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-lg font-semibold text-slate-900 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex h-6 w-6 items-center justify-center rounded-full bg-indigo-600 text-[10px] font-bold text-white", children: "3" }),
            "Choose Foam Type"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(FoamTypeSelector, { value: foamType, onChange: setFoamType })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-lg font-semibold text-slate-900 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex h-6 w-6 items-center justify-center rounded-full bg-indigo-600 text-[10px] font-bold text-white", children: "4" }),
            "Optional Additions"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 rounded-2xl bg-white border border-slate-200 p-6 shadow-sm", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionSelector, { value: addition, onChange: setAddition }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-slate-100 pt-4 mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CoverCheckbox, { checked: hasCover, onChange: setHasCover }) })
          ] })
        ] }),
        ((_a2 = fetcher.data) == null ? void 0 : _a2.error) && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-2xl bg-red-50 p-4 border border-red-100", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "svg",
            {
              className: "h-5 w-5 text-red-400",
              viewBox: "0 0 20 20",
              fill: "currentColor",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "path",
                {
                  fillRule: "evenodd",
                  d: "M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z",
                  clipRule: "evenodd"
                }
              )
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-red-800", children: fetcher.data.error }) })
        ] }) })
      ] })
    ] })
  ] }) }) });
}
async function action$1({ request }) {
  const formData = await request.formData();
  console.log("action");
  const data = Object.fromEntries(formData.entries());
  console.log(JSON.stringify(data));
  const rectangleDimensions = convertDimensionsToRectangle(
    data.shape,
    data
  );
  console.log(rectangleDimensions);
  const price = getPrice(data.shape, {
    width: Number(rectangleDimensions.width),
    height: Number(rectangleDimensions.height),
    depth: Number(rectangleDimensions.depth)
  });
  console.log(JSON.stringify(price));
  return json2({ ok: true, price });
}
const route27 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  action: action$1,
  default: Designer
}, Symbol.toStringTag, { value: "Module" }));
const CUSTOMER_FRAGMENT = `#graphql
  fragment Customer on Customer {
    firstName
    lastName
    defaultAddress {
      ...Address
    }
    addresses(first: 6) {
      nodes {
        ...Address
      }
    }
  }
  fragment Address on CustomerAddress {
    id
    formatted
    firstName
    lastName
    company
    address1
    address2
    territoryCode
    zoneCode
    city
    zip
    phoneNumber
  }
`;
const CUSTOMER_DETAILS_QUERY = `#graphql
  query CustomerDetails {
    customer {
      ...Customer
    }
  }
  ${CUSTOMER_FRAGMENT}
`;
function shouldRevalidate() {
  return true;
}
async function loader$4({ context: context2 }) {
  const { data, errors } = await context2.customerAccount.query(
    CUSTOMER_DETAILS_QUERY
  );
  if ((errors == null ? void 0 : errors.length) || !(data == null ? void 0 : data.customer)) {
    throw new Error("Customer not found");
  }
  return json2(
    { customer: data.customer },
    {
      headers: {
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Set-Cookie": await context2.session.commit()
      }
    }
  );
}
function AccountLayout() {
  const { customer } = useLoaderData();
  const heading = customer ? customer.firstName ? `Welcome, ${customer.firstName}` : `Welcome to your account.` : "Account Details";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-7xl mx-auto px-4 sm:px-6 lg:px-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl font-bold text-gray-900 mb-2", children: heading }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600", children: "Manage your account settings and view your order history" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(AccountMenu, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Outlet, { context: { customer } }) })
  ] });
}
function AccountMenu() {
  function isActiveStyle({
    isActive,
    isPending
  }) {
    return {
      fontWeight: isActive ? "bold" : void 0,
      color: isPending ? "grey" : isActive ? "#1f2937" : "#6b7280",
      backgroundColor: isActive ? "#f3f4f6" : "transparent",
      padding: "0.5rem 1rem",
      borderRadius: "0.375rem",
      textDecoration: "none"
    };
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "nav",
    {
      role: "navigation",
      className: "flex items-center space-x-1 bg-gray-100 p-1 rounded-lg",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          NavLink,
          {
            to: "/account/orders",
            style: isActiveStyle,
            className: "text-sm font-medium",
            children: "Orders"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          NavLink,
          {
            to: "/account/profile",
            style: isActiveStyle,
            className: "text-sm font-medium",
            children: "Profile"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          NavLink,
          {
            to: "/account/addresses",
            style: isActiveStyle,
            className: "text-sm font-medium",
            children: "Addresses"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Logout, {})
      ]
    }
  );
}
function Logout() {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Form, { className: "account-logout", method: "POST", action: "/account/logout", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    "button",
    {
      type: "submit",
      className: "text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-2 rounded-md hover:bg-gray-200 transition-colors duration-200",
      children: "Sign out"
    }
  ) });
}
const route28 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AccountLayout,
  loader: loader$4,
  shouldRevalidate
}, Symbol.toStringTag, { value: "Module" }));
const meta$2 = () => {
  return [{ title: `Hydrogen | Search` }];
};
async function loader$3({ request, context: context2 }) {
  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const variables = fn(request, { pageBy: 8 });
  const searchTerm = String(searchParams.get("q") || "");
  if (!searchTerm) {
    return {
      searchResults: { results: null, totalResults: 0 },
      searchTerm
    };
  }
  const { errors, ...data } = await context2.storefront.query(SEARCH_QUERY, {
    variables: {
      query: searchTerm,
      ...variables
    }
  });
  if (!data) {
    throw new Error("No search data returned from Shopify API");
  }
  const totalResults = Object.values(data).reduce((total, value) => {
    return total + value.nodes.length;
  }, 0);
  const searchResults = {
    results: data,
    totalResults
  };
  return defer2({
    searchTerm,
    searchResults
  });
}
function SearchPage() {
  const { searchTerm, searchResults } = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "search", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pt-24 pb-12 text-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl font-bold tracking-tight text-gray-900", children: "Search" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mx-auto mt-4 max-w-3xl text-base text-gray-500", children: "Search for the exact product you are looking for." })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mx-auto max-w-2xl", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SearchForm, { searchTerm }) }),
    !searchTerm ? /* @__PURE__ */ jsxRuntimeExports.jsx(NoSearchTerm, {}) : !searchResults.totalResults ? /* @__PURE__ */ jsxRuntimeExports.jsx(NoSearchResults, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchResults,
      {
        results: searchResults.results,
        searchTerm
      }
    )
  ] });
}
const SEARCH_QUERY = `#graphql
  fragment SearchProduct on Product {
    __typename
    handle
    id
    publishedAt
    title
    trackingParameters
    vendor
    variants(first: 1) {
      nodes {
        id
        image {
          url
          altText
          width
          height
        }
        price {
          amount
          currencyCode
        }
        compareAtPrice {
          amount
          currencyCode
        }
        selectedOptions {
          name
          value
        }
        product {
          handle
          title
        }
      }
    }
  }
  fragment SearchPage on Page {
     __typename
     handle
    id
    title
    trackingParameters
  }
  fragment SearchArticle on Article {
    __typename
    handle
    id
    title
    trackingParameters
  }
  query search(
    $country: CountryCode
    $endCursor: String
    $first: Int
    $language: LanguageCode
    $last: Int
    $query: String!
    $startCursor: String
  ) @inContext(country: $country, language: $language) {
    products: search(
      query: $query,
      unavailableProducts: HIDE,
      types: [PRODUCT],
      first: $first,
      sortKey: RELEVANCE,
      last: $last,
      before: $startCursor,
      after: $endCursor
    ) {
      nodes {
        ...on Product {
          ...SearchProduct
        }
      }
      pageInfo {
        hasNextPage
        hasPreviousPage
        startCursor
        endCursor
      }
    }
    pages: search(
      query: $query,
      types: [PAGE],
      first: 10
    ) {
      nodes {
        ...on Page {
          ...SearchPage
        }
      }
    }
    articles: search(
      query: $query,
      types: [ARTICLE],
      first: 10
    ) {
      nodes {
        ...on Article {
          ...SearchArticle
        }
      }
    }
  }
`;
const route29 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: SearchPage,
  loader: loader$3,
  meta: meta$2
}, Symbol.toStringTag, { value: "Module" }));
const testimonials = [
  {
    body: "Got a lovely pair of mattresses made bespoke for my van in a hurry. Durafoam were able to help me and allowed me to pick up direct from factory. Great service!",
    author: { name: "Kieran Dudley", role: "Van Life Enthusiast" },
    stars: 5,
    date: "March 2023"
  },
  {
    body: "My order arrived today and it fits first class, very good service and I would use again. Highly recommended for custom cuts!",
    author: { name: "Andrew Hughes", role: "Verified Customer" },
    stars: 5,
    date: "April 2023"
  },
  {
    body: "Very good Firm Foam from Seller. Great comms and very helpful and efficient. Cant recommend enough for furniture restoration.",
    author: { name: "Shiny Stars", role: "Upholsterer" },
    stars: 5,
    date: "May 2023"
  },
  {
    body: "Bought 5inch thick foam for camper van cushions. The quality is exceptional and delivery was incredibly fast.",
    author: { name: "John Doe", role: "Camper Builder" },
    stars: 5,
    date: "June 2023"
  },
  {
    body: "Nice foam, perfect size for my headboard. Well packed and arrived in pristine condition. Excellent value for money.",
    author: { name: "Danielle Smith", role: "Home DIYer" },
    stars: 4,
    date: "July 2023"
  },
  {
    body: "The 3D designer made ordering so easy. The foam fits my window seat perfectly. Will definitely be ordering again!",
    author: { name: "Sarah Wilson", role: "Interior Designer" },
    stars: 5,
    date: "August 2023"
  }
];
function Testimonials() {
  const [isPaused, setIsPaused] = reactExports.useState(false);
  reactExports.useRef(null);
  const displayItems = [...testimonials, ...testimonials, ...testimonials];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "relative isolate bg-white py-24 sm:py-32 overflow-hidden", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "absolute inset-x-0 top-1/2 -z-10 -translate-y-1/2 transform-gpu overflow-hidden opacity-30 blur-3xl",
        "aria-hidden": "true",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "ml-[max(50%,38rem)] aspect-[1313/771] w-[82.0625rem] bg-gradient-to-tr from-primary-200 to-blue-200",
            style: {
              clipPath: "polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)"
            }
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-7xl px-6 lg:px-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-2xl text-center mb-16", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-bold tracking-tight text-primary-600 uppercase", children: "Testimonials" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-4 text-4xl font-extrabold tracking-tight text-slate-900 sm:text-5xl font-heading", children: [
          "Trusted by ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600", children: "Thousands." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-6 text-lg leading-8 text-slate-600", children: "Join the community of happy customers who rely on Durafoam for their bespoke comfort needs." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: "relative mt-8 flex overflow-hidden group",
          onMouseEnter: () => setIsPaused(true),
          onMouseLeave: () => setIsPaused(false),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-y-0 left-0 w-32 bg-gradient-to-r from-white to-transparent z-10" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-y-0 right-0 w-32 bg-gradient-to-l from-white to-transparent z-10" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: `flex gap-8 py-4 animate-infinite-scroll ${isPaused ? "pause-animation" : ""}`,
                style: { width: "max-content" },
                children: displayItems.map((testimonial, idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: "w-[400px] flex-none rounded-[2rem] bg-white p-8 shadow-sm ring-1 ring-slate-200 transition-all duration-500 hover:shadow-premium hover:ring-primary-100 hover:-translate-y-1",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-x-1 text-yellow-500 mb-6", children: [...Array(5)].map((_2, i2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                        ForwardRef$4,
                        {
                          className: `h-5 w-5 ${i2 < testimonial.stars ? "text-yellow-400" : "text-slate-200"}`
                        },
                        i2
                      )) }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("blockquote", { className: "text-lg leading-8 text-slate-700 italic", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: `"${testimonial.body}"` }) }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-8 flex items-center gap-x-4", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-10 rounded-full bg-primary-100 flex items-center justify-center font-bold text-primary-700", children: testimonial.author.name.charAt(0) }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm leading-6", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-bold text-slate-900", children: testimonial.author.name }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-slate-500 flex items-center gap-2", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: testimonial.author.role }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-slate-300", children: "•" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: testimonial.date })
                          ] })
                        ] })
                      ] })
                    ]
                  },
                  `${testimonial.author.name}-${idx}`
                ))
              }
            )
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "style",
      {
        dangerouslySetInnerHTML: {
          __html: `
        @keyframes infinite-scroll {
          from { transform: translateX(0); }
          to { transform: translateX(calc(-33.33% - 1.33rem)); }
        }
        .animate-infinite-scroll {
          animation: infinite-scroll 40s linear infinite;
        }
        .pause-animation {
          animation-play-state: paused;
        }
      `
        }
      }
    )
  ] });
}
const premiumHero = "/assets/premium_hero-BavNRkyN.png";
function Hero() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative isolate overflow-hidden bg-transparent px-4 lg:px-0", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "absolute inset-x-0 -top-40 -z-10 transform-gpu overflow-hidden blur-3xl sm:-top-80",
        "aria-hidden": "true",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "relative left-[calc(50%-11rem)] aspect-[1155/678] w-[36.125rem] -translate-x-1/2 rotate-[30deg] bg-gradient-to-tr from-[#6B9BDA] to-[#91B7E6] opacity-20 sm:left-[calc(50%-30rem)] sm:w-[72.1875rem]",
            style: {
              clipPath: "polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)"
            }
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-7xl px-6 pb-16 pt-6 sm:pb-24 lg:flex lg:px-8 lg:py-16 items-center gap-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-2xl flex-shrink-0 lg:mx-0 lg:max-w-xl lg:pt-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-8 sm:mt-12 lg:mt-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Link, { to: "/designer", className: "inline-flex space-x-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "rounded-full bg-primary-600/10 px-3 py-1 text-sm font-semibold leading-6 text-primary-600 ring-1 ring-inset ring-primary-600/10", children: "New Feature" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center space-x-2 text-sm font-medium leading-6 text-slate-600", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Interactive Foam Designer" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              ForwardRef$k,
              {
                className: "h-5 w-5 text-slate-400",
                "aria-hidden": "true"
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "mt-8 text-4xl font-extrabold tracking-tight text-slate-900 sm:text-5xl font-heading", children: [
          "The One Stop Shop for",
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600", children: "Premium Foam." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-base leading-7 text-slate-600 max-w-lg", children: "The UK's leading provider of quality, sustainable, and affordable foam. From bespoke furniture cushions to specialized acoustic solutions, we cut every piece with professional-grade precision." }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-8 flex flex-wrap items-center gap-x-6 gap-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "a",
            {
              href: "#recommended-products",
              className: "rounded-2xl bg-brand-dark px-6 py-3.5 text-sm font-bold text-white shadow-xl shadow-brand-dark/20 hover:bg-slate-800 transition-all hover:-translate-y-1 active:scale-95 flex items-center gap-2",
              children: [
                "Shop Collections",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "svg",
                  {
                    className: "w-4 h-4 translate-y-[1px]",
                    fill: "none",
                    viewBox: "0 0 24 24",
                    stroke: "currentColor",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "path",
                      {
                        strokeLinecap: "round",
                        strokeLinejoin: "round",
                        strokeWidth: 3,
                        d: "M14 5l7 7m0 0l-7 7m7-7H3"
                      }
                    )
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Link,
            {
              to: "/designer",
              className: "text-sm font-bold leading-6 text-slate-900 flex items-center gap-2 group transition-colors hover:text-primary-600",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-slate-100 rounded-xl group-hover:bg-primary-50 transition-colors", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ForwardRef$o, { className: "h-5 w-5 text-primary-600" }) }),
                "Start Designing"
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mx-auto mt-12 flex max-w-2xl sm:mt-16 lg:ml-10 lg:mr-0 lg:mt-0 lg:max-w-none lg:flex-none xl:ml-20", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-3xl flex-none sm:max-w-5xl lg:max-w-none", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative rounded-3xl overflow-hidden", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "img",
          {
            src: premiumHero,
            alt: "Premium Foam Furniture",
            className: "w-full max-w-[45rem] rounded-2xl lg:rounded-[2.5rem] object-contain"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 rounded-2xl lg:rounded-[2.5rem] bg-gradient-to-t from-black/60 via-black/20 to-transparent pointer-events-none" })
      ] }) }) })
    ] })
  ] });
}
const meta$1 = () => {
  return [{ title: "Hydrogen | Home" }];
};
async function loader$2({ context: context2 }) {
  const { storefront } = context2;
  const { collections } = await storefront.query(FEATURED_COLLECTION_QUERY);
  const featuredCollections = collections.nodes;
  const recommendedProducts = storefront.query(RECOMMENDED_PRODUCTS_QUERY);
  const offerProducts = storefront.query(OFFER_PRODUCTS_QUERY);
  return defer2({ featuredCollections, recommendedProducts, offerProducts });
}
function Homepage() {
  const data = useLoaderData();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "home", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Hero, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ProdRecommendations, { products: data.recommendedProducts }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CustomFoam, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Offers, { products: data.offerProducts }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(NewFeaturedCollection, { collections: data.featuredCollections }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Testimonials, {})
  ] });
}
function NewFeaturedCollection({
  collections
}) {
  var _a2, _b2, _c, _d, _e2, _f, _g;
  if (!collections || collections.length === 0) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "py-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-2xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl font-heading", children: [
          "Shop by ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600", children: "Category." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-lg text-slate-600", children: "Explore our specialized categories to find the exact foam product for your project." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: "/collections",
          className: "text-sm font-bold text-primary-600 hover:text-primary-700 flex items-center gap-2 group",
          children: [
            "Browse all categories",
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "svg",
              {
                className: "w-4 h-4 transition-transform group-hover:translate-x-1",
                fill: "none",
                viewBox: "0 0 24 24",
                stroke: "currentColor",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    strokeWidth: 2,
                    d: "M9 5l7 7-7 7"
                  }
                )
              }
            )
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-6 gap-6 h-[600px]", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: `/collections/${collections[0].handle}`,
          className: "md:col-span-3 md:row-span-2 group relative overflow-hidden rounded-[2.5rem] bg-slate-100 shadow-sm transition-all duration-500 hover:shadow-premium",
          children: [
            ((_a2 = collections[0]) == null ? void 0 : _a2.image) && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Image,
              {
                data: collections[0].image,
                sizes: "(min-width: 768px) 50vw, 100vw",
                className: "h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute inset-0 bg-gradient-to-t from-brand-dark/80 via-transparent to-transparent p-10 flex flex-col justify-end", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-3xl font-bold text-white mb-2", children: collections[0].title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white/70 font-medium", children: "Explore Collection →" })
            ] })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: `/collections/${(_b2 = collections[1]) == null ? void 0 : _b2.handle}`,
          className: "md:col-span-3 group relative overflow-hidden rounded-[2.5rem] bg-slate-100 shadow-sm transition-all duration-500 hover:shadow-premium",
          children: [
            ((_c = collections[1]) == null ? void 0 : _c.image) && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Image,
              {
                data: collections[1].image,
                sizes: "(min-width: 768px) 50vw, 100vw",
                className: "h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute inset-0 bg-gradient-to-t from-brand-dark/80 via-transparent to-transparent p-8 flex flex-col justify-end", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-white mb-2", children: (_d = collections[1]) == null ? void 0 : _d.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white/70 font-medium text-sm", children: "Explore Collection →" })
            ] })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: `/collections/${(_e2 = collections[2]) == null ? void 0 : _e2.handle}`,
          className: "md:col-span-3 group relative overflow-hidden rounded-[2.5rem] bg-slate-100 shadow-sm transition-all duration-500 hover:shadow-premium",
          children: [
            ((_f = collections[2]) == null ? void 0 : _f.image) && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Image,
              {
                data: collections[2].image,
                sizes: "(min-width: 768px) 50vw, 100vw",
                className: "h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute inset-0 bg-gradient-to-t from-brand-dark/80 via-transparent to-transparent p-8 flex flex-col justify-end", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-white mb-2", children: (_g = collections[2]) == null ? void 0 : _g.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white/70 font-medium text-sm", children: "Explore Collection →" })
            ] })
          ]
        }
      )
    ] })
  ] });
}
const Offers = ({ products }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "py-24", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center text-center mb-16 px-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center rounded-full bg-primary-50 px-4 py-1.5 text-sm font-bold text-primary-600 ring-1 ring-inset ring-primary-600/10 mb-4", children: "Limited Time Offers" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-3xl font-extrabold tracking-tight text-slate-900 sm:text-5xl font-heading", children: [
        "Great Savings with ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600", children: "Durafoam." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-lg text-slate-600 max-w-2xl", children: "Don't miss out on our special promotions for high-quality foam solutions and home essentials." })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      reactExports.Suspense,
      {
        fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid md:grid-cols-2 gap-8", children: [...Array(2)].map((_2, i2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "h-96 bg-slate-100 rounded-[2.5rem] animate-pulse"
          },
          i2
        )) }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: products, children: ({ products: products2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid md:grid-cols-2 gap-8", children: products2.nodes.map((product, i2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: "group relative overflow-hidden rounded-[2.5rem] shadow-xl transition-all duration-500 hover:shadow-2xl hover:-translate-y-1",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-[16/9] sm:aspect-square md:aspect-[16/9] overflow-hidden", children: product.images.nodes[0] ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                Image,
                {
                  data: product.images.nodes[0],
                  aspectRatio: "1/1",
                  sizes: "(min-width: 45em) 50vw, 100vw",
                  className: "w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                "img",
                {
                  src: placeholderImg,
                  alt: product.title,
                  className: "w-full h-full object-cover opacity-50 bg-slate-100"
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-gradient-to-t from-brand-dark/90 via-brand-dark/40 to-transparent p-8 flex flex-col justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "bg-primary-500 text-white text-[10px] font-black uppercase px-2 py-1 rounded", children: "Save Big" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-white", children: product.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-slate-400 line-through text-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.priceRange.minVariantPrice }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-2xl font-black text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.priceRange.minVariantPrice }) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Link,
                  {
                    to: `/products/${product.handle}`,
                    className: "inline-flex items-center justify-center rounded-2xl bg-white px-6 py-3 text-sm font-bold text-brand-dark hover:bg-slate-100 transition-colors",
                    children: "Shop now"
                  }
                )
              ] }) })
            ]
          },
          product.id
        )) }) })
      }
    )
  ] });
};
function CustomFoam() {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "relative overflow-hidden rounded-[3rem] bg-brand-dark px-6 py-20 sm:px-12 sm:py-32 lg:px-20 shadow-2xl my-16", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-0 right-0 -translate-y-1/4 translate-x-1/4 w-full h-full bg-primary-600/10 rounded-full blur-3xl pointer-events-none" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute bottom-0 left-0 translate-y-1/4 -translate-x-1/4 w-96 h-96 bg-blue-500/10 rounded-full blur-3xl pointer-events-none" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 grid lg:grid-cols-2 gap-12 items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-xl text-left", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center rounded-full bg-primary-500/10 px-4 py-1.5 text-sm font-bold text-primary-400 ring-1 ring-inset ring-primary-500/20 mb-6", children: "Foam Cut To Size" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-3xl font-extrabold tracking-tight text-white sm:text-5xl font-heading leading-tight italic", children: [
          "Foam. ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-400", children: "Your Way." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-6 text-lg text-slate-300 leading-relaxed", children: "Our interactive 3D designer allows you to configure custom foam shapes with millimeter precision. Choose your shape, enter your dimensions, and get an instant price quotation." }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-10 flex flex-col sm:flex-row gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Link,
            {
              to: "/designer",
              className: "inline-flex items-center justify-center rounded-2xl bg-white px-8 py-4 text-sm font-bold text-brand-dark shadow-xl hover:bg-slate-100 transition-all hover:-translate-y-1 active:scale-95 group",
              children: [
                "Launch 3D Designer",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "svg",
                  {
                    className: "ml-2 w-5 h-5 transition-transform group-hover:translate-x-1",
                    fill: "none",
                    viewBox: "0 0 24 24",
                    stroke: "currentColor",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "path",
                      {
                        strokeLinecap: "round",
                        strokeLinejoin: "round",
                        strokeWidth: 2,
                        d: "M13 10V3L4 14h7v7l9-11h-7z"
                      }
                    )
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Link,
            {
              to: "/collections",
              className: "inline-flex items-center justify-center rounded-2xl bg-white/10 backdrop-blur-md px-8 py-4 text-sm font-bold text-white border border-white/20 hover:bg-white/20 transition-all",
              children: "Browse Standard Shapes"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "hidden lg:block relative", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-video rounded-3xl bg-gradient-to-br from-primary-500/20 to-blue-600/30 border border-white/10 flex items-center justify-center backdrop-blur-sm shadow-inner overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-8 text-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-20 h-20 bg-white/10 rounded-2xl mx-auto mb-4 flex items-center justify-center animate-bounce duration-[3000ms]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "svg",
          {
            className: "w-10 h-10 text-white",
            fill: "none",
            viewBox: "0 0 24 24",
            stroke: "currentColor",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "path",
              {
                strokeLinecap: "round",
                strokeLinejoin: "round",
                strokeWidth: 1.5,
                d: "M21 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-5.25v9"
              }
            )
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white font-bold text-xl font-heading", children: "Interactive Preview" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-white/60 text-sm mt-2", children: "See your foam in 3D as you design" })
      ] }) }) })
    ] })
  ] });
}
function ProdRecommendations({
  products
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: "py-24", id: "recommended-products", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-2xl", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl font-heading", children: [
          "Our Most Popular",
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-primary-600", children: "Solutions." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-4 text-lg text-slate-600", children: "Handpicked foam products and accessories to help you achieve the perfect level of comfort and support." })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Link,
        {
          to: "/collections",
          className: "text-sm font-bold text-primary-600 hover:text-primary-700 flex items-center gap-2 group transition-all",
          children: [
            "View all collections",
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "svg",
              {
                className: "w-4 h-4 transition-transform group-hover:translate-x-1",
                fill: "none",
                viewBox: "0 0 24 24",
                stroke: "currentColor",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    strokeWidth: 2,
                    d: "M9 5l7 7-7 7"
                  }
                )
              }
            )
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      reactExports.Suspense,
      {
        fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 lg:grid-cols-4 gap-6", children: [...Array(4)].map((_2, i2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "aspect-square bg-slate-100 rounded-3xl animate-pulse"
          },
          i2
        )) }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Await, { resolve: products, children: ({ products: products2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8", children: products2.nodes.map((product) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Link,
          {
            className: "group",
            to: `/products/${product.handle}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative aspect-square overflow-hidden rounded-3xl bg-slate-100 shadow-sm border border-slate-100 group-hover:shadow-premium group-hover:border-primary-100 transition-all duration-500", children: [
                product.images.nodes[0] ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Image,
                  {
                    data: product.images.nodes[0],
                    aspectRatio: "1/1",
                    sizes: "(min-width: 45em) 25vw, 50vw",
                    className: "object-cover w-full h-full group-hover:scale-110 transition-transform duration-700 ease-out"
                  }
                ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "img",
                  {
                    src: placeholderImg,
                    alt: product.title,
                    className: "object-cover w-full h-full opacity-40 bg-slate-50"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-x-0 bottom-0 p-4 translate-y-2 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-500 bg-gradient-to-t from-white/90 to-transparent backdrop-blur-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "w-full py-3 bg-brand-dark text-white text-xs font-bold rounded-2xl shadow-lg", children: "View Details" }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-6 space-y-1 px-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-bold text-slate-900 group-hover:text-primary-600 transition-colors", children: product.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-slate-500", children: "Fast Shipping" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-lg font-extrabold text-blue-600", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Money, { data: product.priceRange.minVariantPrice }) })
                ] })
              ] })
            ]
          },
          product.id
        )) }) })
      }
    )
  ] });
}
const FEATURED_COLLECTION_QUERY = `#graphql
  fragment FeaturedCollection on Collection {
    id
    title
    image {
      id
      url
      altText
      width
      height
    }
    handle
  }
  query FeaturedCollection($country: CountryCode, $language: LanguageCode)
    @inContext(country: $country, language: $language) {
    collections(first: 3, sortKey: UPDATED_AT, reverse: true) {
      nodes {
        ...FeaturedCollection
      }
    }
  }
`;
const RECOMMENDED_PRODUCTS_QUERY = `#graphql
  fragment RecommendedProduct on Product {
    id
    title
    handle
    priceRange {
      minVariantPrice {
        amount
        currencyCode
      }
    }
    images(first: 2) {
      nodes {
        id
        url
        altText
        width
        height
      }
    }
  }
  query RecommendedProducts ($country: CountryCode, $language: LanguageCode)
    @inContext(country: $country, language: $language) {
    products(first: 8, sortKey: UPDATED_AT, reverse: true) {
      nodes {
        ...RecommendedProduct
      }
    }
  }
`;
const OFFER_PRODUCTS_QUERY = `#graphql
fragment OfferProduct on Product {
  id
  title
  handle
  priceRange {
    minVariantPrice {
      amount
      currencyCode
    }
    maxVariantPrice {
      amount
      currencyCode
    }
  }
  images(first: 1) {
    nodes {
      id
      url
      altText
      width
      height
    }
  }
}

query OfferProducts($country: CountryCode, $language: LanguageCode) @inContext(country: $country, language: $language) {
  products(first: 2, sortKey: UPDATED_AT, reverse: false) {
    nodes {
      ...OfferProduct
    }
  }
}
`;
const route30 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CustomFoam,
  ProdRecommendations,
  default: Homepage,
  loader: loader$2,
  meta: meta$1
}, Symbol.toStringTag, { value: "Module" }));
const meta = () => {
  return [{ title: `Hydrogen | Cart` }];
};
async function loader$1({ request, context: context2 }) {
  var _a2;
  const url = new URL(request.url);
  const variantId = url.searchParams.get("add");
  if (variantId) {
    const { cart, session } = context2;
    console.log("Adding variant to cart:", variantId);
    const result = await cart.addLines([
      {
        merchandiseId: variantId,
        quantity: 1
      }
    ]);
    console.log("Cart addLines result:", JSON.stringify(result, null, 2));
    if ((_a2 = result.errors) == null ? void 0 : _a2.length) {
      console.error("Cart errors:", result.errors);
    }
    const headers = cart.setCartId(result.cart.id);
    headers.append("Set-Cookie", await session.commit());
    await new Promise((resolve2) => setTimeout(resolve2, 1e3));
    return redirect2("/cart?cartOpen=false", { headers });
  }
  return json2({});
}
async function action({ request, context: context2 }) {
  const { cart } = context2;
  const formData = await request.formData();
  const { action: action2, inputs } = J$1.getFormInput(formData);
  if (!action2) {
    throw new Error("No action provided");
  }
  let status = 200;
  let result;
  switch (action2) {
    case J$1.ACTIONS.LinesAdd:
      result = await cart.addLines(inputs.lines);
      break;
    case J$1.ACTIONS.LinesUpdate:
      result = await cart.updateLines(inputs.lines);
      break;
    case J$1.ACTIONS.LinesRemove:
      result = await cart.removeLines(inputs.lineIds);
      break;
    case J$1.ACTIONS.DiscountCodesUpdate: {
      const formDiscountCode = inputs.discountCode;
      const discountCodes = formDiscountCode ? [formDiscountCode] : [];
      discountCodes.push(...inputs.discountCodes);
      result = await cart.updateDiscountCodes(discountCodes);
      break;
    }
    case J$1.ACTIONS.BuyerIdentityUpdate: {
      result = await cart.updateBuyerIdentity({
        ...inputs.buyerIdentity
      });
      break;
    }
    default:
      throw new Error(`${action2} cart action is not defined`);
  }
  const cartId = result.cart.id;
  const headers = cart.setCartId(result.cart.id);
  const { cart: cartResult, errors } = result;
  const redirectTo = formData.get("redirectTo") ?? null;
  if (typeof redirectTo === "string") {
    status = 303;
    headers.set("Location", redirectTo);
  }
  headers.append("Set-Cookie", await context2.session.commit());
  return json2(
    {
      cart: cartResult,
      errors,
      analytics: {
        cartId
      }
    },
    { status, headers }
  );
}
function Cart() {
  const rootData = useRootLoaderData();
  const cartPromise = rootData.cart;
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "cart", children: /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Loading cart ..." }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    Await,
    {
      resolve: cartPromise,
      errorElement: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "An error occurred" }),
      children: (cart) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(CartMain, { layout: "page", cart });
      }
    }
  ) }) });
}
const route31 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  action,
  default: Cart,
  loader: loader$1,
  meta
}, Symbol.toStringTag, { value: "Module" }));
async function loader({ request }) {
  throw new Response(`${new URL(request.url).pathname} not found`, {
    status: 404
  });
}
function CatchAllPage() {
  return null;
}
const route32 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CatchAllPage,
  loader
}, Symbol.toStringTag, { value: "Module" }));
const serverManifest = { "entry": { "module": "/assets/entry.client-CT2nKCkF.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/client-DzB3ZPxg.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": true, "module": "/assets/root-JWGO7UVn.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/client-DzB3ZPxg.js", "/assets/root-BkPj4fgY.js", "/assets/index-Bn9V8cCg.js", "/assets/PhoneIcon-mNGqpZ3p.js", "/assets/variants-C3Oc9-dg.js", "/assets/placeholder-CgrO-6By.js", "/assets/Money-CrBKsoq2.js", "/assets/Image-BWANSFFu.js", "/assets/focus-management-CC5qaTLR.js", "/assets/transition-D9BblioA.js", "/assets/description-DxJKQhHg.js"], "css": [] }, "routes/blogs.$blogHandle.$articleHandle": { "id": "routes/blogs.$blogHandle.$articleHandle", "parentId": "root", "path": "blogs/:blogHandle/:articleHandle", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/blogs._blogHandle._articleHandle-VsVI8zgc.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/Image-BWANSFFu.js"], "css": [] }, "routes/blogs.$blogHandle._index": { "id": "routes/blogs.$blogHandle._index", "parentId": "root", "path": "blogs/:blogHandle", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/blogs._blogHandle._index-CtKqEyWq.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/index-Bn9V8cCg.js", "/assets/Image-BWANSFFu.js"], "css": [] }, "routes/foam-cut-to-size.$shape": { "id": "routes/foam-cut-to-size.$shape", "parentId": "root", "path": "foam-cut-to-size/:shape", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/foam-cut-to-size._shape-C7KaVwTs.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/shape-configs-K6chYWdD.js", "/assets/bugs-ChsGtR2Y.js", "/assets/focus-management-CC5qaTLR.js", "/assets/description-DxJKQhHg.js"], "css": [] }, "routes/foam-cut-to-size._index": { "id": "routes/foam-cut-to-size._index", "parentId": "root", "path": "foam-cut-to-size", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/foam-cut-to-size._index-BYvnQeMY.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/ShapeIcons-57I6JQp9.js"], "css": [] }, "routes/api.create-custom-foam": { "id": "routes/api.create-custom-foam", "parentId": "root", "path": "api/create-custom-foam", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/api.create-custom-foam-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/account.orders._index": { "id": "routes/account.orders._index", "parentId": "routes/account", "path": "orders", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account.orders._index-DxBWrvNf.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/index-Bn9V8cCg.js", "/assets/Money-CrBKsoq2.js"], "css": [] }, "routes/api.predictive-search": { "id": "routes/api.predictive-search", "parentId": "root", "path": "api/predictive-search", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/api.predictive-search-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/collections.$handle": { "id": "routes/collections.$handle", "parentId": "root", "path": "collections/:handle", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/collections._handle-DZwpS3Uh.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/index-Bn9V8cCg.js", "/assets/variants-C3Oc9-dg.js", "/assets/placeholder-CgrO-6By.js", "/assets/Image-BWANSFFu.js", "/assets/Money-CrBKsoq2.js"], "css": [] }, "routes/account.orders.$id": { "id": "routes/account.orders.$id", "parentId": "routes/account", "path": "orders/:id", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account.orders._id-WodGb9-1.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/Money-CrBKsoq2.js", "/assets/Image-BWANSFFu.js"], "css": [] }, "routes/account_.authorize": { "id": "routes/account_.authorize", "parentId": "root", "path": "account/authorize", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account_.authorize-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/collections._index": { "id": "routes/collections._index", "parentId": "root", "path": "collections", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/collections._index-Cd6lNsfo.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/index-Bn9V8cCg.js", "/assets/placeholder-CgrO-6By.js", "/assets/Image-BWANSFFu.js"], "css": [] }, "routes/account.addresses": { "id": "routes/account.addresses", "parentId": "routes/account", "path": "addresses", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account.addresses-B4pRDP2q.js", "imports": ["/assets/components-tSF29mDa.js"], "css": [] }, "routes/policies.$handle": { "id": "routes/policies.$handle", "parentId": "root", "path": "policies/:handle", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/policies._handle-BShZ216W.js", "imports": ["/assets/components-tSF29mDa.js"], "css": [] }, "routes/products.$handle": { "id": "routes/products.$handle", "parentId": "root", "path": "products/:handle", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/products._handle-DE328sw-.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/transition-D9BblioA.js", "/assets/index-Bn9V8cCg.js", "/assets/Image-BWANSFFu.js", "/assets/placeholder-CgrO-6By.js", "/assets/bugs-ChsGtR2Y.js", "/assets/focus-management-CC5qaTLR.js", "/assets/Money-CrBKsoq2.js"], "css": [] }, "routes/account.profile": { "id": "routes/account.profile", "parentId": "routes/account", "path": "profile", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account.profile-B2sMmEc-.js", "imports": ["/assets/components-tSF29mDa.js"], "css": [] }, "routes/account_.logout": { "id": "routes/account_.logout", "parentId": "root", "path": "account/logout", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account_.logout-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/policies._index": { "id": "routes/policies._index", "parentId": "root", "path": "policies", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/policies._index-CJB23A6g.js", "imports": ["/assets/components-tSF29mDa.js"], "css": [] }, "routes/account._index": { "id": "routes/account._index", "parentId": "routes/account", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account._index-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/account_.login": { "id": "routes/account_.login", "parentId": "root", "path": "account/login", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account_.login-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/discount.$code": { "id": "routes/discount.$code", "parentId": "root", "path": "discount/:code", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/discount._code-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/pages.$handle": { "id": "routes/pages.$handle", "parentId": "root", "path": "pages/:handle", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/pages._handle-TLF67ZdQ.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/PhoneIcon-mNGqpZ3p.js"], "css": [] }, "routes/[sitemap.xml]": { "id": "routes/[sitemap.xml]", "parentId": "root", "path": "sitemap.xml", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/_sitemap.xml_-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/blogs._index": { "id": "routes/blogs._index", "parentId": "root", "path": "blogs", "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/blogs._index-DvDY4thl.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/index-Bn9V8cCg.js"], "css": [] }, "routes/[robots.txt]": { "id": "routes/[robots.txt]", "parentId": "root", "path": "robots.txt", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/_robots.txt_-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/cart.$lines": { "id": "routes/cart.$lines", "parentId": "routes/cart", "path": ":lines", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/cart._lines-C6d-v1ok.js", "imports": [], "css": [] }, "routes/account.$": { "id": "routes/account.$", "parentId": "routes/account", "path": "*", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account._-l0sNRNKZ.js", "imports": [], "css": [] }, "routes/designer": { "id": "routes/designer", "parentId": "root", "path": "designer", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/designer-C59AOci0.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/shape-configs-K6chYWdD.js", "/assets/ShapeIcons-57I6JQp9.js", "/assets/client-DzB3ZPxg.js", "/assets/bugs-ChsGtR2Y.js", "/assets/focus-management-CC5qaTLR.js", "/assets/description-DxJKQhHg.js"], "css": [] }, "routes/account": { "id": "routes/account", "parentId": "root", "path": "account", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/account-BWLbA0cL.js", "imports": ["/assets/components-tSF29mDa.js"], "css": [] }, "routes/search": { "id": "routes/search", "parentId": "root", "path": "search", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/search-Cd94GH2d.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/Image-BWANSFFu.js", "/assets/Money-CrBKsoq2.js"], "css": [] }, "routes/_index": { "id": "routes/_index", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/_index-K8RyLBjx.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/placeholder-CgrO-6By.js", "/assets/Image-BWANSFFu.js", "/assets/Money-CrBKsoq2.js"], "css": [] }, "routes/cart": { "id": "routes/cart", "parentId": "root", "path": "cart", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/cart-BDRFHGky.js", "imports": ["/assets/components-tSF29mDa.js", "/assets/root-BkPj4fgY.js", "/assets/index-Bn9V8cCg.js", "/assets/PhoneIcon-mNGqpZ3p.js", "/assets/variants-C3Oc9-dg.js", "/assets/placeholder-CgrO-6By.js", "/assets/Money-CrBKsoq2.js", "/assets/Image-BWANSFFu.js", "/assets/focus-management-CC5qaTLR.js", "/assets/transition-D9BblioA.js", "/assets/description-DxJKQhHg.js"], "css": [] }, "routes/$": { "id": "routes/$", "parentId": "root", "path": "*", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/_-DtCUJE-g.js", "imports": [], "css": [] } }, "url": "/assets/manifest-2a17e39c.js", "version": "2a17e39c" };
const mode = "production";
const assetsBuildDirectory = "build\\client";
const basename = "/";
const future = { "v3_fetcherPersist": false, "v3_relativeSplatPath": false, "v3_throwAbortReason": false, "v3_routeConfig": false, "v3_singleFetch": false, "v3_lazyRouteDiscovery": false, "unstable_optimizeDeps": false };
const isSpaMode = false;
const publicPath = "/";
const entry = { module: entryServer };
const routes = {
  "root": {
    id: "root",
    parentId: void 0,
    path: "",
    index: void 0,
    caseSensitive: void 0,
    module: route0
  },
  "routes/blogs.$blogHandle.$articleHandle": {
    id: "routes/blogs.$blogHandle.$articleHandle",
    parentId: "root",
    path: "blogs/:blogHandle/:articleHandle",
    index: void 0,
    caseSensitive: void 0,
    module: route1
  },
  "routes/blogs.$blogHandle._index": {
    id: "routes/blogs.$blogHandle._index",
    parentId: "root",
    path: "blogs/:blogHandle",
    index: true,
    caseSensitive: void 0,
    module: route2
  },
  "routes/foam-cut-to-size.$shape": {
    id: "routes/foam-cut-to-size.$shape",
    parentId: "root",
    path: "foam-cut-to-size/:shape",
    index: void 0,
    caseSensitive: void 0,
    module: route3
  },
  "routes/foam-cut-to-size._index": {
    id: "routes/foam-cut-to-size._index",
    parentId: "root",
    path: "foam-cut-to-size",
    index: true,
    caseSensitive: void 0,
    module: route4
  },
  "routes/api.create-custom-foam": {
    id: "routes/api.create-custom-foam",
    parentId: "root",
    path: "api/create-custom-foam",
    index: void 0,
    caseSensitive: void 0,
    module: route5
  },
  "routes/account.orders._index": {
    id: "routes/account.orders._index",
    parentId: "routes/account",
    path: "orders",
    index: true,
    caseSensitive: void 0,
    module: route6
  },
  "routes/api.predictive-search": {
    id: "routes/api.predictive-search",
    parentId: "root",
    path: "api/predictive-search",
    index: void 0,
    caseSensitive: void 0,
    module: route7
  },
  "routes/collections.$handle": {
    id: "routes/collections.$handle",
    parentId: "root",
    path: "collections/:handle",
    index: void 0,
    caseSensitive: void 0,
    module: route8
  },
  "routes/account.orders.$id": {
    id: "routes/account.orders.$id",
    parentId: "routes/account",
    path: "orders/:id",
    index: void 0,
    caseSensitive: void 0,
    module: route9
  },
  "routes/account_.authorize": {
    id: "routes/account_.authorize",
    parentId: "root",
    path: "account/authorize",
    index: void 0,
    caseSensitive: void 0,
    module: route10
  },
  "routes/collections._index": {
    id: "routes/collections._index",
    parentId: "root",
    path: "collections",
    index: true,
    caseSensitive: void 0,
    module: route11
  },
  "routes/account.addresses": {
    id: "routes/account.addresses",
    parentId: "routes/account",
    path: "addresses",
    index: void 0,
    caseSensitive: void 0,
    module: route12
  },
  "routes/policies.$handle": {
    id: "routes/policies.$handle",
    parentId: "root",
    path: "policies/:handle",
    index: void 0,
    caseSensitive: void 0,
    module: route13
  },
  "routes/products.$handle": {
    id: "routes/products.$handle",
    parentId: "root",
    path: "products/:handle",
    index: void 0,
    caseSensitive: void 0,
    module: route14
  },
  "routes/account.profile": {
    id: "routes/account.profile",
    parentId: "routes/account",
    path: "profile",
    index: void 0,
    caseSensitive: void 0,
    module: route15
  },
  "routes/account_.logout": {
    id: "routes/account_.logout",
    parentId: "root",
    path: "account/logout",
    index: void 0,
    caseSensitive: void 0,
    module: route16
  },
  "routes/policies._index": {
    id: "routes/policies._index",
    parentId: "root",
    path: "policies",
    index: true,
    caseSensitive: void 0,
    module: route17
  },
  "routes/account._index": {
    id: "routes/account._index",
    parentId: "routes/account",
    path: void 0,
    index: true,
    caseSensitive: void 0,
    module: route18
  },
  "routes/account_.login": {
    id: "routes/account_.login",
    parentId: "root",
    path: "account/login",
    index: void 0,
    caseSensitive: void 0,
    module: route19
  },
  "routes/discount.$code": {
    id: "routes/discount.$code",
    parentId: "root",
    path: "discount/:code",
    index: void 0,
    caseSensitive: void 0,
    module: route20
  },
  "routes/pages.$handle": {
    id: "routes/pages.$handle",
    parentId: "root",
    path: "pages/:handle",
    index: void 0,
    caseSensitive: void 0,
    module: route21
  },
  "routes/[sitemap.xml]": {
    id: "routes/[sitemap.xml]",
    parentId: "root",
    path: "sitemap.xml",
    index: void 0,
    caseSensitive: void 0,
    module: route22
  },
  "routes/blogs._index": {
    id: "routes/blogs._index",
    parentId: "root",
    path: "blogs",
    index: true,
    caseSensitive: void 0,
    module: route23
  },
  "routes/[robots.txt]": {
    id: "routes/[robots.txt]",
    parentId: "root",
    path: "robots.txt",
    index: void 0,
    caseSensitive: void 0,
    module: route24
  },
  "routes/cart.$lines": {
    id: "routes/cart.$lines",
    parentId: "routes/cart",
    path: ":lines",
    index: void 0,
    caseSensitive: void 0,
    module: route25
  },
  "routes/account.$": {
    id: "routes/account.$",
    parentId: "routes/account",
    path: "*",
    index: void 0,
    caseSensitive: void 0,
    module: route26
  },
  "routes/designer": {
    id: "routes/designer",
    parentId: "root",
    path: "designer",
    index: void 0,
    caseSensitive: void 0,
    module: route27
  },
  "routes/account": {
    id: "routes/account",
    parentId: "root",
    path: "account",
    index: void 0,
    caseSensitive: void 0,
    module: route28
  },
  "routes/search": {
    id: "routes/search",
    parentId: "root",
    path: "search",
    index: void 0,
    caseSensitive: void 0,
    module: route29
  },
  "routes/_index": {
    id: "routes/_index",
    parentId: "root",
    path: void 0,
    index: true,
    caseSensitive: void 0,
    module: route30
  },
  "routes/cart": {
    id: "routes/cart",
    parentId: "root",
    path: "cart",
    index: void 0,
    caseSensitive: void 0,
    module: route31
  },
  "routes/$": {
    id: "routes/$",
    parentId: "root",
    path: "*",
    index: void 0,
    caseSensitive: void 0,
    module: route32
  }
};
const remixBuild = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  assets: serverManifest,
  assetsBuildDirectory,
  basename,
  entry,
  future,
  isSpaMode,
  mode,
  publicPath,
  routes
}, Symbol.toStringTag, { value: "Module" }));
class AppSession {
  constructor(sessionStorage2, session) {
    __privateAdd(this, _sessionStorage);
    __privateAdd(this, _session);
    __privateSet(this, _sessionStorage, sessionStorage2);
    __privateSet(this, _session, session);
  }
  static async init(request, secrets) {
    const storage = b$4({
      cookie: {
        name: "session",
        httpOnly: true,
        path: "/",
        sameSite: "lax",
        secrets
      }
    });
    const session = await storage.getSession(request.headers.get("Cookie")).catch(() => storage.getSession());
    return new this(storage, session);
  }
  get has() {
    return __privateGet(this, _session).has;
  }
  get get() {
    return __privateGet(this, _session).get;
  }
  get flash() {
    return __privateGet(this, _session).flash;
  }
  get unset() {
    return __privateGet(this, _session).unset;
  }
  get set() {
    return __privateGet(this, _session).set;
  }
  destroy() {
    return __privateGet(this, _sessionStorage).destroySession(__privateGet(this, _session));
  }
  commit() {
    return __privateGet(this, _sessionStorage).commitSession(__privateGet(this, _session));
  }
}
_sessionStorage = new WeakMap();
_session = new WeakMap();
const CART_QUERY_FRAGMENT = `#graphql
  fragment Money on MoneyV2 {
    currencyCode
    amount
  }
  fragment CartLine on CartLine {
    id
    quantity
    attributes {
      key
      value
    }
    cost {
      totalAmount {
        ...Money
      }
      amountPerQuantity {
        ...Money
      }
      compareAtAmountPerQuantity {
        ...Money
      }
    }
    merchandise {
      ... on ProductVariant {
        id
        availableForSale
        compareAtPrice {
          ...Money
        }
        price {
          ...Money
        }
        requiresShipping
        title
        image {
          id
          url
          altText
          width
          height

        }
        product {
          handle
          title
          id
        }
        selectedOptions {
          name
          value
        }
      }
    }
  }
  fragment CartApiQuery on Cart {
    id
    checkoutUrl
    totalQuantity
    buyerIdentity {
      countryCode
      customer {
        id
        email
        firstName
        lastName
        displayName
      }
      email
      phone
    }
    lines(first: $numCartLines) {
      nodes {
        ...CartLine
      }
    }
    cost {
      subtotalAmount {
        ...Money
      }
      totalAmount {
        ...Money
      }
      totalDutyAmount {
        ...Money
      }
      totalTaxAmount {
        ...Money
      }
    }
    note
    attributes {
      key
      value
    }
    discountCodes {
      code
      applicable
    }
  }
`;
var define_process_env_default = {};
const server = {
  async fetch(request, env, executionContext) {
    try {
      const buildEnv = {
        ...typeof process !== "undefined" ? define_process_env_default : {},
        ...env || {}
      };
      if (!(buildEnv == null ? void 0 : buildEnv.SESSION_SECRET)) {
        throw new Error(
          "SESSION_SECRET environment variable is not set. Please set it in your environment variables."
        );
      }
      const waitUntil = executionContext.waitUntil.bind(executionContext);
      const [cache, session] = await Promise.all([
        caches.open("hydrogen"),
        AppSession.init(request, [buildEnv.SESSION_SECRET])
      ]);
      const { storefront } = Er({
        cache,
        waitUntil,
        i18n: { language: "EN", country: "US" },
        publicStorefrontToken: buildEnv.PUBLIC_STOREFRONT_API_TOKEN,
        privateStorefrontToken: buildEnv.PRIVATE_STOREFRONT_API_TOKEN,
        storeDomain: buildEnv.PUBLIC_STORE_DOMAIN,
        storefrontId: buildEnv.PUBLIC_STOREFRONT_ID,
        storefrontHeaders: I$6(request)
      });
      const customerAccount = Vt({
        waitUntil,
        request,
        session,
        customerAccountId: buildEnv.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID,
        customerAccountUrl: buildEnv.PUBLIC_CUSTOMER_ACCOUNT_API_URL
      });
      const cart = Zt({
        storefront,
        customerAccount,
        getCartId: Jt(request.headers),
        setCartId: Xt(),
        cartQueryFragment: CART_QUERY_FRAGMENT
      });
      const handleRequest2 = _$4({
        build: remixBuild,
        mode: "production",
        getLoadContext: () => ({
          session,
          storefront,
          customerAccount,
          cart,
          env: buildEnv,
          waitUntil
        })
      });
      const response = await handleRequest2(request);
      if (response.status === 404) {
        return zo({ request, response, storefront });
      }
      return response;
    } catch (error2) {
      console.error(error2);
      return new Response("An unexpected error occurred", { status: 500 });
    }
  }
};
function s({ headTags: n2 }) {
  return a2(n2), null;
}
var c = "text-transform: uppercase;", l = "text-transform: uppercase; font-weight: bold; text-transform: uppercase;font-weight: bold";
function a2(n2) {
  console.log(" "), console.log("%cSEO Meta Tags", `${l}`), console.log(" "), n2.forEach((e2) => {
    if (e2.tag === "script") {
      if (console.log("%c• JSON LD ", c), e2.children) try {
        console.table(JSON.parse(e2.children), ["name", "content"]);
      } catch {
        console.log(e2.children);
      }
    } else {
      if (console.log(`%c• ${e2.tag} `, c), e2.children) if (typeof e2.children == "string") console.log(`↳ ${e2.children}`);
      else try {
        Object.entries(JSON.parse(e2.children)).map(([t2, o4]) => console.log(`↳ ${o4}`));
      } catch {
        console.log(e2.children);
      }
      if (e2.props.property === "og:image:url") {
        let t2 = e2.props.content;
        i(t2).then((o4) => {
          let r2 = `font-size: 400px; padding: 10px; background: white url(${o4}) no-repeat center; background-size: contain;`;
          console.log("%c• Share image preview", c), console.log("%c  ", r2), console.log(`↳ ${t2}`);
        }).catch((o4) => {
          console.error(o4);
        });
      }
      Object.entries(e2.props).map(([t2, o4]) => {
        console.log(`↳ ${t2} → ${o4}`);
      });
    }
    console.log(" ");
  });
}
async function i(n2) {
  let o4 = await (await (await fetch(n2)).blob()).arrayBuffer();
  return `data:image/png;base64,${g(o4)}`;
}
function g(n2) {
  let e2 = "", t2 = new Uint8Array(n2), o4 = t2.byteLength;
  for (let r2 = 0; r2 < o4; r2++) e2 += String.fromCharCode(t2[r2]);
  return btoa(e2);
}
const logSeoTagsTY72EQWZ = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: s,
  logSeoTags: a2
}, Symbol.toStringTag, { value: "Module" }));
export {
  server as default
};
