var Kt, F, Io, ut, Mr, Lo, $o, Po, hr, Jn, Zn, Fo, qt = {}, Oo = [], ts = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, Wt = Array.isArray;
function ze(e, t) {
  for (var n in t) e[n] = t[n];
  return e;
}
function gr(e) {
  e && e.parentNode && e.parentNode.removeChild(e);
}
function We(e, t, n) {
  var r, o, i, s = {};
  for (i in t) i == "key" ? r = t[i] : i == "ref" ? o = t[i] : s[i] = t[i];
  if (arguments.length > 2 && (s.children = arguments.length > 3 ? Kt.call(arguments, 2) : n), typeof e == "function" && e.defaultProps != null) for (i in e.defaultProps) s[i] === void 0 && (s[i] = e.defaultProps[i]);
  return Ot(e, s, r, o, null);
}
function Ot(e, t, n, r, o) {
  var i = { type: e, props: t, key: n, ref: r, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: o ?? ++Io, __i: -1, __u: 0 };
  return o == null && F.vnode != null && F.vnode(i), i;
}
function ns() {
  return { current: null };
}
function Xe(e) {
  return e.children;
}
function Be(e, t) {
  this.props = e, this.context = t;
}
function bt(e, t) {
  if (t == null) return e.__ ? bt(e.__, e.__i + 1) : null;
  for (var n; t < e.__k.length; t++) if ((n = e.__k[t]) != null && n.__e != null) return n.__e;
  return typeof e.type == "function" ? bt(e) : null;
}
function Uo(e) {
  var t, n;
  if ((e = e.__) != null && e.__c != null) {
    for (e.__e = e.__c.base = null, t = 0; t < e.__k.length; t++) if ((n = e.__k[t]) != null && n.__e != null) {
      e.__e = e.__c.base = n.__e;
      break;
    }
    return Uo(e);
  }
}
function er(e) {
  (!e.__d && (e.__d = !0) && ut.push(e) && !gn.__r++ || Mr != F.debounceRendering) && ((Mr = F.debounceRendering) || Lo)(gn);
}
function gn() {
  for (var e, t, n, r, o, i, s, a = 1; ut.length; ) ut.length > a && ut.sort($o), e = ut.shift(), a = ut.length, e.__d && (n = void 0, r = void 0, o = (r = (t = e).__v).__e, i = [], s = [], t.__P && ((n = ze({}, r)).__v = r.__v + 1, F.vnode && F.vnode(n), mr(t.__P, n, r, t.__n, t.__P.namespaceURI, 32 & r.__u ? [o] : null, i, o ?? bt(r), !!(32 & r.__u), s), n.__v = r.__v, n.__.__k[n.__i] = n, qo(i, n, s), r.__e = r.__ = null, n.__e != o && Uo(n)));
  gn.__r = 0;
}
function zo(e, t, n, r, o, i, s, a, c, l, d) {
  var u, h, f, g, _, m, E, w = r && r.__k || Oo, y = t.length;
  for (c = rs(n, t, w, c, y), u = 0; u < y; u++) (f = n.__k[u]) != null && (h = f.__i == -1 ? qt : w[f.__i] || qt, f.__i = u, m = mr(e, f, h, o, i, s, a, c, l, d), g = f.__e, f.ref && h.ref != f.ref && (h.ref && _r(h.ref, null, f), d.push(f.ref, f.__c || g, f)), _ == null && g != null && (_ = g), (E = !!(4 & f.__u)) || h.__k === f.__k ? c = Bo(f, c, e, E) : typeof f.type == "function" && m !== void 0 ? c = m : g && (c = g.nextSibling), f.__u &= -7);
  return n.__e = _, c;
}
function rs(e, t, n, r, o) {
  var i, s, a, c, l, d = n.length, u = d, h = 0;
  for (e.__k = new Array(o), i = 0; i < o; i++) (s = t[i]) != null && typeof s != "boolean" && typeof s != "function" ? (c = i + h, (s = e.__k[i] = typeof s == "string" || typeof s == "number" || typeof s == "bigint" || s.constructor == String ? Ot(null, s, null, null, null) : Wt(s) ? Ot(Xe, { children: s }, null, null, null) : s.constructor == null && s.__b > 0 ? Ot(s.type, s.props, s.key, s.ref ? s.ref : null, s.__v) : s).__ = e, s.__b = e.__b + 1, a = null, (l = s.__i = os(s, n, c, u)) != -1 && (u--, (a = n[l]) && (a.__u |= 2)), a == null || a.__v == null ? (l == -1 && (o > d ? h-- : o < d && h++), typeof s.type != "function" && (s.__u |= 4)) : l != c && (l == c - 1 ? h-- : l == c + 1 ? h++ : (l > c ? h-- : h++, s.__u |= 4))) : e.__k[i] = null;
  if (u) for (i = 0; i < d; i++) (a = n[i]) != null && (2 & a.__u) == 0 && (a.__e == r && (r = bt(a)), Qo(a, a));
  return r;
}
function Bo(e, t, n, r) {
  var o, i;
  if (typeof e.type == "function") {
    for (o = e.__k, i = 0; o && i < o.length; i++) o[i] && (o[i].__ = e, t = Bo(o[i], t, n, r));
    return t;
  }
  e.__e != t && (r && (t && e.type && !t.parentNode && (t = bt(e)), n.insertBefore(e.__e, t || null)), t = e.__e);
  do
    t = t && t.nextSibling;
  while (t != null && t.nodeType == 8);
  return t;
}
function Ke(e, t) {
  return t = t || [], e == null || typeof e == "boolean" || (Wt(e) ? e.some(function(n) {
    Ke(n, t);
  }) : t.push(e)), t;
}
function os(e, t, n, r) {
  var o, i, s, a = e.key, c = e.type, l = t[n], d = l != null && (2 & l.__u) == 0;
  if (l === null && e.key == null || d && a == l.key && c == l.type) return n;
  if (r > (d ? 1 : 0)) {
    for (o = n - 1, i = n + 1; o >= 0 || i < t.length; ) if ((l = t[s = o >= 0 ? o-- : i++]) != null && (2 & l.__u) == 0 && a == l.key && c == l.type) return s;
  }
  return -1;
}
function Ir(e, t, n) {
  t[0] == "-" ? e.setProperty(t, n ?? "") : e[t] = n == null ? "" : typeof n != "number" || ts.test(t) ? n : n + "px";
}
function on(e, t, n, r, o) {
  var i, s;
  e: if (t == "style") if (typeof n == "string") e.style.cssText = n;
  else {
    if (typeof r == "string" && (e.style.cssText = r = ""), r) for (t in r) n && t in n || Ir(e.style, t, "");
    if (n) for (t in n) r && n[t] == r[t] || Ir(e.style, t, n[t]);
  }
  else if (t[0] == "o" && t[1] == "n") i = t != (t = t.replace(Po, "$1")), s = t.toLowerCase(), t = s in e || t == "onFocusOut" || t == "onFocusIn" ? s.slice(2) : t.slice(2), e.l || (e.l = {}), e.l[t + i] = n, n ? r ? n.u = r.u : (n.u = hr, e.addEventListener(t, i ? Zn : Jn, i)) : e.removeEventListener(t, i ? Zn : Jn, i);
  else {
    if (o == "http://www.w3.org/2000/svg") t = t.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
    else if (t != "width" && t != "height" && t != "href" && t != "list" && t != "form" && t != "tabIndex" && t != "download" && t != "rowSpan" && t != "colSpan" && t != "role" && t != "popover" && t in e) try {
      e[t] = n ?? "";
      break e;
    } catch {
    }
    typeof n == "function" || (n == null || n === !1 && t[4] != "-" ? e.removeAttribute(t) : e.setAttribute(t, t == "popover" && n == 1 ? "" : n));
  }
}
function Lr(e) {
  return function(t) {
    if (this.l) {
      var n = this.l[t.type + e];
      if (t.t == null) t.t = hr++;
      else if (t.t < n.u) return;
      return n(F.event ? F.event(t) : t);
    }
  };
}
function mr(e, t, n, r, o, i, s, a, c, l) {
  var d, u, h, f, g, _, m, E, w, y, R, x, C, A, D, I, B, $ = t.type;
  if (t.constructor != null) return null;
  128 & n.__u && (c = !!(32 & n.__u), i = [a = t.__e = n.__e]), (d = F.__b) && d(t);
  e: if (typeof $ == "function") try {
    if (E = t.props, w = "prototype" in $ && $.prototype.render, y = (d = $.contextType) && r[d.__c], R = d ? y ? y.props.value : d.__ : r, n.__c ? m = (u = t.__c = n.__c).__ = u.__E : (w ? t.__c = u = new $(E, R) : (t.__c = u = new Be(E, R), u.constructor = $, u.render = ss), y && y.sub(u), u.props = E, u.state || (u.state = {}), u.context = R, u.__n = r, h = u.__d = !0, u.__h = [], u._sb = []), w && u.__s == null && (u.__s = u.state), w && $.getDerivedStateFromProps != null && (u.__s == u.state && (u.__s = ze({}, u.__s)), ze(u.__s, $.getDerivedStateFromProps(E, u.__s))), f = u.props, g = u.state, u.__v = t, h) w && $.getDerivedStateFromProps == null && u.componentWillMount != null && u.componentWillMount(), w && u.componentDidMount != null && u.__h.push(u.componentDidMount);
    else {
      if (w && $.getDerivedStateFromProps == null && E !== f && u.componentWillReceiveProps != null && u.componentWillReceiveProps(E, R), !u.__e && u.shouldComponentUpdate != null && u.shouldComponentUpdate(E, u.__s, R) === !1 || t.__v == n.__v) {
        for (t.__v != n.__v && (u.props = E, u.state = u.__s, u.__d = !1), t.__e = n.__e, t.__k = n.__k, t.__k.some(function(G) {
          G && (G.__ = t);
        }), x = 0; x < u._sb.length; x++) u.__h.push(u._sb[x]);
        u._sb = [], u.__h.length && s.push(u);
        break e;
      }
      u.componentWillUpdate != null && u.componentWillUpdate(E, u.__s, R), w && u.componentDidUpdate != null && u.__h.push(function() {
        u.componentDidUpdate(f, g, _);
      });
    }
    if (u.context = R, u.props = E, u.__P = e, u.__e = !1, C = F.__r, A = 0, w) {
      for (u.state = u.__s, u.__d = !1, C && C(t), d = u.render(u.props, u.state, u.context), D = 0; D < u._sb.length; D++) u.__h.push(u._sb[D]);
      u._sb = [];
    } else do
      u.__d = !1, C && C(t), d = u.render(u.props, u.state, u.context), u.state = u.__s;
    while (u.__d && ++A < 25);
    u.state = u.__s, u.getChildContext != null && (r = ze(ze({}, r), u.getChildContext())), w && !h && u.getSnapshotBeforeUpdate != null && (_ = u.getSnapshotBeforeUpdate(f, g)), I = d, d != null && d.type === Xe && d.key == null && (I = Ho(d.props.children)), a = zo(e, Wt(I) ? I : [I], t, n, r, o, i, s, a, c, l), u.base = t.__e, t.__u &= -161, u.__h.length && s.push(u), m && (u.__E = u.__ = null);
  } catch (G) {
    if (t.__v = null, c || i != null) if (G.then) {
      for (t.__u |= c ? 160 : 128; a && a.nodeType == 8 && a.nextSibling; ) a = a.nextSibling;
      i[i.indexOf(a)] = null, t.__e = a;
    } else {
      for (B = i.length; B--; ) gr(i[B]);
      tr(t);
    }
    else t.__e = n.__e, t.__k = n.__k, G.then || tr(t);
    F.__e(G, t, n);
  }
  else i == null && t.__v == n.__v ? (t.__k = n.__k, t.__e = n.__e) : a = t.__e = is(n.__e, t, n, r, o, i, s, c, l);
  return (d = F.diffed) && d(t), 128 & t.__u ? void 0 : a;
}
function tr(e) {
  e && e.__c && (e.__c.__e = !0), e && e.__k && e.__k.forEach(tr);
}
function qo(e, t, n) {
  for (var r = 0; r < n.length; r++) _r(n[r], n[++r], n[++r]);
  F.__c && F.__c(t, e), e.some(function(o) {
    try {
      e = o.__h, o.__h = [], e.some(function(i) {
        i.call(o);
      });
    } catch (i) {
      F.__e(i, o.__v);
    }
  });
}
function Ho(e) {
  return typeof e != "object" || e == null || e.__b && e.__b > 0 ? e : Wt(e) ? e.map(Ho) : ze({}, e);
}
function is(e, t, n, r, o, i, s, a, c) {
  var l, d, u, h, f, g, _, m = n.props, E = t.props, w = t.type;
  if (w == "svg" ? o = "http://www.w3.org/2000/svg" : w == "math" ? o = "http://www.w3.org/1998/Math/MathML" : o || (o = "http://www.w3.org/1999/xhtml"), i != null) {
    for (l = 0; l < i.length; l++) if ((f = i[l]) && "setAttribute" in f == !!w && (w ? f.localName == w : f.nodeType == 3)) {
      e = f, i[l] = null;
      break;
    }
  }
  if (e == null) {
    if (w == null) return document.createTextNode(E);
    e = document.createElementNS(o, w, E.is && E), a && (F.__m && F.__m(t, i), a = !1), i = null;
  }
  if (w == null) m === E || a && e.data == E || (e.data = E);
  else {
    if (i = i && Kt.call(e.childNodes), m = n.props || qt, !a && i != null) for (m = {}, l = 0; l < e.attributes.length; l++) m[(f = e.attributes[l]).name] = f.value;
    for (l in m) if (f = m[l], l != "children") {
      if (l == "dangerouslySetInnerHTML") u = f;
      else if (!(l in E)) {
        if (l == "value" && "defaultValue" in E || l == "checked" && "defaultChecked" in E) continue;
        on(e, l, null, f, o);
      }
    }
    for (l in E) f = E[l], l == "children" ? h = f : l == "dangerouslySetInnerHTML" ? d = f : l == "value" ? g = f : l == "checked" ? _ = f : a && typeof f != "function" || m[l] === f || on(e, l, f, m[l], o);
    if (d) a || u && (d.__html == u.__html || d.__html == e.innerHTML) || (e.innerHTML = d.__html), t.__k = [];
    else if (u && (e.innerHTML = ""), zo(t.type == "template" ? e.content : e, Wt(h) ? h : [h], t, n, r, w == "foreignObject" ? "http://www.w3.org/1999/xhtml" : o, i, s, i ? i[0] : n.__k && bt(n, 0), a, c), i != null) for (l = i.length; l--; ) gr(i[l]);
    a || (l = "value", w == "progress" && g == null ? e.removeAttribute("value") : g != null && (g !== e[l] || w == "progress" && !g || w == "option" && g != m[l]) && on(e, l, g, m[l], o), l = "checked", _ != null && _ != e[l] && on(e, l, _, m[l], o));
  }
  return e;
}
function _r(e, t, n) {
  try {
    if (typeof e == "function") {
      var r = typeof e.__u == "function";
      r && e.__u(), r && t == null || (e.__u = e(t));
    } else e.current = t;
  } catch (o) {
    F.__e(o, n);
  }
}
function Qo(e, t, n) {
  var r, o;
  if (F.unmount && F.unmount(e), (r = e.ref) && (r.current && r.current != e.__e || _r(r, null, t)), (r = e.__c) != null) {
    if (r.componentWillUnmount) try {
      r.componentWillUnmount();
    } catch (i) {
      F.__e(i, t);
    }
    r.base = r.__P = null;
  }
  if (r = e.__k) for (o = 0; o < r.length; o++) r[o] && Qo(r[o], t, n || typeof e.type != "function");
  n || gr(e.__e), e.__c = e.__ = e.__e = void 0;
}
function ss(e, t, n) {
  return this.constructor(e, n);
}
function vt(e, t, n) {
  var r, o, i, s;
  t == document && (t = document.documentElement), F.__ && F.__(e, t), o = (r = typeof n == "function") ? null : n && n.__k || t.__k, i = [], s = [], mr(t, e = (!r && n || t).__k = We(Xe, null, [e]), o || qt, qt, t.namespaceURI, !r && n ? [n] : o ? null : t.firstChild ? Kt.call(t.childNodes) : null, i, !r && n ? n : o ? o.__e : t.firstChild, r, s), qo(i, e, s);
}
function jo(e, t) {
  vt(e, t, jo);
}
function as(e, t, n) {
  var r, o, i, s, a = ze({}, e.props);
  for (i in e.type && e.type.defaultProps && (s = e.type.defaultProps), t) i == "key" ? r = t[i] : i == "ref" ? o = t[i] : a[i] = t[i] === void 0 && s != null ? s[i] : t[i];
  return arguments.length > 2 && (a.children = arguments.length > 3 ? Kt.call(arguments, 2) : n), Ot(e.type, a, r || e.key, o || e.ref, null);
}
function Et(e) {
  function t(n) {
    var r, o;
    return this.getChildContext || (r = /* @__PURE__ */ new Set(), (o = {})[t.__c] = this, this.getChildContext = function() {
      return o;
    }, this.componentWillUnmount = function() {
      r = null;
    }, this.shouldComponentUpdate = function(i) {
      this.props.value != i.value && r.forEach(function(s) {
        s.__e = !0, er(s);
      });
    }, this.sub = function(i) {
      r.add(i);
      var s = i.componentWillUnmount;
      i.componentWillUnmount = function() {
        r && r.delete(i), s && s.call(i);
      };
    }), n.children;
  }
  return t.__c = "__cC" + Fo++, t.__ = e, t.Provider = t.__l = (t.Consumer = function(n, r) {
    return n.children(r);
  }).contextType = t, t;
}
Kt = Oo.slice, F = { __e: function(e, t, n, r) {
  for (var o, i, s; t = t.__; ) if ((o = t.__c) && !o.__) try {
    if ((i = o.constructor) && i.getDerivedStateFromError != null && (o.setState(i.getDerivedStateFromError(e)), s = o.__d), o.componentDidCatch != null && (o.componentDidCatch(e, r || {}), s = o.__d), s) return o.__E = o;
  } catch (a) {
    e = a;
  }
  throw e;
} }, Io = 0, Be.prototype.setState = function(e, t) {
  var n;
  n = this.__s != null && this.__s != this.state ? this.__s : this.__s = ze({}, this.state), typeof e == "function" && (e = e(ze({}, n), this.props)), e && ze(n, e), e != null && this.__v && (t && this._sb.push(t), er(this));
}, Be.prototype.forceUpdate = function(e) {
  this.__v && (this.__e = !0, e && this.__h.push(e), er(this));
}, Be.prototype.render = Xe, ut = [], Lo = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, $o = function(e, t) {
  return e.__v.__b - t.__v.__b;
}, gn.__r = 0, Po = /(PointerCapture)$|Capture$/i, hr = 0, Jn = Lr(!1), Zn = Lr(!0), Fo = 0;
var cs = 0;
function b(e, t, n, r, o, i) {
  t || (t = {});
  var s, a, c = t;
  if ("ref" in c) for (a in c = {}, t) a == "ref" ? s = t[a] : c[a] = t[a];
  var l = { type: e, props: c, key: n, ref: s, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --cs, __i: -1, __u: 0, __source: o, __self: i };
  if (typeof e == "function" && (s = e.defaultProps)) for (a in s) c[a] === void 0 && (c[a] = s[a]);
  return F.vnode && F.vnode(l), l;
}
var ot, W, Hn, $r, St = 0, Vo = [], J = F, Pr = J.__b, Fr = J.__r, Or = J.diffed, Ur = J.__c, zr = J.unmount, Br = J.__;
function At(e, t) {
  J.__h && J.__h(W, e, St || t), St = 0;
  var n = W.__H || (W.__H = { __: [], __h: [] });
  return e >= n.__.length && n.__.push({}), n.__[e];
}
function j(e) {
  return St = 1, xn(Xo, e);
}
function xn(e, t, n) {
  var r = At(ot++, 2);
  if (r.t = e, !r.__c && (r.__ = [n ? n(t) : Xo(void 0, t), function(a) {
    var c = r.__N ? r.__N[0] : r.__[0], l = r.t(c, a);
    c !== l && (r.__N = [l, r.__[1]], r.__c.setState({}));
  }], r.__c = W, !W.__f)) {
    var o = function(a, c, l) {
      if (!r.__c.__H) return !0;
      var d = r.__c.__H.__.filter(function(h) {
        return !!h.__c;
      });
      if (d.every(function(h) {
        return !h.__N;
      })) return !i || i.call(this, a, c, l);
      var u = r.__c.props !== a;
      return d.forEach(function(h) {
        if (h.__N) {
          var f = h.__[0];
          h.__ = h.__N, h.__N = void 0, f !== h.__[0] && (u = !0);
        }
      }), i && i.call(this, a, c, l) || u;
    };
    W.__f = !0;
    var i = W.shouldComponentUpdate, s = W.componentWillUpdate;
    W.componentWillUpdate = function(a, c, l) {
      if (this.__e) {
        var d = i;
        i = void 0, o(a, c, l), i = d;
      }
      s && s.call(this, a, c, l);
    }, W.shouldComponentUpdate = o;
  }
  return r.__N || r.__;
}
function U(e, t) {
  var n = At(ot++, 3);
  !J.__s && yr(n.__H, t) && (n.__ = e, n.u = t, W.__H.__h.push(n));
}
function Ct(e, t) {
  var n = At(ot++, 4);
  !J.__s && yr(n.__H, t) && (n.__ = e, n.u = t, W.__h.push(n));
}
function z(e) {
  return St = 5, H(function() {
    return { current: e };
  }, []);
}
function Yo(e, t, n) {
  St = 6, Ct(function() {
    if (typeof e == "function") {
      var r = e(t());
      return function() {
        e(null), r && typeof r == "function" && r();
      };
    }
    if (e) return e.current = t(), function() {
      return e.current = null;
    };
  }, n == null ? n : n.concat(e));
}
function H(e, t) {
  var n = At(ot++, 7);
  return yr(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
}
function P(e, t) {
  return St = 8, H(function() {
    return e;
  }, t);
}
function qe(e) {
  var t = W.context[e.__c], n = At(ot++, 9);
  return n.c = e, t ? (n.__ == null && (n.__ = !0, t.sub(W)), t.props.value) : e.__;
}
function Ko(e, t) {
  J.useDebugValue && J.useDebugValue(t ? t(e) : e);
}
function Wo() {
  var e = At(ot++, 11);
  if (!e.__) {
    for (var t = W.__v; t !== null && !t.__m && t.__ !== null; ) t = t.__;
    var n = t.__m || (t.__m = [0, 0]);
    e.__ = "P" + n[0] + "-" + n[1]++;
  }
  return e.__;
}
function ls() {
  for (var e; e = Vo.shift(); ) if (e.__P && e.__H) try {
    e.__H.__h.forEach(un), e.__H.__h.forEach(nr), e.__H.__h = [];
  } catch (t) {
    e.__H.__h = [], J.__e(t, e.__v);
  }
}
J.__b = function(e) {
  W = null, Pr && Pr(e);
}, J.__ = function(e, t) {
  e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Br && Br(e, t);
}, J.__r = function(e) {
  Fr && Fr(e), ot = 0;
  var t = (W = e.__c).__H;
  t && (Hn === W ? (t.__h = [], W.__h = [], t.__.forEach(function(n) {
    n.__N && (n.__ = n.__N), n.u = n.__N = void 0;
  })) : (t.__h.forEach(un), t.__h.forEach(nr), t.__h = [], ot = 0)), Hn = W;
}, J.diffed = function(e) {
  Or && Or(e);
  var t = e.__c;
  t && t.__H && (t.__H.__h.length && (Vo.push(t) !== 1 && $r === J.requestAnimationFrame || (($r = J.requestAnimationFrame) || us)(ls)), t.__H.__.forEach(function(n) {
    n.u && (n.__H = n.u), n.u = void 0;
  })), Hn = W = null;
}, J.__c = function(e, t) {
  t.some(function(n) {
    try {
      n.__h.forEach(un), n.__h = n.__h.filter(function(r) {
        return !r.__ || nr(r);
      });
    } catch (r) {
      t.some(function(o) {
        o.__h && (o.__h = []);
      }), t = [], J.__e(r, n.__v);
    }
  }), Ur && Ur(e, t);
}, J.unmount = function(e) {
  zr && zr(e);
  var t, n = e.__c;
  n && n.__H && (n.__H.__.forEach(function(r) {
    try {
      un(r);
    } catch (o) {
      t = o;
    }
  }), n.__H = void 0, t && J.__e(t, n.__v));
};
var qr = typeof requestAnimationFrame == "function";
function us(e) {
  var t, n = function() {
    clearTimeout(r), qr && cancelAnimationFrame(t), setTimeout(e);
  }, r = setTimeout(n, 35);
  qr && (t = requestAnimationFrame(n));
}
function un(e) {
  var t = W, n = e.__c;
  typeof n == "function" && (e.__c = void 0, n()), W = t;
}
function nr(e) {
  var t = W;
  e.__c = e.__(), W = t;
}
function yr(e, t) {
  return !e || e.length !== t.length || t.some(function(n, r) {
    return n !== e[r];
  });
}
function Xo(e, t) {
  return typeof t == "function" ? t(e) : t;
}
function Go(e, t) {
  for (var n in t) e[n] = t[n];
  return e;
}
function rr(e, t) {
  for (var n in e) if (n !== "__source" && !(n in t)) return !0;
  for (var r in t) if (r !== "__source" && e[r] !== t[r]) return !0;
  return !1;
}
function Jo(e, t) {
  var n = t(), r = j({ t: { __: n, u: t } }), o = r[0].t, i = r[1];
  return Ct(function() {
    o.__ = n, o.u = t, Qn(o) && i({ t: o });
  }, [e, n, t]), U(function() {
    return Qn(o) && i({ t: o }), e(function() {
      Qn(o) && i({ t: o });
    });
  }, [e]), n;
}
function Qn(e) {
  var t, n, r = e.u, o = e.__;
  try {
    var i = r();
    return !((t = o) === (n = i) && (t !== 0 || 1 / t == 1 / n) || t != t && n != n);
  } catch {
    return !0;
  }
}
function Zo(e) {
  e();
}
function ei(e) {
  return e;
}
function ti() {
  return [!1, Zo];
}
var ni = Ct;
function or(e, t) {
  this.props = e, this.context = t;
}
function ri(e, t) {
  function n(o) {
    var i = this.props.ref, s = i == o.ref;
    return !s && i && (i.call ? i(null) : i.current = null), t ? !t(this.props, o) || !s : rr(this.props, o);
  }
  function r(o) {
    return this.shouldComponentUpdate = n, We(e, o);
  }
  return r.displayName = "Memo(" + (e.displayName || e.name) + ")", r.prototype.isReactComponent = !0, r.__f = !0, r.type = e, r;
}
(or.prototype = new Be()).isPureReactComponent = !0, or.prototype.shouldComponentUpdate = function(e, t) {
  return rr(this.props, e) || rr(this.state, t);
};
var Hr = F.__b;
F.__b = function(e) {
  e.type && e.type.__f && e.ref && (e.props.ref = e.ref, e.ref = null), Hr && Hr(e);
};
var ds = typeof Symbol < "u" && Symbol.for && Symbol.for("react.forward_ref") || 3911;
function oi(e) {
  function t(n) {
    var r = Go({}, n);
    return delete r.ref, e(r, n.ref || null);
  }
  return t.$$typeof = ds, t.render = e, t.prototype.isReactComponent = t.__f = !0, t.displayName = "ForwardRef(" + (e.displayName || e.name) + ")", t;
}
var Qr = function(e, t) {
  return e == null ? null : Ke(Ke(e).map(t));
}, fs = { map: Qr, forEach: Qr, count: function(e) {
  return e ? Ke(e).length : 0;
}, only: function(e) {
  var t = Ke(e);
  if (t.length !== 1) throw "Children.only";
  return t[0];
}, toArray: Ke }, ps = F.__e;
F.__e = function(e, t, n, r) {
  if (e.then) {
    for (var o, i = t; i = i.__; ) if ((o = i.__c) && o.__c) return t.__e == null && (t.__e = n.__e, t.__k = n.__k), o.__c(e, t);
  }
  ps(e, t, n, r);
};
var jr = F.unmount;
function ii(e, t, n) {
  return e && (e.__c && e.__c.__H && (e.__c.__H.__.forEach(function(r) {
    typeof r.__c == "function" && r.__c();
  }), e.__c.__H = null), (e = Go({}, e)).__c != null && (e.__c.__P === n && (e.__c.__P = t), e.__c.__e = !0, e.__c = null), e.__k = e.__k && e.__k.map(function(r) {
    return ii(r, t, n);
  })), e;
}
function si(e, t, n) {
  return e && n && (e.__v = null, e.__k = e.__k && e.__k.map(function(r) {
    return si(r, t, n);
  }), e.__c && e.__c.__P === t && (e.__e && n.appendChild(e.__e), e.__c.__e = !0, e.__c.__P = n)), e;
}
function dn() {
  this.__u = 0, this.o = null, this.__b = null;
}
function ai(e) {
  var t = e.__.__c;
  return t && t.__a && t.__a(e);
}
function hs(e) {
  var t, n, r;
  function o(i) {
    if (t || (t = e()).then(function(s) {
      n = s.default || s;
    }, function(s) {
      r = s;
    }), r) throw r;
    if (!n) throw t;
    return We(n, i);
  }
  return o.displayName = "Lazy", o.__f = !0, o;
}
function Pt() {
  this.i = null, this.l = null;
}
F.unmount = function(e) {
  var t = e.__c;
  t && t.__R && t.__R(), t && 32 & e.__u && (e.type = null), jr && jr(e);
}, (dn.prototype = new Be()).__c = function(e, t) {
  var n = t.__c, r = this;
  r.o == null && (r.o = []), r.o.push(n);
  var o = ai(r.__v), i = !1, s = function() {
    i || (i = !0, n.__R = null, o ? o(a) : a());
  };
  n.__R = s;
  var a = function() {
    if (!--r.__u) {
      if (r.state.__a) {
        var c = r.state.__a;
        r.__v.__k[0] = si(c, c.__c.__P, c.__c.__O);
      }
      var l;
      for (r.setState({ __a: r.__b = null }); l = r.o.pop(); ) l.forceUpdate();
    }
  };
  r.__u++ || 32 & t.__u || r.setState({ __a: r.__b = r.__v.__k[0] }), e.then(s, s);
}, dn.prototype.componentWillUnmount = function() {
  this.o = [];
}, dn.prototype.render = function(e, t) {
  if (this.__b) {
    if (this.__v.__k) {
      var n = document.createElement("div"), r = this.__v.__k[0].__c;
      this.__v.__k[0] = ii(this.__b, n, r.__O = r.__P);
    }
    this.__b = null;
  }
  var o = t.__a && We(Xe, null, e.fallback);
  return o && (o.__u &= -33), [We(Xe, null, t.__a ? null : e.children), o];
};
var Vr = function(e, t, n) {
  if (++n[1] === n[0] && e.l.delete(t), e.props.revealOrder && (e.props.revealOrder[0] !== "t" || !e.l.size)) for (n = e.i; n; ) {
    for (; n.length > 3; ) n.pop()();
    if (n[1] < n[0]) break;
    e.i = n = n[2];
  }
};
function gs(e) {
  return this.getChildContext = function() {
    return e.context;
  }, e.children;
}
function ms(e) {
  var t = this, n = e.h;
  if (t.componentWillUnmount = function() {
    vt(null, t.v), t.v = null, t.h = null;
  }, t.h && t.h !== n && t.componentWillUnmount(), !t.v) {
    for (var r = t.__v; r !== null && !r.__m && r.__ !== null; ) r = r.__;
    t.h = n, t.v = { nodeType: 1, parentNode: n, childNodes: [], __k: { __m: r.__m }, contains: function() {
      return !0;
    }, insertBefore: function(o, i) {
      this.childNodes.push(o), t.h.insertBefore(o, i);
    }, removeChild: function(o) {
      this.childNodes.splice(this.childNodes.indexOf(o) >>> 1, 1), t.h.removeChild(o);
    } };
  }
  vt(We(gs, { context: t.context }, e.__v), t.v);
}
function ci(e, t) {
  var n = We(ms, { __v: e, h: t });
  return n.containerInfo = t, n;
}
(Pt.prototype = new Be()).__a = function(e) {
  var t = this, n = ai(t.__v), r = t.l.get(e);
  return r[0]++, function(o) {
    var i = function() {
      t.props.revealOrder ? (r.push(o), Vr(t, e, r)) : o();
    };
    n ? n(i) : i();
  };
}, Pt.prototype.render = function(e) {
  this.i = null, this.l = /* @__PURE__ */ new Map();
  var t = Ke(e.children);
  e.revealOrder && e.revealOrder[0] === "b" && t.reverse();
  for (var n = t.length; n--; ) this.l.set(t[n], this.i = [1, 0, this.i]);
  return e.children;
}, Pt.prototype.componentDidUpdate = Pt.prototype.componentDidMount = function() {
  var e = this;
  this.l.forEach(function(t, n) {
    Vr(e, n, t);
  });
};
var li = typeof Symbol < "u" && Symbol.for && Symbol.for("react.element") || 60103, _s = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, ys = /^on(Ani|Tra|Tou|BeforeInp|Compo)/, bs = /[A-Z0-9]/g, vs = typeof document < "u", Ss = function(e) {
  return (typeof Symbol < "u" && typeof Symbol() == "symbol" ? /fil|che|rad/ : /fil|che|ra/).test(e);
};
function ws(e, t, n) {
  return t.__k == null && (t.textContent = ""), vt(e, t), typeof n == "function" && n(), e ? e.__c : null;
}
function Es(e, t, n) {
  return jo(e, t), typeof n == "function" && n(), e ? e.__c : null;
}
Be.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(e) {
  Object.defineProperty(Be.prototype, e, { configurable: !0, get: function() {
    return this["UNSAFE_" + e];
  }, set: function(t) {
    Object.defineProperty(this, e, { configurable: !0, writable: !0, value: t });
  } });
});
var Yr = F.event;
function As() {
}
function Cs() {
  return this.cancelBubble;
}
function ks() {
  return this.defaultPrevented;
}
F.event = function(e) {
  return Yr && (e = Yr(e)), e.persist = As, e.isPropagationStopped = Cs, e.isDefaultPrevented = ks, e.nativeEvent = e;
};
var br, xs = { enumerable: !1, configurable: !0, get: function() {
  return this.class;
} }, Kr = F.vnode;
F.vnode = function(e) {
  typeof e.type == "string" && (function(t) {
    var n = t.props, r = t.type, o = {}, i = r.indexOf("-") === -1;
    for (var s in n) {
      var a = n[s];
      if (!(s === "value" && "defaultValue" in n && a == null || vs && s === "children" && r === "noscript" || s === "class" || s === "className")) {
        var c = s.toLowerCase();
        s === "defaultValue" && "value" in n && n.value == null ? s = "value" : s === "download" && a === !0 ? a = "" : c === "translate" && a === "no" ? a = !1 : c[0] === "o" && c[1] === "n" ? c === "ondoubleclick" ? s = "ondblclick" : c !== "onchange" || r !== "input" && r !== "textarea" || Ss(n.type) ? c === "onfocus" ? s = "onfocusin" : c === "onblur" ? s = "onfocusout" : ys.test(s) && (s = c) : c = s = "oninput" : i && _s.test(s) ? s = s.replace(bs, "-$&").toLowerCase() : a === null && (a = void 0), c === "oninput" && o[s = c] && (s = "oninputCapture"), o[s] = a;
      }
    }
    r == "select" && o.multiple && Array.isArray(o.value) && (o.value = Ke(n.children).forEach(function(l) {
      l.props.selected = o.value.indexOf(l.props.value) != -1;
    })), r == "select" && o.defaultValue != null && (o.value = Ke(n.children).forEach(function(l) {
      l.props.selected = o.multiple ? o.defaultValue.indexOf(l.props.value) != -1 : o.defaultValue == l.props.value;
    })), n.class && !n.className ? (o.class = n.class, Object.defineProperty(o, "className", xs)) : (n.className && !n.class || n.class && n.className) && (o.class = o.className = n.className), t.props = o;
  })(e), e.$$typeof = li, Kr && Kr(e);
};
var Wr = F.__r;
F.__r = function(e) {
  Wr && Wr(e), br = e.__c;
};
var Xr = F.diffed;
F.diffed = function(e) {
  Xr && Xr(e);
  var t = e.props, n = e.__e;
  n != null && e.type === "textarea" && "value" in t && t.value !== n.value && (n.value = t.value == null ? "" : t.value), br = null;
};
var Ts = { ReactCurrentDispatcher: { current: { readContext: function(e) {
  return br.__n[e.__c].props.value;
}, useCallback: P, useContext: qe, useDebugValue: Ko, useDeferredValue: ei, useEffect: U, useId: Wo, useImperativeHandle: Yo, useInsertionEffect: ni, useLayoutEffect: Ct, useMemo: H, useReducer: xn, useRef: z, useState: j, useSyncExternalStore: Jo, useTransition: ti } } };
function Rs(e) {
  return We.bind(null, e);
}
function Tn(e) {
  return !!e && e.$$typeof === li;
}
function Ds(e) {
  return Tn(e) && e.type === Xe;
}
function Ns(e) {
  return !!e && !!e.displayName && (typeof e.displayName == "string" || e.displayName instanceof String) && e.displayName.startsWith("Memo(");
}
function ui(e) {
  return Tn(e) ? as.apply(null, arguments) : e;
}
function Ms(e) {
  return !!e.__k && (vt(null, e), !0);
}
function Is(e) {
  return e && (e.base || e.nodeType === 1 && e) || null;
}
var Ft = function(e, t) {
  return e(t);
}, Ls = function(e, t) {
  return e(t);
}, $s = Xe, Ps = Tn, Z = { useState: j, useId: Wo, useReducer: xn, useEffect: U, useLayoutEffect: Ct, useInsertionEffect: ni, useTransition: ti, useDeferredValue: ei, useSyncExternalStore: Jo, startTransition: Zo, useRef: z, useImperativeHandle: Yo, useMemo: H, useCallback: P, useContext: qe, useDebugValue: Ko, version: "18.3.1", Children: fs, render: ws, hydrate: Es, unmountComponentAtNode: Ms, createPortal: ci, createElement: We, createContext: Et, createFactory: Rs, cloneElement: ui, createRef: ns, Fragment: Xe, isValidElement: Tn, isElement: Ps, isFragment: Ds, isMemo: Ns, findDOMNode: Is, Component: Be, PureComponent: or, memo: ri, forwardRef: oi, flushSync: Ls, unstable_batchedUpdates: Ft, StrictMode: $s, Suspense: dn, SuspenseList: Pt, lazy: hs, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: Ts };
function Fs() {
  for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)
    t[n] = arguments[n];
  return H(
    () => (r) => {
      t.forEach((o) => o(r));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    t
  );
}
const Rn = typeof window < "u" && typeof window.document < "u" && typeof window.document.createElement < "u";
function kt(e) {
  const t = Object.prototype.toString.call(e);
  return t === "[object Window]" || // In Electron context the Window object serializes to [object global]
  t === "[object global]";
}
function vr(e) {
  return "nodeType" in e;
}
function ge(e) {
  var t, n;
  return e ? kt(e) ? e : vr(e) && (t = (n = e.ownerDocument) == null ? void 0 : n.defaultView) != null ? t : window : window;
}
function Sr(e) {
  const {
    Document: t
  } = ge(e);
  return e instanceof t;
}
function Xt(e) {
  return kt(e) ? !1 : e instanceof ge(e).HTMLElement;
}
function di(e) {
  return e instanceof ge(e).SVGElement;
}
function xt(e) {
  return e ? kt(e) ? e.document : vr(e) ? Sr(e) ? e : Xt(e) || di(e) ? e.ownerDocument : document : document : document;
}
const Me = Rn ? Ct : U;
function Dn(e) {
  const t = z(e);
  return Me(() => {
    t.current = e;
  }), P(function() {
    for (var n = arguments.length, r = new Array(n), o = 0; o < n; o++)
      r[o] = arguments[o];
    return t.current == null ? void 0 : t.current(...r);
  }, []);
}
function Os() {
  const e = z(null), t = P((r, o) => {
    e.current = setInterval(r, o);
  }, []), n = P(() => {
    e.current !== null && (clearInterval(e.current), e.current = null);
  }, []);
  return [t, n];
}
function Ht(e, t) {
  t === void 0 && (t = [e]);
  const n = z(e);
  return Me(() => {
    n.current !== e && (n.current = e);
  }, t), n;
}
function Gt(e, t) {
  const n = z();
  return H(
    () => {
      const r = e(n.current);
      return n.current = r, r;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [...t]
  );
}
function mn(e) {
  const t = Dn(e), n = z(null), r = P(
    (o) => {
      o !== n.current && t?.(o, n.current), n.current = o;
    },
    //eslint-disable-next-line
    []
  );
  return [n, r];
}
function _n(e) {
  const t = z();
  return U(() => {
    t.current = e;
  }, [e]), t.current;
}
let jn = {};
function Jt(e, t) {
  return H(() => {
    if (t)
      return t;
    const n = jn[e] == null ? 0 : jn[e] + 1;
    return jn[e] = n, e + "-" + n;
  }, [e, t]);
}
function fi(e) {
  return function(t) {
    for (var n = arguments.length, r = new Array(n > 1 ? n - 1 : 0), o = 1; o < n; o++)
      r[o - 1] = arguments[o];
    return r.reduce((i, s) => {
      const a = Object.entries(s);
      for (const [c, l] of a) {
        const d = i[c];
        d != null && (i[c] = d + e * l);
      }
      return i;
    }, {
      ...t
    });
  };
}
const _t = /* @__PURE__ */ fi(1), Qt = /* @__PURE__ */ fi(-1);
function Us(e) {
  return "clientX" in e && "clientY" in e;
}
function Nn(e) {
  if (!e)
    return !1;
  const {
    KeyboardEvent: t
  } = ge(e.target);
  return t && e instanceof t;
}
function zs(e) {
  if (!e)
    return !1;
  const {
    TouchEvent: t
  } = ge(e.target);
  return t && e instanceof t;
}
function yn(e) {
  if (zs(e)) {
    if (e.touches && e.touches.length) {
      const {
        clientX: t,
        clientY: n
      } = e.touches[0];
      return {
        x: t,
        y: n
      };
    } else if (e.changedTouches && e.changedTouches.length) {
      const {
        clientX: t,
        clientY: n
      } = e.changedTouches[0];
      return {
        x: t,
        y: n
      };
    }
  }
  return Us(e) ? {
    x: e.clientX,
    y: e.clientY
  } : null;
}
const it = /* @__PURE__ */ Object.freeze({
  Translate: {
    toString(e) {
      if (!e)
        return;
      const {
        x: t,
        y: n
      } = e;
      return "translate3d(" + (t ? Math.round(t) : 0) + "px, " + (n ? Math.round(n) : 0) + "px, 0)";
    }
  },
  Scale: {
    toString(e) {
      if (!e)
        return;
      const {
        scaleX: t,
        scaleY: n
      } = e;
      return "scaleX(" + t + ") scaleY(" + n + ")";
    }
  },
  Transform: {
    toString(e) {
      if (e)
        return [it.Translate.toString(e), it.Scale.toString(e)].join(" ");
    }
  },
  Transition: {
    toString(e) {
      let {
        property: t,
        duration: n,
        easing: r
      } = e;
      return t + " " + n + "ms " + r;
    }
  }
}), Gr = "a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";
function Bs(e) {
  return e.matches(Gr) ? e : e.querySelector(Gr);
}
const qs = {
  display: "none"
};
function Hs(e) {
  let {
    id: t,
    value: n
  } = e;
  return Z.createElement("div", {
    id: t,
    style: qs
  }, n);
}
function Qs(e) {
  let {
    id: t,
    announcement: n,
    ariaLiveType: r = "assertive"
  } = e;
  const o = {
    position: "fixed",
    top: 0,
    left: 0,
    width: 1,
    height: 1,
    margin: -1,
    border: 0,
    padding: 0,
    overflow: "hidden",
    clip: "rect(0 0 0 0)",
    clipPath: "inset(100%)",
    whiteSpace: "nowrap"
  };
  return Z.createElement("div", {
    id: t,
    style: o,
    role: "status",
    "aria-live": r,
    "aria-atomic": !0
  }, n);
}
function js() {
  const [e, t] = j("");
  return {
    announce: P((r) => {
      r != null && t(r);
    }, []),
    announcement: e
  };
}
const pi = /* @__PURE__ */ Et(null);
function Vs(e) {
  const t = qe(pi);
  U(() => {
    if (!t)
      throw new Error("useDndMonitor must be used within a children of <DndContext>");
    return t(e);
  }, [e, t]);
}
function Ys() {
  const [e] = j(() => /* @__PURE__ */ new Set()), t = P((r) => (e.add(r), () => e.delete(r)), [e]);
  return [P((r) => {
    let {
      type: o,
      event: i
    } = r;
    e.forEach((s) => {
      var a;
      return (a = s[o]) == null ? void 0 : a.call(s, i);
    });
  }, [e]), t];
}
const Ks = {
  draggable: `
    To pick up a draggable item, press the space bar.
    While dragging, use the arrow keys to move the item.
    Press space again to drop the item in its new position, or press escape to cancel.
  `
}, Ws = {
  onDragStart(e) {
    let {
      active: t
    } = e;
    return "Picked up draggable item " + t.id + ".";
  },
  onDragOver(e) {
    let {
      active: t,
      over: n
    } = e;
    return n ? "Draggable item " + t.id + " was moved over droppable area " + n.id + "." : "Draggable item " + t.id + " is no longer over a droppable area.";
  },
  onDragEnd(e) {
    let {
      active: t,
      over: n
    } = e;
    return n ? "Draggable item " + t.id + " was dropped over droppable area " + n.id : "Draggable item " + t.id + " was dropped.";
  },
  onDragCancel(e) {
    let {
      active: t
    } = e;
    return "Dragging was cancelled. Draggable item " + t.id + " was dropped.";
  }
};
function Xs(e) {
  let {
    announcements: t = Ws,
    container: n,
    hiddenTextDescribedById: r,
    screenReaderInstructions: o = Ks
  } = e;
  const {
    announce: i,
    announcement: s
  } = js(), a = Jt("DndLiveRegion"), [c, l] = j(!1);
  if (U(() => {
    l(!0);
  }, []), Vs(H(() => ({
    onDragStart(u) {
      let {
        active: h
      } = u;
      i(t.onDragStart({
        active: h
      }));
    },
    onDragMove(u) {
      let {
        active: h,
        over: f
      } = u;
      t.onDragMove && i(t.onDragMove({
        active: h,
        over: f
      }));
    },
    onDragOver(u) {
      let {
        active: h,
        over: f
      } = u;
      i(t.onDragOver({
        active: h,
        over: f
      }));
    },
    onDragEnd(u) {
      let {
        active: h,
        over: f
      } = u;
      i(t.onDragEnd({
        active: h,
        over: f
      }));
    },
    onDragCancel(u) {
      let {
        active: h,
        over: f
      } = u;
      i(t.onDragCancel({
        active: h,
        over: f
      }));
    }
  }), [i, t])), !c)
    return null;
  const d = Z.createElement(Z.Fragment, null, Z.createElement(Hs, {
    id: r,
    value: o.draggable
  }), Z.createElement(Qs, {
    id: a,
    announcement: s
  }));
  return n ? ci(d, n) : d;
}
var re;
(function(e) {
  e.DragStart = "dragStart", e.DragMove = "dragMove", e.DragEnd = "dragEnd", e.DragCancel = "dragCancel", e.DragOver = "dragOver", e.RegisterDroppable = "registerDroppable", e.SetDroppableDisabled = "setDroppableDisabled", e.UnregisterDroppable = "unregisterDroppable";
})(re || (re = {}));
function bn() {
}
function Jr(e, t) {
  return H(
    () => ({
      sensor: e,
      options: t ?? {}
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [e, t]
  );
}
function Gs() {
  for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)
    t[n] = arguments[n];
  return H(
    () => [...t].filter((r) => r != null),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [...t]
  );
}
const Ie = /* @__PURE__ */ Object.freeze({
  x: 0,
  y: 0
});
function hi(e, t) {
  return Math.sqrt(Math.pow(e.x - t.x, 2) + Math.pow(e.y - t.y, 2));
}
function Js(e, t) {
  const n = yn(e);
  if (!n)
    return "0 0";
  const r = {
    x: (n.x - t.left) / t.width * 100,
    y: (n.y - t.top) / t.height * 100
  };
  return r.x + "% " + r.y + "%";
}
function gi(e, t) {
  let {
    data: {
      value: n
    }
  } = e, {
    data: {
      value: r
    }
  } = t;
  return n - r;
}
function Zs(e, t) {
  let {
    data: {
      value: n
    }
  } = e, {
    data: {
      value: r
    }
  } = t;
  return r - n;
}
function Zr(e) {
  let {
    left: t,
    top: n,
    height: r,
    width: o
  } = e;
  return [{
    x: t,
    y: n
  }, {
    x: t + o,
    y: n
  }, {
    x: t,
    y: n + r
  }, {
    x: t + o,
    y: n + r
  }];
}
function mi(e, t) {
  if (!e || e.length === 0)
    return null;
  const [n] = e;
  return n[t];
}
function eo(e, t, n) {
  return t === void 0 && (t = e.left), n === void 0 && (n = e.top), {
    x: t + e.width * 0.5,
    y: n + e.height * 0.5
  };
}
const ea = (e) => {
  let {
    collisionRect: t,
    droppableRects: n,
    droppableContainers: r
  } = e;
  const o = eo(t, t.left, t.top), i = [];
  for (const s of r) {
    const {
      id: a
    } = s, c = n.get(a);
    if (c) {
      const l = hi(eo(c), o);
      i.push({
        id: a,
        data: {
          droppableContainer: s,
          value: l
        }
      });
    }
  }
  return i.sort(gi);
}, ta = (e) => {
  let {
    collisionRect: t,
    droppableRects: n,
    droppableContainers: r
  } = e;
  const o = Zr(t), i = [];
  for (const s of r) {
    const {
      id: a
    } = s, c = n.get(a);
    if (c) {
      const l = Zr(c), d = o.reduce((h, f, g) => h + hi(l[g], f), 0), u = Number((d / 4).toFixed(4));
      i.push({
        id: a,
        data: {
          droppableContainer: s,
          value: u
        }
      });
    }
  }
  return i.sort(gi);
};
function na(e, t) {
  const n = Math.max(t.top, e.top), r = Math.max(t.left, e.left), o = Math.min(t.left + t.width, e.left + e.width), i = Math.min(t.top + t.height, e.top + e.height), s = o - r, a = i - n;
  if (r < o && n < i) {
    const c = t.width * t.height, l = e.width * e.height, d = s * a, u = d / (c + l - d);
    return Number(u.toFixed(4));
  }
  return 0;
}
const ra = (e) => {
  let {
    collisionRect: t,
    droppableRects: n,
    droppableContainers: r
  } = e;
  const o = [];
  for (const i of r) {
    const {
      id: s
    } = i, a = n.get(s);
    if (a) {
      const c = na(a, t);
      c > 0 && o.push({
        id: s,
        data: {
          droppableContainer: i,
          value: c
        }
      });
    }
  }
  return o.sort(Zs);
};
function oa(e, t, n) {
  return {
    ...e,
    scaleX: t && n ? t.width / n.width : 1,
    scaleY: t && n ? t.height / n.height : 1
  };
}
function _i(e, t) {
  return e && t ? {
    x: e.left - t.left,
    y: e.top - t.top
  } : Ie;
}
function ia(e) {
  return function(n) {
    for (var r = arguments.length, o = new Array(r > 1 ? r - 1 : 0), i = 1; i < r; i++)
      o[i - 1] = arguments[i];
    return o.reduce((s, a) => ({
      ...s,
      top: s.top + e * a.y,
      bottom: s.bottom + e * a.y,
      left: s.left + e * a.x,
      right: s.right + e * a.x
    }), {
      ...n
    });
  };
}
const sa = /* @__PURE__ */ ia(1);
function yi(e) {
  if (e.startsWith("matrix3d(")) {
    const t = e.slice(9, -1).split(/, /);
    return {
      x: +t[12],
      y: +t[13],
      scaleX: +t[0],
      scaleY: +t[5]
    };
  } else if (e.startsWith("matrix(")) {
    const t = e.slice(7, -1).split(/, /);
    return {
      x: +t[4],
      y: +t[5],
      scaleX: +t[0],
      scaleY: +t[3]
    };
  }
  return null;
}
function aa(e, t, n) {
  const r = yi(t);
  if (!r)
    return e;
  const {
    scaleX: o,
    scaleY: i,
    x: s,
    y: a
  } = r, c = e.left - s - (1 - o) * parseFloat(n), l = e.top - a - (1 - i) * parseFloat(n.slice(n.indexOf(" ") + 1)), d = o ? e.width / o : e.width, u = i ? e.height / i : e.height;
  return {
    width: d,
    height: u,
    top: l,
    right: c + d,
    bottom: l + u,
    left: c
  };
}
const ca = {
  ignoreTransform: !1
};
function Tt(e, t) {
  t === void 0 && (t = ca);
  let n = e.getBoundingClientRect();
  if (t.ignoreTransform) {
    const {
      transform: l,
      transformOrigin: d
    } = ge(e).getComputedStyle(e);
    l && (n = aa(n, l, d));
  }
  const {
    top: r,
    left: o,
    width: i,
    height: s,
    bottom: a,
    right: c
  } = n;
  return {
    top: r,
    left: o,
    width: i,
    height: s,
    bottom: a,
    right: c
  };
}
function to(e) {
  return Tt(e, {
    ignoreTransform: !0
  });
}
function la(e) {
  const t = e.innerWidth, n = e.innerHeight;
  return {
    top: 0,
    left: 0,
    right: t,
    bottom: n,
    width: t,
    height: n
  };
}
function ua(e, t) {
  return t === void 0 && (t = ge(e).getComputedStyle(e)), t.position === "fixed";
}
function da(e, t) {
  t === void 0 && (t = ge(e).getComputedStyle(e));
  const n = /(auto|scroll|overlay)/;
  return ["overflow", "overflowX", "overflowY"].some((o) => {
    const i = t[o];
    return typeof i == "string" ? n.test(i) : !1;
  });
}
function Mn(e, t) {
  const n = [];
  function r(o) {
    if (t != null && n.length >= t || !o)
      return n;
    if (Sr(o) && o.scrollingElement != null && !n.includes(o.scrollingElement))
      return n.push(o.scrollingElement), n;
    if (!Xt(o) || di(o) || n.includes(o))
      return n;
    const i = ge(e).getComputedStyle(o);
    return o !== e && da(o, i) && n.push(o), ua(o, i) ? n : r(o.parentNode);
  }
  return e ? r(e) : n;
}
function bi(e) {
  const [t] = Mn(e, 1);
  return t ?? null;
}
function Vn(e) {
  return !Rn || !e ? null : kt(e) ? e : vr(e) ? Sr(e) || e === xt(e).scrollingElement ? window : Xt(e) ? e : null : null;
}
function vi(e) {
  return kt(e) ? e.scrollX : e.scrollLeft;
}
function Si(e) {
  return kt(e) ? e.scrollY : e.scrollTop;
}
function ir(e) {
  return {
    x: vi(e),
    y: Si(e)
  };
}
var ie;
(function(e) {
  e[e.Forward = 1] = "Forward", e[e.Backward = -1] = "Backward";
})(ie || (ie = {}));
function wi(e) {
  return !Rn || !e ? !1 : e === document.scrollingElement;
}
function Ei(e) {
  const t = {
    x: 0,
    y: 0
  }, n = wi(e) ? {
    height: window.innerHeight,
    width: window.innerWidth
  } : {
    height: e.clientHeight,
    width: e.clientWidth
  }, r = {
    x: e.scrollWidth - n.width,
    y: e.scrollHeight - n.height
  }, o = e.scrollTop <= t.y, i = e.scrollLeft <= t.x, s = e.scrollTop >= r.y, a = e.scrollLeft >= r.x;
  return {
    isTop: o,
    isLeft: i,
    isBottom: s,
    isRight: a,
    maxScroll: r,
    minScroll: t
  };
}
const fa = {
  x: 0.2,
  y: 0.2
};
function pa(e, t, n, r, o) {
  let {
    top: i,
    left: s,
    right: a,
    bottom: c
  } = n;
  r === void 0 && (r = 10), o === void 0 && (o = fa);
  const {
    isTop: l,
    isBottom: d,
    isLeft: u,
    isRight: h
  } = Ei(e), f = {
    x: 0,
    y: 0
  }, g = {
    x: 0,
    y: 0
  }, _ = {
    height: t.height * o.y,
    width: t.width * o.x
  };
  return !l && i <= t.top + _.height ? (f.y = ie.Backward, g.y = r * Math.abs((t.top + _.height - i) / _.height)) : !d && c >= t.bottom - _.height && (f.y = ie.Forward, g.y = r * Math.abs((t.bottom - _.height - c) / _.height)), !h && a >= t.right - _.width ? (f.x = ie.Forward, g.x = r * Math.abs((t.right - _.width - a) / _.width)) : !u && s <= t.left + _.width && (f.x = ie.Backward, g.x = r * Math.abs((t.left + _.width - s) / _.width)), {
    direction: f,
    speed: g
  };
}
function ha(e) {
  if (e === document.scrollingElement) {
    const {
      innerWidth: i,
      innerHeight: s
    } = window;
    return {
      top: 0,
      left: 0,
      right: i,
      bottom: s,
      width: i,
      height: s
    };
  }
  const {
    top: t,
    left: n,
    right: r,
    bottom: o
  } = e.getBoundingClientRect();
  return {
    top: t,
    left: n,
    right: r,
    bottom: o,
    width: e.clientWidth,
    height: e.clientHeight
  };
}
function Ai(e) {
  return e.reduce((t, n) => _t(t, ir(n)), Ie);
}
function ga(e) {
  return e.reduce((t, n) => t + vi(n), 0);
}
function ma(e) {
  return e.reduce((t, n) => t + Si(n), 0);
}
function Ci(e, t) {
  if (t === void 0 && (t = Tt), !e)
    return;
  const {
    top: n,
    left: r,
    bottom: o,
    right: i
  } = t(e);
  bi(e) && (o <= 0 || i <= 0 || n >= window.innerHeight || r >= window.innerWidth) && e.scrollIntoView({
    block: "center",
    inline: "center"
  });
}
const _a = [["x", ["left", "right"], ga], ["y", ["top", "bottom"], ma]];
class wr {
  constructor(t, n) {
    this.rect = void 0, this.width = void 0, this.height = void 0, this.top = void 0, this.bottom = void 0, this.right = void 0, this.left = void 0;
    const r = Mn(n), o = Ai(r);
    this.rect = {
      ...t
    }, this.width = t.width, this.height = t.height;
    for (const [i, s, a] of _a)
      for (const c of s)
        Object.defineProperty(this, c, {
          get: () => {
            const l = a(r), d = o[i] - l;
            return this.rect[c] + d;
          },
          enumerable: !0
        });
    Object.defineProperty(this, "rect", {
      enumerable: !1
    });
  }
}
class Ut {
  constructor(t) {
    this.target = void 0, this.listeners = [], this.removeAll = () => {
      this.listeners.forEach((n) => {
        var r;
        return (r = this.target) == null ? void 0 : r.removeEventListener(...n);
      });
    }, this.target = t;
  }
  add(t, n, r) {
    var o;
    (o = this.target) == null || o.addEventListener(t, n, r), this.listeners.push([t, n, r]);
  }
}
function ya(e) {
  const {
    EventTarget: t
  } = ge(e);
  return e instanceof t ? e : xt(e);
}
function Yn(e, t) {
  const n = Math.abs(e.x), r = Math.abs(e.y);
  return typeof t == "number" ? Math.sqrt(n ** 2 + r ** 2) > t : "x" in t && "y" in t ? n > t.x && r > t.y : "x" in t ? n > t.x : "y" in t ? r > t.y : !1;
}
var Ce;
(function(e) {
  e.Click = "click", e.DragStart = "dragstart", e.Keydown = "keydown", e.ContextMenu = "contextmenu", e.Resize = "resize", e.SelectionChange = "selectionchange", e.VisibilityChange = "visibilitychange";
})(Ce || (Ce = {}));
function no(e) {
  e.preventDefault();
}
function ba(e) {
  e.stopPropagation();
}
var q;
(function(e) {
  e.Space = "Space", e.Down = "ArrowDown", e.Right = "ArrowRight", e.Left = "ArrowLeft", e.Up = "ArrowUp", e.Esc = "Escape", e.Enter = "Enter", e.Tab = "Tab";
})(q || (q = {}));
const ki = {
  start: [q.Space, q.Enter],
  cancel: [q.Esc],
  end: [q.Space, q.Enter, q.Tab]
}, va = (e, t) => {
  let {
    currentCoordinates: n
  } = t;
  switch (e.code) {
    case q.Right:
      return {
        ...n,
        x: n.x + 25
      };
    case q.Left:
      return {
        ...n,
        x: n.x - 25
      };
    case q.Down:
      return {
        ...n,
        y: n.y + 25
      };
    case q.Up:
      return {
        ...n,
        y: n.y - 25
      };
  }
};
class Er {
  constructor(t) {
    this.props = void 0, this.autoScrollEnabled = !1, this.referenceCoordinates = void 0, this.listeners = void 0, this.windowListeners = void 0, this.props = t;
    const {
      event: {
        target: n
      }
    } = t;
    this.props = t, this.listeners = new Ut(xt(n)), this.windowListeners = new Ut(ge(n)), this.handleKeyDown = this.handleKeyDown.bind(this), this.handleCancel = this.handleCancel.bind(this), this.attach();
  }
  attach() {
    this.handleStart(), this.windowListeners.add(Ce.Resize, this.handleCancel), this.windowListeners.add(Ce.VisibilityChange, this.handleCancel), setTimeout(() => this.listeners.add(Ce.Keydown, this.handleKeyDown));
  }
  handleStart() {
    const {
      activeNode: t,
      onStart: n
    } = this.props, r = t.node.current;
    r && Ci(r), n(Ie);
  }
  handleKeyDown(t) {
    if (Nn(t)) {
      const {
        active: n,
        context: r,
        options: o
      } = this.props, {
        keyboardCodes: i = ki,
        coordinateGetter: s = va,
        scrollBehavior: a = "smooth"
      } = o, {
        code: c
      } = t;
      if (i.end.includes(c)) {
        this.handleEnd(t);
        return;
      }
      if (i.cancel.includes(c)) {
        this.handleCancel(t);
        return;
      }
      const {
        collisionRect: l
      } = r.current, d = l ? {
        x: l.left,
        y: l.top
      } : Ie;
      this.referenceCoordinates || (this.referenceCoordinates = d);
      const u = s(t, {
        active: n,
        context: r.current,
        currentCoordinates: d
      });
      if (u) {
        const h = Qt(u, d), f = {
          x: 0,
          y: 0
        }, {
          scrollableAncestors: g
        } = r.current;
        for (const _ of g) {
          const m = t.code, {
            isTop: E,
            isRight: w,
            isLeft: y,
            isBottom: R,
            maxScroll: x,
            minScroll: C
          } = Ei(_), A = ha(_), D = {
            x: Math.min(m === q.Right ? A.right - A.width / 2 : A.right, Math.max(m === q.Right ? A.left : A.left + A.width / 2, u.x)),
            y: Math.min(m === q.Down ? A.bottom - A.height / 2 : A.bottom, Math.max(m === q.Down ? A.top : A.top + A.height / 2, u.y))
          }, I = m === q.Right && !w || m === q.Left && !y, B = m === q.Down && !R || m === q.Up && !E;
          if (I && D.x !== u.x) {
            const $ = _.scrollLeft + h.x, G = m === q.Right && $ <= x.x || m === q.Left && $ >= C.x;
            if (G && !h.y) {
              _.scrollTo({
                left: $,
                behavior: a
              });
              return;
            }
            G ? f.x = _.scrollLeft - $ : f.x = m === q.Right ? _.scrollLeft - x.x : _.scrollLeft - C.x, f.x && _.scrollBy({
              left: -f.x,
              behavior: a
            });
            break;
          } else if (B && D.y !== u.y) {
            const $ = _.scrollTop + h.y, G = m === q.Down && $ <= x.y || m === q.Up && $ >= C.y;
            if (G && !h.x) {
              _.scrollTo({
                top: $,
                behavior: a
              });
              return;
            }
            G ? f.y = _.scrollTop - $ : f.y = m === q.Down ? _.scrollTop - x.y : _.scrollTop - C.y, f.y && _.scrollBy({
              top: -f.y,
              behavior: a
            });
            break;
          }
        }
        this.handleMove(t, _t(Qt(u, this.referenceCoordinates), f));
      }
    }
  }
  handleMove(t, n) {
    const {
      onMove: r
    } = this.props;
    t.preventDefault(), r(n);
  }
  handleEnd(t) {
    const {
      onEnd: n
    } = this.props;
    t.preventDefault(), this.detach(), n();
  }
  handleCancel(t) {
    const {
      onCancel: n
    } = this.props;
    t.preventDefault(), this.detach(), n();
  }
  detach() {
    this.listeners.removeAll(), this.windowListeners.removeAll();
  }
}
Er.activators = [{
  eventName: "onKeyDown",
  handler: (e, t, n) => {
    let {
      keyboardCodes: r = ki,
      onActivation: o
    } = t, {
      active: i
    } = n;
    const {
      code: s
    } = e.nativeEvent;
    if (r.start.includes(s)) {
      const a = i.activatorNode.current;
      return a && e.target !== a ? !1 : (e.preventDefault(), o?.({
        event: e.nativeEvent
      }), !0);
    }
    return !1;
  }
}];
function ro(e) {
  return !!(e && "distance" in e);
}
function oo(e) {
  return !!(e && "delay" in e);
}
class Ar {
  constructor(t, n, r) {
    var o;
    r === void 0 && (r = ya(t.event.target)), this.props = void 0, this.events = void 0, this.autoScrollEnabled = !0, this.document = void 0, this.activated = !1, this.initialCoordinates = void 0, this.timeoutId = null, this.listeners = void 0, this.documentListeners = void 0, this.windowListeners = void 0, this.props = t, this.events = n;
    const {
      event: i
    } = t, {
      target: s
    } = i;
    this.props = t, this.events = n, this.document = xt(s), this.documentListeners = new Ut(this.document), this.listeners = new Ut(r), this.windowListeners = new Ut(ge(s)), this.initialCoordinates = (o = yn(i)) != null ? o : Ie, this.handleStart = this.handleStart.bind(this), this.handleMove = this.handleMove.bind(this), this.handleEnd = this.handleEnd.bind(this), this.handleCancel = this.handleCancel.bind(this), this.handleKeydown = this.handleKeydown.bind(this), this.removeTextSelection = this.removeTextSelection.bind(this), this.attach();
  }
  attach() {
    const {
      events: t,
      props: {
        options: {
          activationConstraint: n,
          bypassActivationConstraint: r
        }
      }
    } = this;
    if (this.listeners.add(t.move.name, this.handleMove, {
      passive: !1
    }), this.listeners.add(t.end.name, this.handleEnd), t.cancel && this.listeners.add(t.cancel.name, this.handleCancel), this.windowListeners.add(Ce.Resize, this.handleCancel), this.windowListeners.add(Ce.DragStart, no), this.windowListeners.add(Ce.VisibilityChange, this.handleCancel), this.windowListeners.add(Ce.ContextMenu, no), this.documentListeners.add(Ce.Keydown, this.handleKeydown), n) {
      if (r != null && r({
        event: this.props.event,
        activeNode: this.props.activeNode,
        options: this.props.options
      }))
        return this.handleStart();
      if (oo(n)) {
        this.timeoutId = setTimeout(this.handleStart, n.delay), this.handlePending(n);
        return;
      }
      if (ro(n)) {
        this.handlePending(n);
        return;
      }
    }
    this.handleStart();
  }
  detach() {
    this.listeners.removeAll(), this.windowListeners.removeAll(), setTimeout(this.documentListeners.removeAll, 50), this.timeoutId !== null && (clearTimeout(this.timeoutId), this.timeoutId = null);
  }
  handlePending(t, n) {
    const {
      active: r,
      onPending: o
    } = this.props;
    o(r, t, this.initialCoordinates, n);
  }
  handleStart() {
    const {
      initialCoordinates: t
    } = this, {
      onStart: n
    } = this.props;
    t && (this.activated = !0, this.documentListeners.add(Ce.Click, ba, {
      capture: !0
    }), this.removeTextSelection(), this.documentListeners.add(Ce.SelectionChange, this.removeTextSelection), n(t));
  }
  handleMove(t) {
    var n;
    const {
      activated: r,
      initialCoordinates: o,
      props: i
    } = this, {
      onMove: s,
      options: {
        activationConstraint: a
      }
    } = i;
    if (!o)
      return;
    const c = (n = yn(t)) != null ? n : Ie, l = Qt(o, c);
    if (!r && a) {
      if (ro(a)) {
        if (a.tolerance != null && Yn(l, a.tolerance))
          return this.handleCancel();
        if (Yn(l, a.distance))
          return this.handleStart();
      }
      if (oo(a) && Yn(l, a.tolerance))
        return this.handleCancel();
      this.handlePending(a, l);
      return;
    }
    t.cancelable && t.preventDefault(), s(c);
  }
  handleEnd() {
    const {
      onAbort: t,
      onEnd: n
    } = this.props;
    this.detach(), this.activated || t(this.props.active), n();
  }
  handleCancel() {
    const {
      onAbort: t,
      onCancel: n
    } = this.props;
    this.detach(), this.activated || t(this.props.active), n();
  }
  handleKeydown(t) {
    t.code === q.Esc && this.handleCancel();
  }
  removeTextSelection() {
    var t;
    (t = this.document.getSelection()) == null || t.removeAllRanges();
  }
}
const Sa = {
  cancel: {
    name: "pointercancel"
  },
  move: {
    name: "pointermove"
  },
  end: {
    name: "pointerup"
  }
};
class Cr extends Ar {
  constructor(t) {
    const {
      event: n
    } = t, r = xt(n.target);
    super(t, Sa, r);
  }
}
Cr.activators = [{
  eventName: "onPointerDown",
  handler: (e, t) => {
    let {
      nativeEvent: n
    } = e, {
      onActivation: r
    } = t;
    return !n.isPrimary || n.button !== 0 ? !1 : (r?.({
      event: n
    }), !0);
  }
}];
const wa = {
  move: {
    name: "mousemove"
  },
  end: {
    name: "mouseup"
  }
};
var sr;
(function(e) {
  e[e.RightClick = 2] = "RightClick";
})(sr || (sr = {}));
class Ea extends Ar {
  constructor(t) {
    super(t, wa, xt(t.event.target));
  }
}
Ea.activators = [{
  eventName: "onMouseDown",
  handler: (e, t) => {
    let {
      nativeEvent: n
    } = e, {
      onActivation: r
    } = t;
    return n.button === sr.RightClick ? !1 : (r?.({
      event: n
    }), !0);
  }
}];
const Kn = {
  cancel: {
    name: "touchcancel"
  },
  move: {
    name: "touchmove"
  },
  end: {
    name: "touchend"
  }
};
class Aa extends Ar {
  constructor(t) {
    super(t, Kn);
  }
  static setup() {
    return window.addEventListener(Kn.move.name, t, {
      capture: !1,
      passive: !1
    }), function() {
      window.removeEventListener(Kn.move.name, t);
    };
    function t() {
    }
  }
}
Aa.activators = [{
  eventName: "onTouchStart",
  handler: (e, t) => {
    let {
      nativeEvent: n
    } = e, {
      onActivation: r
    } = t;
    const {
      touches: o
    } = n;
    return o.length > 1 ? !1 : (r?.({
      event: n
    }), !0);
  }
}];
var zt;
(function(e) {
  e[e.Pointer = 0] = "Pointer", e[e.DraggableRect = 1] = "DraggableRect";
})(zt || (zt = {}));
var vn;
(function(e) {
  e[e.TreeOrder = 0] = "TreeOrder", e[e.ReversedTreeOrder = 1] = "ReversedTreeOrder";
})(vn || (vn = {}));
function Ca(e) {
  let {
    acceleration: t,
    activator: n = zt.Pointer,
    canScroll: r,
    draggingRect: o,
    enabled: i,
    interval: s = 5,
    order: a = vn.TreeOrder,
    pointerCoordinates: c,
    scrollableAncestors: l,
    scrollableAncestorRects: d,
    delta: u,
    threshold: h
  } = e;
  const f = xa({
    delta: u,
    disabled: !i
  }), [g, _] = Os(), m = z({
    x: 0,
    y: 0
  }), E = z({
    x: 0,
    y: 0
  }), w = H(() => {
    switch (n) {
      case zt.Pointer:
        return c ? {
          top: c.y,
          bottom: c.y,
          left: c.x,
          right: c.x
        } : null;
      case zt.DraggableRect:
        return o;
    }
  }, [n, o, c]), y = z(null), R = P(() => {
    const C = y.current;
    if (!C)
      return;
    const A = m.current.x * E.current.x, D = m.current.y * E.current.y;
    C.scrollBy(A, D);
  }, []), x = H(() => a === vn.TreeOrder ? [...l].reverse() : l, [a, l]);
  U(
    () => {
      if (!i || !l.length || !w) {
        _();
        return;
      }
      for (const C of x) {
        if (r?.(C) === !1)
          continue;
        const A = l.indexOf(C), D = d[A];
        if (!D)
          continue;
        const {
          direction: I,
          speed: B
        } = pa(C, D, w, t, h);
        for (const $ of ["x", "y"])
          f[$][I[$]] || (B[$] = 0, I[$] = 0);
        if (B.x > 0 || B.y > 0) {
          _(), y.current = C, g(R, s), m.current = B, E.current = I;
          return;
        }
      }
      m.current = {
        x: 0,
        y: 0
      }, E.current = {
        x: 0,
        y: 0
      }, _();
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      t,
      R,
      r,
      _,
      i,
      s,
      // eslint-disable-next-line react-hooks/exhaustive-deps
      JSON.stringify(w),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      JSON.stringify(f),
      g,
      l,
      x,
      d,
      // eslint-disable-next-line react-hooks/exhaustive-deps
      JSON.stringify(h)
    ]
  );
}
const ka = {
  x: {
    [ie.Backward]: !1,
    [ie.Forward]: !1
  },
  y: {
    [ie.Backward]: !1,
    [ie.Forward]: !1
  }
};
function xa(e) {
  let {
    delta: t,
    disabled: n
  } = e;
  const r = _n(t);
  return Gt((o) => {
    if (n || !r || !o)
      return ka;
    const i = {
      x: Math.sign(t.x - r.x),
      y: Math.sign(t.y - r.y)
    };
    return {
      x: {
        [ie.Backward]: o.x[ie.Backward] || i.x === -1,
        [ie.Forward]: o.x[ie.Forward] || i.x === 1
      },
      y: {
        [ie.Backward]: o.y[ie.Backward] || i.y === -1,
        [ie.Forward]: o.y[ie.Forward] || i.y === 1
      }
    };
  }, [n, t, r]);
}
function Ta(e, t) {
  const n = t != null ? e.get(t) : void 0, r = n ? n.node.current : null;
  return Gt((o) => {
    var i;
    return t == null ? null : (i = r ?? o) != null ? i : null;
  }, [r, t]);
}
function Ra(e, t) {
  return H(() => e.reduce((n, r) => {
    const {
      sensor: o
    } = r, i = o.activators.map((s) => ({
      eventName: s.eventName,
      handler: t(s.handler, r)
    }));
    return [...n, ...i];
  }, []), [e, t]);
}
var jt;
(function(e) {
  e[e.Always = 0] = "Always", e[e.BeforeDragging = 1] = "BeforeDragging", e[e.WhileDragging = 2] = "WhileDragging";
})(jt || (jt = {}));
var ar;
(function(e) {
  e.Optimized = "optimized";
})(ar || (ar = {}));
const io = /* @__PURE__ */ new Map();
function Da(e, t) {
  let {
    dragging: n,
    dependencies: r,
    config: o
  } = t;
  const [i, s] = j(null), {
    frequency: a,
    measure: c,
    strategy: l
  } = o, d = z(e), u = m(), h = Ht(u), f = P(function(E) {
    E === void 0 && (E = []), !h.current && s((w) => w === null ? E : w.concat(E.filter((y) => !w.includes(y))));
  }, [h]), g = z(null), _ = Gt((E) => {
    if (u && !n)
      return io;
    if (!E || E === io || d.current !== e || i != null) {
      const w = /* @__PURE__ */ new Map();
      for (let y of e) {
        if (!y)
          continue;
        if (i && i.length > 0 && !i.includes(y.id) && y.rect.current) {
          w.set(y.id, y.rect.current);
          continue;
        }
        const R = y.node.current, x = R ? new wr(c(R), R) : null;
        y.rect.current = x, x && w.set(y.id, x);
      }
      return w;
    }
    return E;
  }, [e, i, n, u, c]);
  return U(() => {
    d.current = e;
  }, [e]), U(
    () => {
      u || f();
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [n, u]
  ), U(
    () => {
      i && i.length > 0 && s(null);
    },
    //eslint-disable-next-line react-hooks/exhaustive-deps
    [JSON.stringify(i)]
  ), U(
    () => {
      u || typeof a != "number" || g.current !== null || (g.current = setTimeout(() => {
        f(), g.current = null;
      }, a));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [a, u, f, ...r]
  ), {
    droppableRects: _,
    measureDroppableContainers: f,
    measuringScheduled: i != null
  };
  function m() {
    switch (l) {
      case jt.Always:
        return !1;
      case jt.BeforeDragging:
        return n;
      default:
        return !n;
    }
  }
}
function kr(e, t) {
  return Gt((n) => e ? n || (typeof t == "function" ? t(e) : e) : null, [t, e]);
}
function Na(e, t) {
  return kr(e, t);
}
function Ma(e) {
  let {
    callback: t,
    disabled: n
  } = e;
  const r = Dn(t), o = H(() => {
    if (n || typeof window > "u" || typeof window.MutationObserver > "u")
      return;
    const {
      MutationObserver: i
    } = window;
    return new i(r);
  }, [r, n]);
  return U(() => () => o?.disconnect(), [o]), o;
}
function In(e) {
  let {
    callback: t,
    disabled: n
  } = e;
  const r = Dn(t), o = H(
    () => {
      if (n || typeof window > "u" || typeof window.ResizeObserver > "u")
        return;
      const {
        ResizeObserver: i
      } = window;
      return new i(r);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [n]
  );
  return U(() => () => o?.disconnect(), [o]), o;
}
function Ia(e) {
  return new wr(Tt(e), e);
}
function so(e, t, n) {
  t === void 0 && (t = Ia);
  const [r, o] = j(null);
  function i() {
    o((c) => {
      if (!e)
        return null;
      if (e.isConnected === !1) {
        var l;
        return (l = c ?? n) != null ? l : null;
      }
      const d = t(e);
      return JSON.stringify(c) === JSON.stringify(d) ? c : d;
    });
  }
  const s = Ma({
    callback(c) {
      if (e)
        for (const l of c) {
          const {
            type: d,
            target: u
          } = l;
          if (d === "childList" && u instanceof HTMLElement && u.contains(e)) {
            i();
            break;
          }
        }
    }
  }), a = In({
    callback: i
  });
  return Me(() => {
    i(), e ? (a?.observe(e), s?.observe(document.body, {
      childList: !0,
      subtree: !0
    })) : (a?.disconnect(), s?.disconnect());
  }, [e]), r;
}
function La(e) {
  const t = kr(e);
  return _i(e, t);
}
const ao = [];
function $a(e) {
  const t = z(e), n = Gt((r) => e ? r && r !== ao && e && t.current && e.parentNode === t.current.parentNode ? r : Mn(e) : ao, [e]);
  return U(() => {
    t.current = e;
  }, [e]), n;
}
function Pa(e) {
  const [t, n] = j(null), r = z(e), o = P((i) => {
    const s = Vn(i.target);
    s && n((a) => a ? (a.set(s, ir(s)), new Map(a)) : null);
  }, []);
  return U(() => {
    const i = r.current;
    if (e !== i) {
      s(i);
      const a = e.map((c) => {
        const l = Vn(c);
        return l ? (l.addEventListener("scroll", o, {
          passive: !0
        }), [l, ir(l)]) : null;
      }).filter((c) => c != null);
      n(a.length ? new Map(a) : null), r.current = e;
    }
    return () => {
      s(e), s(i);
    };
    function s(a) {
      a.forEach((c) => {
        const l = Vn(c);
        l?.removeEventListener("scroll", o);
      });
    }
  }, [o, e]), H(() => e.length ? t ? Array.from(t.values()).reduce((i, s) => _t(i, s), Ie) : Ai(e) : Ie, [e, t]);
}
function co(e, t) {
  t === void 0 && (t = []);
  const n = z(null);
  return U(
    () => {
      n.current = null;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    t
  ), U(() => {
    const r = e !== Ie;
    r && !n.current && (n.current = e), !r && n.current && (n.current = null);
  }, [e]), n.current ? Qt(e, n.current) : Ie;
}
function Fa(e) {
  U(
    () => {
      if (!Rn)
        return;
      const t = e.map((n) => {
        let {
          sensor: r
        } = n;
        return r.setup == null ? void 0 : r.setup();
      });
      return () => {
        for (const n of t)
          n?.();
      };
    },
    // TO-DO: Sensors length could theoretically change which would not be a valid dependency
    // eslint-disable-next-line react-hooks/exhaustive-deps
    e.map((t) => {
      let {
        sensor: n
      } = t;
      return n;
    })
  );
}
function Oa(e, t) {
  return H(() => e.reduce((n, r) => {
    let {
      eventName: o,
      handler: i
    } = r;
    return n[o] = (s) => {
      i(s, t);
    }, n;
  }, {}), [e, t]);
}
function xi(e) {
  return H(() => e ? la(e) : null, [e]);
}
const lo = [];
function Ua(e, t) {
  t === void 0 && (t = Tt);
  const [n] = e, r = xi(n ? ge(n) : null), [o, i] = j(lo);
  function s() {
    i(() => e.length ? e.map((c) => wi(c) ? r : new wr(t(c), c)) : lo);
  }
  const a = In({
    callback: s
  });
  return Me(() => {
    a?.disconnect(), s(), e.forEach((c) => a?.observe(c));
  }, [e]), o;
}
function Ti(e) {
  if (!e)
    return null;
  if (e.children.length > 1)
    return e;
  const t = e.children[0];
  return Xt(t) ? t : e;
}
function za(e) {
  let {
    measure: t
  } = e;
  const [n, r] = j(null), o = P((l) => {
    for (const {
      target: d
    } of l)
      if (Xt(d)) {
        r((u) => {
          const h = t(d);
          return u ? {
            ...u,
            width: h.width,
            height: h.height
          } : h;
        });
        break;
      }
  }, [t]), i = In({
    callback: o
  }), s = P((l) => {
    const d = Ti(l);
    i?.disconnect(), d && i?.observe(d), r(d ? t(d) : null);
  }, [t, i]), [a, c] = mn(s);
  return H(() => ({
    nodeRef: a,
    rect: n,
    setRef: c
  }), [n, a, c]);
}
const Ba = [{
  sensor: Cr,
  options: {}
}, {
  sensor: Er,
  options: {}
}], qa = {
  current: {}
}, fn = {
  draggable: {
    measure: to
  },
  droppable: {
    measure: to,
    strategy: jt.WhileDragging,
    frequency: ar.Optimized
  },
  dragOverlay: {
    measure: Tt
  }
};
class Bt extends Map {
  get(t) {
    var n;
    return t != null && (n = super.get(t)) != null ? n : void 0;
  }
  toArray() {
    return Array.from(this.values());
  }
  getEnabled() {
    return this.toArray().filter((t) => {
      let {
        disabled: n
      } = t;
      return !n;
    });
  }
  getNodeFor(t) {
    var n, r;
    return (n = (r = this.get(t)) == null ? void 0 : r.node.current) != null ? n : void 0;
  }
}
const Ha = {
  activatorEvent: null,
  active: null,
  activeNode: null,
  activeNodeRect: null,
  collisions: null,
  containerNodeRect: null,
  draggableNodes: /* @__PURE__ */ new Map(),
  droppableRects: /* @__PURE__ */ new Map(),
  droppableContainers: /* @__PURE__ */ new Bt(),
  over: null,
  dragOverlay: {
    nodeRef: {
      current: null
    },
    rect: null,
    setRef: bn
  },
  scrollableAncestors: [],
  scrollableAncestorRects: [],
  measuringConfiguration: fn,
  measureDroppableContainers: bn,
  windowRect: null,
  measuringScheduled: !1
}, Ri = {
  activatorEvent: null,
  activators: [],
  active: null,
  activeNodeRect: null,
  ariaDescribedById: {
    draggable: ""
  },
  dispatch: bn,
  draggableNodes: /* @__PURE__ */ new Map(),
  over: null,
  measureDroppableContainers: bn
}, Zt = /* @__PURE__ */ Et(Ri), Di = /* @__PURE__ */ Et(Ha);
function Qa() {
  return {
    draggable: {
      active: null,
      initialCoordinates: {
        x: 0,
        y: 0
      },
      nodes: /* @__PURE__ */ new Map(),
      translate: {
        x: 0,
        y: 0
      }
    },
    droppable: {
      containers: new Bt()
    }
  };
}
function ja(e, t) {
  switch (t.type) {
    case re.DragStart:
      return {
        ...e,
        draggable: {
          ...e.draggable,
          initialCoordinates: t.initialCoordinates,
          active: t.active
        }
      };
    case re.DragMove:
      return e.draggable.active == null ? e : {
        ...e,
        draggable: {
          ...e.draggable,
          translate: {
            x: t.coordinates.x - e.draggable.initialCoordinates.x,
            y: t.coordinates.y - e.draggable.initialCoordinates.y
          }
        }
      };
    case re.DragEnd:
    case re.DragCancel:
      return {
        ...e,
        draggable: {
          ...e.draggable,
          active: null,
          initialCoordinates: {
            x: 0,
            y: 0
          },
          translate: {
            x: 0,
            y: 0
          }
        }
      };
    case re.RegisterDroppable: {
      const {
        element: n
      } = t, {
        id: r
      } = n, o = new Bt(e.droppable.containers);
      return o.set(r, n), {
        ...e,
        droppable: {
          ...e.droppable,
          containers: o
        }
      };
    }
    case re.SetDroppableDisabled: {
      const {
        id: n,
        key: r,
        disabled: o
      } = t, i = e.droppable.containers.get(n);
      if (!i || r !== i.key)
        return e;
      const s = new Bt(e.droppable.containers);
      return s.set(n, {
        ...i,
        disabled: o
      }), {
        ...e,
        droppable: {
          ...e.droppable,
          containers: s
        }
      };
    }
    case re.UnregisterDroppable: {
      const {
        id: n,
        key: r
      } = t, o = e.droppable.containers.get(n);
      if (!o || r !== o.key)
        return e;
      const i = new Bt(e.droppable.containers);
      return i.delete(n), {
        ...e,
        droppable: {
          ...e.droppable,
          containers: i
        }
      };
    }
    default:
      return e;
  }
}
function Va(e) {
  let {
    disabled: t
  } = e;
  const {
    active: n,
    activatorEvent: r,
    draggableNodes: o
  } = qe(Zt), i = _n(r), s = _n(n?.id);
  return U(() => {
    if (!t && !r && i && s != null) {
      if (!Nn(i) || document.activeElement === i.target)
        return;
      const a = o.get(s);
      if (!a)
        return;
      const {
        activatorNode: c,
        node: l
      } = a;
      if (!c.current && !l.current)
        return;
      requestAnimationFrame(() => {
        for (const d of [c.current, l.current]) {
          if (!d)
            continue;
          const u = Bs(d);
          if (u) {
            u.focus();
            break;
          }
        }
      });
    }
  }, [r, t, o, s, i]), null;
}
function Ni(e, t) {
  let {
    transform: n,
    ...r
  } = t;
  return e != null && e.length ? e.reduce((o, i) => i({
    transform: o,
    ...r
  }), n) : n;
}
function Ya(e) {
  return H(
    () => ({
      draggable: {
        ...fn.draggable,
        ...e?.draggable
      },
      droppable: {
        ...fn.droppable,
        ...e?.droppable
      },
      dragOverlay: {
        ...fn.dragOverlay,
        ...e?.dragOverlay
      }
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [e?.draggable, e?.droppable, e?.dragOverlay]
  );
}
function Ka(e) {
  let {
    activeNode: t,
    measure: n,
    initialRect: r,
    config: o = !0
  } = e;
  const i = z(!1), {
    x: s,
    y: a
  } = typeof o == "boolean" ? {
    x: o,
    y: o
  } : o;
  Me(() => {
    if (!s && !a || !t) {
      i.current = !1;
      return;
    }
    if (i.current || !r)
      return;
    const l = t?.node.current;
    if (!l || l.isConnected === !1)
      return;
    const d = n(l), u = _i(d, r);
    if (s || (u.x = 0), a || (u.y = 0), i.current = !0, Math.abs(u.x) > 0 || Math.abs(u.y) > 0) {
      const h = bi(l);
      h && h.scrollBy({
        top: u.y,
        left: u.x
      });
    }
  }, [t, s, a, r, n]);
}
const Ln = /* @__PURE__ */ Et({
  ...Ie,
  scaleX: 1,
  scaleY: 1
});
var nt;
(function(e) {
  e[e.Uninitialized = 0] = "Uninitialized", e[e.Initializing = 1] = "Initializing", e[e.Initialized = 2] = "Initialized";
})(nt || (nt = {}));
const Wa = /* @__PURE__ */ ri(function(t) {
  var n, r, o, i;
  let {
    id: s,
    accessibility: a,
    autoScroll: c = !0,
    children: l,
    sensors: d = Ba,
    collisionDetection: u = ra,
    measuring: h,
    modifiers: f,
    ...g
  } = t;
  const _ = xn(ja, void 0, Qa), [m, E] = _, [w, y] = Ys(), [R, x] = j(nt.Uninitialized), C = R === nt.Initialized, {
    draggable: {
      active: A,
      nodes: D,
      translate: I
    },
    droppable: {
      containers: B
    }
  } = m, $ = A != null ? D.get(A) : null, G = z({
    initial: null,
    translated: null
  }), ce = H(() => {
    var fe;
    return A != null ? {
      id: A,
      // It's possible for the active node to unmount while dragging
      data: (fe = $?.data) != null ? fe : qa,
      rect: G
    } : null;
  }, [A, $]), pe = z(null), [Le, He] = j(null), [te, Qe] = j(null), le = Ht(g, Object.values(g)), $e = Jt("DndDescribedBy", s), je = H(() => B.getEnabled(), [B]), X = Ya(h), {
    droppableRects: se,
    measureDroppableContainers: Ee,
    measuringScheduled: Pe
  } = Da(je, {
    dragging: C,
    dependencies: [I.x, I.y],
    config: X.droppable
  }), ne = Ta(D, A), xe = H(() => te ? yn(te) : null, [te]), v = Bn(), S = Na(ne, X.draggable.measure);
  Ka({
    activeNode: A != null ? D.get(A) : null,
    config: v.layoutShiftCompensation,
    initialRect: S,
    measure: X.draggable.measure
  });
  const p = so(ne, X.draggable.measure, S), T = so(ne ? ne.parentElement : null), k = z({
    activatorEvent: null,
    active: null,
    activeNode: ne,
    collisionRect: null,
    collisions: null,
    droppableRects: se,
    draggableNodes: D,
    draggingNode: null,
    draggingNodeRect: null,
    droppableContainers: B,
    over: null,
    scrollableAncestors: [],
    scrollAdjustedTranslate: null
  }), N = B.getNodeFor((n = k.current.over) == null ? void 0 : n.id), M = za({
    measure: X.dragOverlay.measure
  }), L = (r = M.nodeRef.current) != null ? r : ne, Q = C ? (o = M.rect) != null ? o : p : null, ue = !!(M.nodeRef.current && M.rect), de = La(ue ? null : p), ee = xi(L ? ge(L) : null), V = $a(C ? N ?? ne : null), _e = Ua(V), O = Ni(f, {
    transform: {
      x: I.x - de.x,
      y: I.y - de.y,
      scaleX: 1,
      scaleY: 1
    },
    activatorEvent: te,
    active: ce,
    activeNodeRect: p,
    containerNodeRect: T,
    draggingNodeRect: Q,
    over: k.current.over,
    overlayNodeRect: M.rect,
    scrollableAncestors: V,
    scrollableAncestorRects: _e,
    windowRect: ee
  }), oe = xe ? _t(xe, I) : null, Te = Pa(V), Rt = co(Te), Fn = co(Te, [p]), Ge = _t(O, Rt), Je = Q ? sa(Q, O) : null, Ve = ce && Je ? u({
    active: ce,
    collisionRect: Je,
    droppableRects: se,
    droppableContainers: je,
    pointerCoordinates: oe
  }) : null, st = mi(Ve, "id"), [Fe, at] = j(null), On = ue ? O : _t(O, Fn), nn = oa(On, (i = Fe?.rect) != null ? i : null, p), pt = z(null), ct = P(
    (fe, ye) => {
      let {
        sensor: be,
        options: Ze
      } = ye;
      if (pe.current == null)
        return;
      const Ae = D.get(pe.current);
      if (!Ae)
        return;
      const ve = fe.nativeEvent, Oe = new be({
        active: pe.current,
        activeNode: Ae,
        event: ve,
        options: Ze,
        // Sensors need to be instantiated with refs for arguments that change over time
        // otherwise they are frozen in time with the stale arguments
        context: k,
        onAbort(ae) {
          if (!D.get(ae))
            return;
          const {
            onDragAbort: Ue
          } = le.current, Ye = {
            id: ae
          };
          Ue?.(Ye), w({
            type: "onDragAbort",
            event: Ye
          });
        },
        onPending(ae, et, Ue, Ye) {
          if (!D.get(ae))
            return;
          const {
            onDragPending: Mt
          } = le.current, tt = {
            id: ae,
            constraint: et,
            initialCoordinates: Ue,
            offset: Ye
          };
          Mt?.(tt), w({
            type: "onDragPending",
            event: tt
          });
        },
        onStart(ae) {
          const et = pe.current;
          if (et == null)
            return;
          const Ue = D.get(et);
          if (!Ue)
            return;
          const {
            onDragStart: Ye
          } = le.current, Nt = {
            activatorEvent: ve,
            active: {
              id: et,
              data: Ue.data,
              rect: G
            }
          };
          Ft(() => {
            Ye?.(Nt), x(nt.Initializing), E({
              type: re.DragStart,
              initialCoordinates: ae,
              active: et
            }), w({
              type: "onDragStart",
              event: Nt
            }), He(pt.current), Qe(ve);
          });
        },
        onMove(ae) {
          E({
            type: re.DragMove,
            coordinates: ae
          });
        },
        onEnd: ht(re.DragEnd),
        onCancel: ht(re.DragCancel)
      });
      pt.current = Oe;
      function ht(ae) {
        return async function() {
          const {
            active: Ue,
            collisions: Ye,
            over: Nt,
            scrollAdjustedTranslate: Mt
          } = k.current;
          let tt = null;
          if (Ue && Mt) {
            const {
              cancelDrop: It
            } = le.current;
            tt = {
              activatorEvent: ve,
              active: Ue,
              collisions: Ye,
              delta: Mt,
              over: Nt
            }, ae === re.DragEnd && typeof It == "function" && await Promise.resolve(It(tt)) && (ae = re.DragCancel);
          }
          pe.current = null, Ft(() => {
            E({
              type: ae
            }), x(nt.Uninitialized), at(null), He(null), Qe(null), pt.current = null;
            const It = ae === re.DragEnd ? "onDragEnd" : "onDragCancel";
            if (tt) {
              const qn = le.current[It];
              qn?.(tt), w({
                type: It,
                event: tt
              });
            }
          });
        };
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [D]
  ), Dt = P((fe, ye) => (be, Ze) => {
    const Ae = be.nativeEvent, ve = D.get(Ze);
    if (
      // Another sensor is already instantiating
      pe.current !== null || // No active draggable
      !ve || // Event has already been captured
      Ae.dndKit || Ae.defaultPrevented
    )
      return;
    const Oe = {
      active: ve
    };
    fe(be, ye.options, Oe) === !0 && (Ae.dndKit = {
      capturedBy: ye.sensor
    }, pe.current = Ze, ct(be, ye));
  }, [D, ct]), Un = Ra(d, Dt);
  Fa(d), Me(() => {
    p && R === nt.Initializing && x(nt.Initialized);
  }, [p, R]), U(
    () => {
      const {
        onDragMove: fe
      } = le.current, {
        active: ye,
        activatorEvent: be,
        collisions: Ze,
        over: Ae
      } = k.current;
      if (!ye || !be)
        return;
      const ve = {
        active: ye,
        activatorEvent: be,
        collisions: Ze,
        delta: {
          x: Ge.x,
          y: Ge.y
        },
        over: Ae
      };
      Ft(() => {
        fe?.(ve), w({
          type: "onDragMove",
          event: ve
        });
      });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [Ge.x, Ge.y]
  ), U(
    () => {
      const {
        active: fe,
        activatorEvent: ye,
        collisions: be,
        droppableContainers: Ze,
        scrollAdjustedTranslate: Ae
      } = k.current;
      if (!fe || pe.current == null || !ye || !Ae)
        return;
      const {
        onDragOver: ve
      } = le.current, Oe = Ze.get(st), ht = Oe && Oe.rect.current ? {
        id: Oe.id,
        rect: Oe.rect.current,
        data: Oe.data,
        disabled: Oe.disabled
      } : null, ae = {
        active: fe,
        activatorEvent: ye,
        collisions: be,
        delta: {
          x: Ae.x,
          y: Ae.y
        },
        over: ht
      };
      Ft(() => {
        at(ht), ve?.(ae), w({
          type: "onDragOver",
          event: ae
        });
      });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [st]
  ), Me(() => {
    k.current = {
      activatorEvent: te,
      active: ce,
      activeNode: ne,
      collisionRect: Je,
      collisions: Ve,
      droppableRects: se,
      draggableNodes: D,
      draggingNode: L,
      draggingNodeRect: Q,
      droppableContainers: B,
      over: Fe,
      scrollableAncestors: V,
      scrollAdjustedTranslate: Ge
    }, G.current = {
      initial: Q,
      translated: Je
    };
  }, [ce, ne, Ve, Je, D, L, Q, se, B, Fe, V, Ge]), Ca({
    ...v,
    delta: I,
    draggingRect: Je,
    pointerCoordinates: oe,
    scrollableAncestors: V,
    scrollableAncestorRects: _e
  });
  const zn = H(() => ({
    active: ce,
    activeNode: ne,
    activeNodeRect: p,
    activatorEvent: te,
    collisions: Ve,
    containerNodeRect: T,
    dragOverlay: M,
    draggableNodes: D,
    droppableContainers: B,
    droppableRects: se,
    over: Fe,
    measureDroppableContainers: Ee,
    scrollableAncestors: V,
    scrollableAncestorRects: _e,
    measuringConfiguration: X,
    measuringScheduled: Pe,
    windowRect: ee
  }), [ce, ne, p, te, Ve, T, M, D, B, se, Fe, Ee, V, _e, X, Pe, ee]), rn = H(() => ({
    activatorEvent: te,
    activators: Un,
    active: ce,
    activeNodeRect: p,
    ariaDescribedById: {
      draggable: $e
    },
    dispatch: E,
    draggableNodes: D,
    over: Fe,
    measureDroppableContainers: Ee
  }), [te, Un, ce, p, E, $e, D, Fe, Ee]);
  return Z.createElement(pi.Provider, {
    value: y
  }, Z.createElement(Zt.Provider, {
    value: rn
  }, Z.createElement(Di.Provider, {
    value: zn
  }, Z.createElement(Ln.Provider, {
    value: nn
  }, l)), Z.createElement(Va, {
    disabled: a?.restoreFocus === !1
  })), Z.createElement(Xs, {
    ...a,
    hiddenTextDescribedById: $e
  }));
  function Bn() {
    const fe = Le?.autoScrollEnabled === !1, ye = typeof c == "object" ? c.enabled === !1 : c === !1, be = C && !fe && !ye;
    return typeof c == "object" ? {
      ...c,
      enabled: be
    } : {
      enabled: be
    };
  }
}), Xa = /* @__PURE__ */ Et(null), uo = "button", Ga = "Draggable";
function Ja(e) {
  let {
    id: t,
    data: n,
    disabled: r = !1,
    attributes: o
  } = e;
  const i = Jt(Ga), {
    activators: s,
    activatorEvent: a,
    active: c,
    activeNodeRect: l,
    ariaDescribedById: d,
    draggableNodes: u,
    over: h
  } = qe(Zt), {
    role: f = uo,
    roleDescription: g = "draggable",
    tabIndex: _ = 0
  } = o ?? {}, m = c?.id === t, E = qe(m ? Ln : Xa), [w, y] = mn(), [R, x] = mn(), C = Oa(s, t), A = Ht(n);
  Me(
    () => (u.set(t, {
      id: t,
      key: i,
      node: w,
      activatorNode: R,
      data: A
    }), () => {
      const I = u.get(t);
      I && I.key === i && u.delete(t);
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [u, t]
  );
  const D = H(() => ({
    role: f,
    tabIndex: _,
    "aria-disabled": r,
    "aria-pressed": m && f === uo ? !0 : void 0,
    "aria-roledescription": g,
    "aria-describedby": d.draggable
  }), [r, f, _, m, g, d.draggable]);
  return {
    active: c,
    activatorEvent: a,
    activeNodeRect: l,
    attributes: D,
    isDragging: m,
    listeners: r ? void 0 : C,
    node: w,
    over: h,
    setNodeRef: y,
    setActivatorNodeRef: x,
    transform: E
  };
}
function Mi() {
  return qe(Di);
}
const Za = "Droppable", ec = {
  timeout: 25
};
function tc(e) {
  let {
    data: t,
    disabled: n = !1,
    id: r,
    resizeObserverConfig: o
  } = e;
  const i = Jt(Za), {
    active: s,
    dispatch: a,
    over: c,
    measureDroppableContainers: l
  } = qe(Zt), d = z({
    disabled: n
  }), u = z(!1), h = z(null), f = z(null), {
    disabled: g,
    updateMeasurementsFor: _,
    timeout: m
  } = {
    ...ec,
    ...o
  }, E = Ht(_ ?? r), w = P(
    () => {
      if (!u.current) {
        u.current = !0;
        return;
      }
      f.current != null && clearTimeout(f.current), f.current = setTimeout(() => {
        l(Array.isArray(E.current) ? E.current : [E.current]), f.current = null;
      }, m);
    },
    //eslint-disable-next-line react-hooks/exhaustive-deps
    [m]
  ), y = In({
    callback: w,
    disabled: g || !s
  }), R = P((D, I) => {
    y && (I && (y.unobserve(I), u.current = !1), D && y.observe(D));
  }, [y]), [x, C] = mn(R), A = Ht(t);
  return U(() => {
    !y || !x.current || (y.disconnect(), u.current = !1, y.observe(x.current));
  }, [x, y]), U(
    () => (a({
      type: re.RegisterDroppable,
      element: {
        id: r,
        key: i,
        disabled: n,
        node: x,
        rect: h,
        data: A
      }
    }), () => a({
      type: re.UnregisterDroppable,
      key: i,
      id: r
    })),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [r]
  ), U(() => {
    n !== d.current.disabled && (a({
      type: re.SetDroppableDisabled,
      id: r,
      key: i,
      disabled: n
    }), d.current.disabled = n);
  }, [r, i, n, a]), {
    active: s,
    rect: h,
    isOver: c?.id === r,
    node: x,
    over: c,
    setNodeRef: C
  };
}
function nc(e) {
  let {
    animation: t,
    children: n
  } = e;
  const [r, o] = j(null), [i, s] = j(null), a = _n(n);
  return !n && !r && a && o(a), Me(() => {
    if (!i)
      return;
    const c = r?.key, l = r?.props.id;
    if (c == null || l == null) {
      o(null);
      return;
    }
    Promise.resolve(t(l, i)).then(() => {
      o(null);
    });
  }, [t, r, i]), Z.createElement(Z.Fragment, null, n, r ? ui(r, {
    ref: s
  }) : null);
}
const rc = {
  x: 0,
  y: 0,
  scaleX: 1,
  scaleY: 1
};
function oc(e) {
  let {
    children: t
  } = e;
  return Z.createElement(Zt.Provider, {
    value: Ri
  }, Z.createElement(Ln.Provider, {
    value: rc
  }, t));
}
const ic = {
  position: "fixed",
  touchAction: "none"
}, sc = (e) => Nn(e) ? "transform 250ms ease" : void 0, ac = /* @__PURE__ */ oi((e, t) => {
  let {
    as: n,
    activatorEvent: r,
    adjustScale: o,
    children: i,
    className: s,
    rect: a,
    style: c,
    transform: l,
    transition: d = sc
  } = e;
  if (!a)
    return null;
  const u = o ? l : {
    ...l,
    scaleX: 1,
    scaleY: 1
  }, h = {
    ...ic,
    width: a.width,
    height: a.height,
    top: a.top,
    left: a.left,
    transform: it.Transform.toString(u),
    transformOrigin: o && r ? Js(r, a) : void 0,
    transition: typeof d == "function" ? d(r) : d,
    ...c
  };
  return Z.createElement(n, {
    className: s,
    style: h,
    ref: t
  }, i);
}), cc = (e) => (t) => {
  let {
    active: n,
    dragOverlay: r
  } = t;
  const o = {}, {
    styles: i,
    className: s
  } = e;
  if (i != null && i.active)
    for (const [a, c] of Object.entries(i.active))
      c !== void 0 && (o[a] = n.node.style.getPropertyValue(a), n.node.style.setProperty(a, c));
  if (i != null && i.dragOverlay)
    for (const [a, c] of Object.entries(i.dragOverlay))
      c !== void 0 && r.node.style.setProperty(a, c);
  return s != null && s.active && n.node.classList.add(s.active), s != null && s.dragOverlay && r.node.classList.add(s.dragOverlay), function() {
    for (const [c, l] of Object.entries(o))
      n.node.style.setProperty(c, l);
    s != null && s.active && n.node.classList.remove(s.active);
  };
}, lc = (e) => {
  let {
    transform: {
      initial: t,
      final: n
    }
  } = e;
  return [{
    transform: it.Transform.toString(t)
  }, {
    transform: it.Transform.toString(n)
  }];
}, uc = {
  duration: 250,
  easing: "ease",
  keyframes: lc,
  sideEffects: /* @__PURE__ */ cc({
    styles: {
      active: {
        opacity: "0"
      }
    }
  })
};
function dc(e) {
  let {
    config: t,
    draggableNodes: n,
    droppableContainers: r,
    measuringConfiguration: o
  } = e;
  return Dn((i, s) => {
    if (t === null)
      return;
    const a = n.get(i);
    if (!a)
      return;
    const c = a.node.current;
    if (!c)
      return;
    const l = Ti(s);
    if (!l)
      return;
    const {
      transform: d
    } = ge(s).getComputedStyle(s), u = yi(d);
    if (!u)
      return;
    const h = typeof t == "function" ? t : fc(t);
    return Ci(c, o.draggable.measure), h({
      active: {
        id: i,
        data: a.data,
        node: c,
        rect: o.draggable.measure(c)
      },
      draggableNodes: n,
      dragOverlay: {
        node: s,
        rect: o.dragOverlay.measure(l)
      },
      droppableContainers: r,
      measuringConfiguration: o,
      transform: u
    });
  });
}
function fc(e) {
  const {
    duration: t,
    easing: n,
    sideEffects: r,
    keyframes: o
  } = {
    ...uc,
    ...e
  };
  return (i) => {
    let {
      active: s,
      dragOverlay: a,
      transform: c,
      ...l
    } = i;
    if (!t)
      return;
    const d = {
      x: a.rect.left - s.rect.left,
      y: a.rect.top - s.rect.top
    }, u = {
      scaleX: c.scaleX !== 1 ? s.rect.width * c.scaleX / a.rect.width : 1,
      scaleY: c.scaleY !== 1 ? s.rect.height * c.scaleY / a.rect.height : 1
    }, h = {
      x: c.x - d.x,
      y: c.y - d.y,
      ...u
    }, f = o({
      ...l,
      active: s,
      dragOverlay: a,
      transform: {
        initial: c,
        final: h
      }
    }), [g] = f, _ = f[f.length - 1];
    if (JSON.stringify(g) === JSON.stringify(_))
      return;
    const m = r?.({
      active: s,
      dragOverlay: a,
      ...l
    }), E = a.node.animate(f, {
      duration: t,
      easing: n,
      fill: "forwards"
    });
    return new Promise((w) => {
      E.onfinish = () => {
        m?.(), w();
      };
    });
  };
}
let fo = 0;
function pc(e) {
  return H(() => {
    if (e != null)
      return fo++, fo;
  }, [e]);
}
const hc = /* @__PURE__ */ Z.memo((e) => {
  let {
    adjustScale: t = !1,
    children: n,
    dropAnimation: r,
    style: o,
    transition: i,
    modifiers: s,
    wrapperElement: a = "div",
    className: c,
    zIndex: l = 999
  } = e;
  const {
    activatorEvent: d,
    active: u,
    activeNodeRect: h,
    containerNodeRect: f,
    draggableNodes: g,
    droppableContainers: _,
    dragOverlay: m,
    over: E,
    measuringConfiguration: w,
    scrollableAncestors: y,
    scrollableAncestorRects: R,
    windowRect: x
  } = Mi(), C = qe(Ln), A = pc(u?.id), D = Ni(s, {
    activatorEvent: d,
    active: u,
    activeNodeRect: h,
    containerNodeRect: f,
    draggingNodeRect: m.rect,
    over: E,
    overlayNodeRect: m.rect,
    scrollableAncestors: y,
    scrollableAncestorRects: R,
    transform: C,
    windowRect: x
  }), I = kr(h), B = dc({
    config: r,
    draggableNodes: g,
    droppableContainers: _,
    measuringConfiguration: w
  }), $ = I ? m.setRef : void 0;
  return Z.createElement(oc, null, Z.createElement(nc, {
    animation: B
  }, u && A ? Z.createElement(ac, {
    key: A,
    id: u.id,
    ref: $,
    as: a,
    activatorEvent: d,
    adjustScale: t,
    className: c,
    transition: i,
    rect: I,
    style: {
      zIndex: l,
      ...o
    },
    transform: D
  }, n) : null));
});
function xr(e, t, n) {
  const r = e.slice();
  return r.splice(n < 0 ? r.length + n : n, 0, r.splice(t, 1)[0]), r;
}
function gc(e, t) {
  return e.reduce((n, r, o) => {
    const i = t.get(r);
    return i && (n[o] = i), n;
  }, Array(e.length));
}
function sn(e) {
  return e !== null && e >= 0;
}
function mc(e, t) {
  if (e === t)
    return !0;
  if (e.length !== t.length)
    return !1;
  for (let n = 0; n < e.length; n++)
    if (e[n] !== t[n])
      return !1;
  return !0;
}
function _c(e) {
  return typeof e == "boolean" ? {
    draggable: e,
    droppable: e
  } : e;
}
const Ii = (e) => {
  let {
    rects: t,
    activeIndex: n,
    overIndex: r,
    index: o
  } = e;
  const i = xr(t, r, n), s = t[o], a = i[o];
  return !a || !s ? null : {
    x: a.left - s.left,
    y: a.top - s.top,
    scaleX: a.width / s.width,
    scaleY: a.height / s.height
  };
}, an = {
  scaleX: 1,
  scaleY: 1
}, yc = (e) => {
  var t;
  let {
    activeIndex: n,
    activeNodeRect: r,
    index: o,
    rects: i,
    overIndex: s
  } = e;
  const a = (t = i[n]) != null ? t : r;
  if (!a)
    return null;
  if (o === n) {
    const l = i[s];
    return l ? {
      x: 0,
      y: n < s ? l.top + l.height - (a.top + a.height) : l.top - a.top,
      ...an
    } : null;
  }
  const c = bc(i, o, n);
  return o > n && o <= s ? {
    x: 0,
    y: -a.height - c,
    ...an
  } : o < n && o >= s ? {
    x: 0,
    y: a.height + c,
    ...an
  } : {
    x: 0,
    y: 0,
    ...an
  };
};
function bc(e, t, n) {
  const r = e[t], o = e[t - 1], i = e[t + 1];
  return r ? n < t ? o ? r.top - (o.top + o.height) : i ? i.top - (r.top + r.height) : 0 : i ? i.top - (r.top + r.height) : o ? r.top - (o.top + o.height) : 0 : 0;
}
const Li = "Sortable", $i = /* @__PURE__ */ Z.createContext({
  activeIndex: -1,
  containerId: Li,
  disableTransforms: !1,
  items: [],
  overIndex: -1,
  useDragOverlay: !1,
  sortedRects: [],
  strategy: Ii,
  disabled: {
    draggable: !1,
    droppable: !1
  }
});
function vc(e) {
  let {
    children: t,
    id: n,
    items: r,
    strategy: o = Ii,
    disabled: i = !1
  } = e;
  const {
    active: s,
    dragOverlay: a,
    droppableRects: c,
    over: l,
    measureDroppableContainers: d
  } = Mi(), u = Jt(Li, n), h = a.rect !== null, f = H(() => r.map((C) => typeof C == "object" && "id" in C ? C.id : C), [r]), g = s != null, _ = s ? f.indexOf(s.id) : -1, m = l ? f.indexOf(l.id) : -1, E = z(f), w = !mc(f, E.current), y = m !== -1 && _ === -1 || w, R = _c(i);
  Me(() => {
    w && g && d(f);
  }, [w, f, g, d]), U(() => {
    E.current = f;
  }, [f]);
  const x = H(
    () => ({
      activeIndex: _,
      containerId: u,
      disabled: R,
      disableTransforms: y,
      items: f,
      overIndex: m,
      useDragOverlay: h,
      sortedRects: gc(f, c),
      strategy: o
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [_, u, R.draggable, R.droppable, y, f, m, c, h, o]
  );
  return Z.createElement($i.Provider, {
    value: x
  }, t);
}
const Sc = (e) => {
  let {
    id: t,
    items: n,
    activeIndex: r,
    overIndex: o
  } = e;
  return xr(n, r, o).indexOf(t);
}, wc = (e) => {
  let {
    containerId: t,
    isSorting: n,
    wasDragging: r,
    index: o,
    items: i,
    newIndex: s,
    previousItems: a,
    previousContainerId: c,
    transition: l
  } = e;
  return !l || !r || a !== i && o === s ? !1 : n ? !0 : s !== o && t === c;
}, Ec = {
  duration: 200,
  easing: "ease"
}, Pi = "transform", Ac = /* @__PURE__ */ it.Transition.toString({
  property: Pi,
  duration: 0,
  easing: "linear"
}), Cc = {
  roleDescription: "sortable"
};
function kc(e) {
  let {
    disabled: t,
    index: n,
    node: r,
    rect: o
  } = e;
  const [i, s] = j(null), a = z(n);
  return Me(() => {
    if (!t && n !== a.current && r.current) {
      const c = o.current;
      if (c) {
        const l = Tt(r.current, {
          ignoreTransform: !0
        }), d = {
          x: c.left - l.left,
          y: c.top - l.top,
          scaleX: c.width / l.width,
          scaleY: c.height / l.height
        };
        (d.x || d.y) && s(d);
      }
    }
    n !== a.current && (a.current = n);
  }, [t, n, r, o]), U(() => {
    i && s(null);
  }, [i]), i;
}
function xc(e) {
  let {
    animateLayoutChanges: t = wc,
    attributes: n,
    disabled: r,
    data: o,
    getNewIndex: i = Sc,
    id: s,
    strategy: a,
    resizeObserverConfig: c,
    transition: l = Ec
  } = e;
  const {
    items: d,
    containerId: u,
    activeIndex: h,
    disabled: f,
    disableTransforms: g,
    sortedRects: _,
    overIndex: m,
    useDragOverlay: E,
    strategy: w
  } = qe($i), y = Tc(r, f), R = d.indexOf(s), x = H(() => ({
    sortable: {
      containerId: u,
      index: R,
      items: d
    },
    ...o
  }), [u, o, R, d]), C = H(() => d.slice(d.indexOf(s)), [d, s]), {
    rect: A,
    node: D,
    isOver: I,
    setNodeRef: B
  } = tc({
    id: s,
    data: x,
    disabled: y.droppable,
    resizeObserverConfig: {
      updateMeasurementsFor: C,
      ...c
    }
  }), {
    active: $,
    activatorEvent: G,
    activeNodeRect: ce,
    attributes: pe,
    setNodeRef: Le,
    listeners: He,
    isDragging: te,
    over: Qe,
    setActivatorNodeRef: le,
    transform: $e
  } = Ja({
    id: s,
    data: x,
    attributes: {
      ...Cc,
      ...n
    },
    disabled: y.draggable
  }), je = Fs(B, Le), X = !!$, se = X && !g && sn(h) && sn(m), Ee = !E && te, Pe = Ee && se ? $e : null, xe = se ? Pe ?? (a ?? w)({
    rects: _,
    activeNodeRect: ce,
    activeIndex: h,
    overIndex: m,
    index: R
  }) : null, v = sn(h) && sn(m) ? i({
    id: s,
    items: d,
    activeIndex: h,
    overIndex: m
  }) : R, S = $?.id, p = z({
    activeId: S,
    items: d,
    newIndex: v,
    containerId: u
  }), T = d !== p.current.items, k = t({
    active: $,
    containerId: u,
    isDragging: te,
    isSorting: X,
    id: s,
    index: R,
    items: d,
    newIndex: p.current.newIndex,
    previousItems: p.current.items,
    previousContainerId: p.current.containerId,
    transition: l,
    wasDragging: p.current.activeId != null
  }), N = kc({
    disabled: !k,
    index: R,
    node: D,
    rect: A
  });
  return U(() => {
    X && p.current.newIndex !== v && (p.current.newIndex = v), u !== p.current.containerId && (p.current.containerId = u), d !== p.current.items && (p.current.items = d);
  }, [X, v, u, d]), U(() => {
    if (S === p.current.activeId)
      return;
    if (S != null && p.current.activeId == null) {
      p.current.activeId = S;
      return;
    }
    const L = setTimeout(() => {
      p.current.activeId = S;
    }, 50);
    return () => clearTimeout(L);
  }, [S]), {
    active: $,
    activeIndex: h,
    attributes: pe,
    data: x,
    rect: A,
    index: R,
    newIndex: v,
    items: d,
    isOver: I,
    isSorting: X,
    isDragging: te,
    listeners: He,
    node: D,
    overIndex: m,
    over: Qe,
    setNodeRef: je,
    setActivatorNodeRef: le,
    setDroppableNodeRef: B,
    setDraggableNodeRef: Le,
    transform: N ?? xe,
    transition: M()
  };
  function M() {
    if (
      // Temporarily disable transitions for a single frame to set up derived transforms
      N || // Or to prevent items jumping to back to their "new" position when items change
      T && p.current.newIndex === R
    )
      return Ac;
    if (!(Ee && !Nn(G) || !l) && (X || k))
      return it.Transition.toString({
        ...l,
        property: Pi
      });
  }
}
function Tc(e, t) {
  var n, r;
  return typeof e == "boolean" ? {
    draggable: e,
    // Backwards compatibility
    droppable: !1
  } : {
    draggable: (n = e?.draggable) != null ? n : t.draggable,
    droppable: (r = e?.droppable) != null ? r : t.droppable
  };
}
function Sn(e) {
  if (!e)
    return !1;
  const t = e.data.current;
  return !!(t && "sortable" in t && typeof t.sortable == "object" && "containerId" in t.sortable && "items" in t.sortable && "index" in t.sortable);
}
const Rc = [q.Down, q.Right, q.Up, q.Left], Dc = (e, t) => {
  let {
    context: {
      active: n,
      collisionRect: r,
      droppableRects: o,
      droppableContainers: i,
      over: s,
      scrollableAncestors: a
    }
  } = t;
  if (Rc.includes(e.code)) {
    if (e.preventDefault(), !n || !r)
      return;
    const c = [];
    i.getEnabled().forEach((u) => {
      if (!u || u != null && u.disabled)
        return;
      const h = o.get(u.id);
      if (h)
        switch (e.code) {
          case q.Down:
            r.top < h.top && c.push(u);
            break;
          case q.Up:
            r.top > h.top && c.push(u);
            break;
          case q.Left:
            r.left > h.left && c.push(u);
            break;
          case q.Right:
            r.left < h.left && c.push(u);
            break;
        }
    });
    const l = ta({
      collisionRect: r,
      droppableRects: o,
      droppableContainers: c
    });
    let d = mi(l, "id");
    if (d === s?.id && l.length > 1 && (d = l[1].id), d != null) {
      const u = i.get(n.id), h = i.get(d), f = h ? o.get(h.id) : null, g = h?.node.current;
      if (g && f && u && h) {
        const m = Mn(g).some((C, A) => a[A] !== C), E = Fi(u, h), w = Nc(u, h), y = m || !E ? {
          x: 0,
          y: 0
        } : {
          x: w ? r.width - f.width : 0,
          y: w ? r.height - f.height : 0
        }, R = {
          x: f.left,
          y: f.top
        };
        return y.x && y.y ? R : Qt(R, y);
      }
    }
  }
};
function Fi(e, t) {
  return !Sn(e) || !Sn(t) ? !1 : e.data.current.sortable.containerId === t.data.current.sortable.containerId;
}
function Nc(e, t) {
  return !Sn(e) || !Sn(t) || !Fi(e, t) ? !1 : e.data.current.sortable.index < t.data.current.sortable.index;
}
const po = chrome.runtime.getURL("options/options.html"), Mc = chrome.runtime.getURL("icons/logo.png");
function Y(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" && Number.isFinite(e) ? String(e) : "";
}
function Ic(e) {
  if (e == null) return;
  const t = Number(e);
  return Number.isFinite(t) ? t : void 0;
}
function ho(e) {
  const t = Number(e) || 0, n = Math.floor(t / 3600), r = Math.floor(t % 3600 / 60), o = Math.floor(t % 60), i = String(r).padStart(2, "0"), s = String(o).padStart(2, "0");
  return n > 0 ? `${n}:${i}:${s}` : `${i}:${s}`;
}
function Lc(e) {
  const t = Number(e);
  return !Number.isFinite(t) || t <= 0 ? "" : `${Math.round(t / 60)} 分钟`;
}
function $c(e) {
  if (!e) return "";
  const t = typeof e == "string" ? Date.parse(e) : Number(e);
  if (!Number.isFinite(t)) return "";
  const r = Date.now() - t, o = 1440 * 60 * 1e3;
  if (r < o)
    return "今天";
  if (r < 2 * o)
    return "昨天";
  const i = new Date(t), s = String(i.getMonth() + 1).padStart(2, "0"), a = String(i.getDate()).padStart(2, "0");
  return `${s}-${a}`;
}
function cn(e, t) {
  const n = Y(e?.id || t);
  if (!n) return null;
  const r = Y(e?.audioUrl), o = Array.isArray(e?.backupAudioUrls) ? e.backupAudioUrls.map(Y).filter(Boolean) : void 0;
  return {
    id: n,
    episodeTitle: Y(e?.episodeTitle || e?.episodeDescription || n),
    episodeDescription: Y(e?.episodeDescription || ""),
    audioUrl: r || void 0,
    backupAudioUrls: o,
    publishedAt: e?.publishedAt ?? null,
    duration: Ic(e?.duration),
    cover: Y(e?.cover || ""),
    episodeLink: Y(e?.episodeLink || ""),
    podcastTitle: Y(e?.podcastTitle || ""),
    podcastSourceRef: Y(e?.podcastSourceRef || ""),
    podcastLink: Y(e?.podcastLink || ""),
    source: Y(e?.source || "")
  };
}
function Lt(e, {
  queueIds: t,
  removedIds: n,
  playedIds: r,
  showAllLatest: o
}) {
  return o ? e.slice() : e.filter((i) => {
    if (!i?.id) return !1;
    const s = i.id;
    return !(t.has(s) || n.has(s) || r.has(s));
  });
}
function Pc(e) {
  const t = typeof e == "string" ? Number.isNaN(Date.parse(e)) ? NaN : Date.parse(e) : typeof e == "number" ? e : NaN;
  if (!Number.isFinite(t)) return "";
  const n = Date.now() - t;
  return !Number.isFinite(n) || n < 0 ? "" : n < 60 * 1e3 ? "刚刚" : n < 3600 * 1e3 ? `${Math.round(n / 6e4)} 分钟前` : n < 1440 * 60 * 1e3 ? `${Math.round(n / 36e5)} 小时前` : `${Math.round(n / (1440 * 60 * 1e3))} 天前`;
}
function Oi(e) {
  const t = Y(e);
  if (!t) return "";
  try {
    const n = new URL(t, "https://www.xiaoyuzhoufm.com");
    return n.protocol !== "http:" && n.protocol !== "https:" ? "" : n.href;
  } catch {
    return "";
  }
}
function Fc(e) {
  const t = Oi(e);
  if (!t) return;
  const n = globalThis.chrome;
  if (n?.tabs?.create)
    try {
      n.tabs.create({ url: t });
    } catch {
      window.open(t, "_blank", "noopener,noreferrer");
    }
  else
    window.open(t, "_blank", "noopener,noreferrer");
  try {
    globalThis.close?.();
  } catch {
  }
}
function Ui({
  mode: e,
  episodes: t,
  playbackState: n,
  playedPositions: r,
  onPlayNow: o,
  onEnqueueNext: i,
  onComplete: s,
  onRemoveFromLatest: a,
  onRemoveFromQueue: c,
  onReorder: l,
  removedIds: d,
  playedIds: u,
  listRef: h,
  footer: f
}) {
  return e === "queue" ? l ? /* @__PURE__ */ b("div", { class: "episode-feed", children: [
    /* @__PURE__ */ b(
      Uc,
      {
        episodes: t,
        playbackState: n,
        playedPositions: r,
        onPlayNow: o,
        onComplete: s,
        onRemoveFromQueue: c,
        onReorder: l
      }
    ),
    /* @__PURE__ */ b(go, {})
  ] }) : /* @__PURE__ */ b("div", { class: "episode-feed", children: [
    t.map((_) => /* @__PURE__ */ b(
      Tr,
      {
        episode: _,
        playbackState: n,
        playedPositions: r,
        onPlayNow: o,
        onComplete: s,
        onRemoveFromQueue: c
      },
      _.id
    )),
    /* @__PURE__ */ b(go, {})
  ] }) : /* @__PURE__ */ b("div", { class: `episode-feed${f ? " has-footer" : ""}`, ref: h, children: [
    t.map(
      (_) => Oc({ episode: _, playbackState: n, onPlayNow: o, onEnqueueNext: i, onRemoveFromLatest: a, removedIds: d, playedIds: u })
    ),
    f ?? null
  ] });
}
function Oc({
  episode: e,
  playbackState: t,
  onPlayNow: n,
  onEnqueueNext: r,
  onRemoveFromLatest: o,
  removedIds: i,
  playedIds: s
}) {
  const a = t.currentEpisodeId === e.id, c = i?.has(e.id) ? "已移除" : s?.has(e.id) ? "已完成" : "", l = Oi(e.episodeLink || e.podcastLink || ""), d = e.cover ? /* @__PURE__ */ b("img", { class: "episode-card__cover", src: e.cover, alt: `${e.episodeTitle} 封面`, loading: "lazy" }) : /* @__PURE__ */ b("div", { class: "episode-card__cover episode-card__cover--placeholder", children: zi(e.episodeTitle) }), u = l ? /* @__PURE__ */ b(
    "button",
    {
      type: "button",
      class: "episode-card__cover-btn",
      "aria-label": "打开节目页面",
      onClick: () => Fc(l),
      children: d
    }
  ) : d, h = Lc(e.duration ?? void 0), f = Pc(e.publishedAt ?? void 0), g = $c(e.publishedAt ?? void 0), _ = f ? g ? `${f} · ${g}` : f : g || "", m = [];
  h && m.push(h), _ && m.push(_);
  const E = a ? "播放中" : "";
  return /* @__PURE__ */ b(
    "article",
    {
      class: `episode-card episode-card--latest${a ? " episode-card--current" : ""}`,
      "data-episode-id": e.id,
      children: [
        u,
        /* @__PURE__ */ b("div", { class: "episode-card__content", children: /* @__PURE__ */ b("div", { class: "episode-card__info", children: [
          /* @__PURE__ */ b("div", { class: "episode-card__title", children: e.episodeTitle }),
          E ? /* @__PURE__ */ b("span", { class: "episode-card__badge", children: E }) : null,
          /* @__PURE__ */ b("div", { class: "episode-card__meta", children: [
            m.map((w, y) => /* @__PURE__ */ b("span", { class: "episode-card__meta-item", children: w }, `${w}-${y}`)),
            c ? /* @__PURE__ */ b("span", { class: "episode-card__meta-item", children: c }) : null,
            /* @__PURE__ */ b("div", { class: "episode-card__meta-actions", children: [
              /* @__PURE__ */ b(
                "button",
                {
                  type: "button",
                  class: "hover-action-btn hover-action-btn--play hover-action-btn--sm",
                  "aria-label": "立即播放",
                  onClick: () => n(e),
                  children: /* @__PURE__ */ b("span", { class: "hover-action-btn__icon iconfont", children: "" })
                }
              ),
              r ? /* @__PURE__ */ b(
                "button",
                {
                  type: "button",
                  class: "hover-action-btn hover-action-btn--queue hover-action-btn--sm",
                  "aria-label": "加入播放清单",
                  onClick: () => r(e),
                  children: /* @__PURE__ */ b("span", { class: "hover-action-btn__icon iconfont", children: "" })
                }
              ) : null,
              o ? /* @__PURE__ */ b(
                "button",
                {
                  type: "button",
                  class: "hover-action-btn hover-action-btn--remove hover-action-btn--sm",
                  "aria-label": "从最新列表移除",
                  onClick: () => o(e.id),
                  children: /* @__PURE__ */ b("span", { class: "hover-action-btn__icon iconfont", children: "" })
                }
              ) : null
            ] })
          ] })
        ] }) })
      ]
    },
    e.id
  );
}
function Uc({ episodes: e, playbackState: t, playedPositions: n, onPlayNow: r, onComplete: o, onRemoveFromQueue: i, onReorder: s }) {
  const a = Gs(
    Jr(Cr, { activationConstraint: { distance: 6 } }),
    Jr(Er, { coordinateGetter: Dc })
  ), [c, l] = j(null), [d, u] = j(null), h = H(() => e.map((y) => y.id), [e]), f = H(
    () => c && e.find((y) => y.id === c) || null,
    [c, e]
  ), g = () => {
    l(null), u(null);
  };
  return /* @__PURE__ */ b(
    Wa,
    {
      sensors: a,
      collisionDetection: ea,
      onDragStart: (y) => {
        l(String(y.active.id));
      },
      onDragOver: (y) => {
        u(y.over ? String(y.over.id) : null);
      },
      onDragEnd: (y) => {
        const { active: R, over: x } = y;
        if (!x) {
          g();
          return;
        }
        const C = String(R.id), A = String(x.id);
        if (g(), C === A)
          return;
        const D = h.indexOf(C), I = h.indexOf(A);
        if (D === -1 || I === -1)
          return;
        const B = xr(h, D, I);
        s(B);
      },
      onDragCancel: (y) => {
        g();
      },
      children: [
        /* @__PURE__ */ b(vc, { items: h, strategy: yc, children: e.map((y) => /* @__PURE__ */ b(
          zc,
          {
            episode: y,
            playbackState: t,
            playedPositions: n,
            onPlayNow: r,
            onComplete: o,
            onRemoveFromQueue: i,
            isDropTarget: !!(d && d === y.id && c !== d)
          },
          y.id
        )) }),
        /* @__PURE__ */ b(hc, { dropAnimation: null, children: f ? /* @__PURE__ */ b(
          Tr,
          {
            episode: f,
            playbackState: t,
            onPlayNow: r,
            onComplete: o,
            onRemoveFromQueue: i,
            isDragging: !0,
            dragOverlay: !0
          }
        ) : null })
      ]
    }
  );
}
function zc({ episode: e, playbackState: t, playedPositions: n, onPlayNow: r, onComplete: o, onRemoveFromQueue: i, isDropTarget: s }) {
  const { attributes: a, listeners: c, setNodeRef: l, transform: d, transition: u, isDragging: h } = xc({ id: e.id }), f = {
    transform: it.Transform.toString(d),
    transition: u
  };
  return /* @__PURE__ */ b(
    Tr,
    {
      nodeRef: l,
      style: f,
      attributes: a,
      listeners: c,
      episode: e,
      playbackState: t,
      playedPositions: n,
      onPlayNow: r,
      onComplete: o,
      onRemoveFromQueue: i,
      isDragging: h,
      isDropTarget: s
    }
  );
}
function Tr(e) {
  const {
    episode: t,
    playbackState: n,
    playedPositions: r,
    onPlayNow: o,
    onComplete: i,
    onRemoveFromQueue: s,
    style: a,
    attributes: c,
    listeners: l,
    nodeRef: d,
    isDragging: u,
    isDropTarget: h,
    dragOverlay: f
  } = e, g = n.currentEpisodeId === t.id, _ = g && n.playing, m = Number.isFinite(Number(t.duration)) && Number(t.duration) > 0 ? Math.max(1, Math.round(Number(t.duration) / 60)) : null, E = g ? Number(n.positionSec) || 0 : r?.[t.id] || 0, w = E > 0 ? Math.max(1, Math.round(E / 60)) : 0, y = m ? w > 0 ? `${w}/${m} 分钟` : `${m} 分钟` : w > 0 ? `已播 ${w} 分钟` : "", R = t.cover ? /* @__PURE__ */ b("img", { class: "episode-card__cover", src: t.cover, alt: `${t.episodeTitle} 封面`, loading: "lazy" }) : /* @__PURE__ */ b("div", { class: "episode-card__cover episode-card__cover--placeholder", children: zi(t.episodeTitle) });
  return /* @__PURE__ */ b("article", { ref: d, class: `episode-card episode-card--queue${g ? " episode-card--current" : ""}${u ? " is-dragging" : ""}${h ? " is-drop-target" : ""}${f ? " is-drag-overlay" : ""}`, style: a, ...c || {}, children: [
    /* @__PURE__ */ b("div", { class: "queue-card__drag-area", ...l || {}, children: [
      /* @__PURE__ */ b("div", { class: "drag-handle", "aria-hidden": "true", children: "⋮⋮" }),
      R
    ] }),
    /* @__PURE__ */ b("div", { class: "episode-card__content", children: /* @__PURE__ */ b("div", { class: "episode-card__info", children: [
      /* @__PURE__ */ b("div", { class: "episode-card__title", children: t.episodeTitle }),
      /* @__PURE__ */ b("div", { class: "episode-card__meta", children: [
        y ? /* @__PURE__ */ b("span", { class: "episode-card__meta-item", children: y }) : null,
        /* @__PURE__ */ b("div", { class: "episode-card__meta-actions", children: [
          /* @__PURE__ */ b(
            "button",
            {
              type: "button",
              class: "hover-action-btn hover-action-btn--play hover-action-btn--sm",
              "aria-label": "播放此条",
              onClick: () => o(t),
              children: _ ? /* @__PURE__ */ b("span", { class: "hover-action-btn__icon hover-action-btn__icon--text", children: "⏸" }) : /* @__PURE__ */ b("span", { class: "hover-action-btn__icon iconfont", children: "" })
            }
          ),
          s ? /* @__PURE__ */ b(
            "button",
            {
              type: "button",
              class: "hover-action-btn hover-action-btn--return hover-action-btn--sm",
              "aria-label": "返回最新节目",
              onClick: () => s(t.id),
              children: /* @__PURE__ */ b("span", { class: "hover-action-btn__icon hover-action-btn__icon--text", children: "↩" })
            }
          ) : null,
          i ? /* @__PURE__ */ b(
            "button",
            {
              type: "button",
              class: "hover-action-btn hover-action-btn--remove hover-action-btn--sm",
              "aria-label": "标记为已完成",
              onClick: () => i(t.id),
              children: /* @__PURE__ */ b("span", { class: "hover-action-btn__icon iconfont", children: "" })
            }
          ) : null
        ] })
      ] })
    ] }) })
  ] });
}
function go() {
  return /* @__PURE__ */ b("div", { class: "episode-feed__footer", children: "—— 到底啦 ——" });
}
function zi(e) {
  const t = (e || "").replace(/\s+/g, "");
  return t ? Array.from(t).slice(0, 2).join("").toUpperCase() : "FM";
}
function Bc(e) {
  const {
    episodes: t,
    playbackState: n,
    showAllLatest: r,
    onToggleFilter: o,
    onPlayNow: i,
    onEnqueueNext: s,
    onRemoveFromLatest: a,
    removedIds: c,
    playedIds: l,
    canLoadMore: d,
    onLoadMore: u,
    totalCount: h,
    visibleCount: f,
    filteredCount: g,
    showCounts: _
  } = e, m = z(null), E = z(null), w = z(!1), [y, R] = j(!1);
  U(() => {
    w.current = !1, R(!1);
  }, [t.length]), U(() => {
    d || (w.current = !1, R(!1));
  }, [d]), U(() => {
    if (!d) return;
    const C = E.current, A = m.current;
    if (!C) return;
    const D = new IntersectionObserver(
      (I) => {
        I[0]?.isIntersecting && !w.current && (w.current = !0, R(!0), u());
      },
      {
        root: A,
        rootMargin: "0px 0px 96px 0px",
        threshold: 0.05
      }
    );
    return D.observe(C), () => {
      D.disconnect();
    };
  }, [d, u, t.length]);
  const x = h ? `显示 ${f}/${h} · ${d ? "继续下滑加载更多…" : g < h && !r ? "仅显示未处理" : "已加载全部"}` : "暂无节目 · 默认每次加载 15 条";
  return /* @__PURE__ */ b("section", { class: "latest-section", children: [
    /* @__PURE__ */ b("div", { class: "section-title-row", children: [
      /* @__PURE__ */ b("h2", { class: "section-title", children: "最新节目" }),
      /* @__PURE__ */ b("button", { id: "latestToggle", class: "small-toggle", type: "button", onClick: o, children: r ? "仅未处理" : "显示全部" })
    ] }),
    _ ? /* @__PURE__ */ b("p", { class: "section-meta", children: x }) : null,
    /* @__PURE__ */ b(
      Ui,
      {
        mode: "latest",
        episodes: t,
        playbackState: n,
        onPlayNow: i,
        onEnqueueNext: s,
        onRemoveFromLatest: a,
        removedIds: c,
        playedIds: l,
        listRef: m,
        footer: t.length ? /* @__PURE__ */ b(
          "div",
          {
            ref: E,
            class: `list-sentinel${d ? "" : " is-disabled"}`,
            "aria-hidden": "true",
            children: d ? y ? "加载中…" : "继续下滑加载更多…" : "—— 到底啦 ——"
          }
        ) : null
      }
    ),
    t.length === 0 ? /* @__PURE__ */ b("p", { class: "empty-hint", children: "暂无节目，请刷新或稍后重试。" }) : null
  ] });
}
function qc(e) {
  const {
    playbackState: t,
    currentEpisode: n,
    activeTab: r,
    hasQueue: o,
    loadingHint: i,
    onTogglePlayback: s,
    onSelectLatest: a,
    onSelectQueue: c,
    onSeekBy: l,
    onSeekTo: d,
    onSetRate: u,
    onSkipNext: h
  } = e, f = !!n, g = f && n?.cover ? /* @__PURE__ */ b(
    "a",
    {
      class: "player-cover-link",
      href: n?.episodeLink || "#",
      target: "_blank",
      rel: "noreferrer",
      onClick: (x) => {
        n?.episodeLink || x.preventDefault();
      },
      children: /* @__PURE__ */ b("img", { class: "player-cover", src: n.cover, alt: `${n.episodeTitle} 封面` })
    }
  ) : /* @__PURE__ */ b("div", { class: "player-cover player-cover--placeholder", children: "FM" }), _ = n?.episodeTitle || "请选择要播放的节目", m = `${ho(t.positionSec)} / ${ho(t.durationSec)}`, E = `${Number(t.playbackRate || 1).toFixed(2).replace(/\.00$/, "")}x`, w = t.durationSec > 0 ? Math.min(t.positionSec, t.durationSec) / t.durationSec * 100 : 0, y = () => {
    const x = Number(t.playbackRate || 1), C = [1, 1.25, 1.5, 1.75, 2], A = C.findIndex((I) => Math.abs(I - x) < 1e-3), D = C[(A + 1) % C.length];
    u(D);
  }, R = (x) => {
    const A = x.currentTarget.getBoundingClientRect(), D = Math.min(1, Math.max(0, (x.clientX - A.left) / A.width)), I = (t.durationSec || 0) * D;
    d(I);
  };
  return /* @__PURE__ */ b("div", { class: "player-wrapper", children: [
    /* @__PURE__ */ b("div", { class: "player-body", children: [
      g,
      /* @__PURE__ */ b("div", { class: "player-info", children: [
        /* @__PURE__ */ b("div", { class: "player-title", title: _, children: _ }),
        /* @__PURE__ */ b("div", { class: "player-progress-inline", children: m })
      ] })
    ] }),
    /* @__PURE__ */ b(
      "div",
      {
        class: "player-progress",
        role: "progressbar",
        "aria-valuenow": t.positionSec,
        "aria-valuemin": 0,
        "aria-valuemax": t.durationSec || 0,
        onPointerDown: R,
        children: /* @__PURE__ */ b("div", { class: "player-progress__bar", style: { width: `${w.toFixed(2)}%` } })
      }
    ),
    /* @__PURE__ */ b("div", { class: "player-controls", children: [
      /* @__PURE__ */ b("div", { class: "player-controls__cluster player-controls__cluster--side", children: /* @__PURE__ */ b("button", { type: "button", class: "player-button player-button--ghost", onClick: y, disabled: !f, children: E }) }),
      /* @__PURE__ */ b("div", { class: "player-controls__cluster player-controls__cluster--center", children: [
        /* @__PURE__ */ b("button", { type: "button", class: "player-button player-button--ghost", onClick: () => l(-15), disabled: !f, children: "-15s" }),
        /* @__PURE__ */ b("button", { type: "button", class: "player-button player-button--primary", onClick: s, disabled: !f, children: t.playing ? "⏸" : "▶" }),
        /* @__PURE__ */ b("button", { type: "button", class: "player-button player-button--ghost", onClick: () => l(30), disabled: !f, children: "+30s" })
      ] }),
      /* @__PURE__ */ b("div", { class: "player-controls__cluster player-controls__cluster--side", children: /* @__PURE__ */ b("button", { type: "button", class: "player-button player-button--ghost", onClick: h, disabled: !f, children: "⏭" }) })
    ] })
  ] });
}
function Hc({ episodes: e, playbackState: t, playedPositions: n, onPlayNow: r, onComplete: o, onReorder: i, onRemove: s }) {
  return /* @__PURE__ */ b("section", { class: "queue-section", children: [
    /* @__PURE__ */ b("div", { class: "section-title-row", children: /* @__PURE__ */ b("h2", { class: "section-title", children: "播放列表" }) }),
    /* @__PURE__ */ b(
      Ui,
      {
        mode: "queue",
        episodes: e,
        playbackState: t,
        playedPositions: n,
        onPlayNow: r,
        onComplete: o,
        onReorder: i,
        onRemoveFromQueue: s
      }
    )
  ] });
}
const wt = "xiaoyuzhou", Qc = "podcast", ln = "subscriptions";
async function jc() {
  const e = await chrome.storage.sync.get({ [ln]: [] }), t = Array.isArray(e[ln]) ? e[ln] : [], { subscriptions: n, mutated: r } = Vc(t);
  return r && await chrome.storage.sync.set({ [ln]: n }), n;
}
function Vc(e) {
  const t = /* @__PURE__ */ new Map(), n = [];
  let r = !1;
  return e.forEach((o) => {
    const i = Yc(o);
    if (!i) {
      r = !0;
      return;
    }
    const s = `${i.source}::${i.sourceRef}`;
    if (t.has(s)) {
      r = !0;
      return;
    }
    t.set(s, !0), n.push(i);
  }), n.sort((o, i) => (i.addedAt || 0) - (o.addedAt || 0)), { subscriptions: n, mutated: r };
}
function Yc(e) {
  if (typeof e == "string") {
    const s = _o(e);
    return s ? {
      source: mo(s, wt),
      sourceRef: s,
      addedAt: Date.now()
    } : null;
  }
  if (!e || typeof e != "object")
    return null;
  const t = _o(e.sourceRef ?? e.id);
  if (!t)
    return null;
  const n = mo(t, e.source ?? e.platform), r = Kc(e.title ?? e.name), o = Wc(e.addedAt ?? e.createdAt), i = {
    source: n,
    sourceRef: t
  };
  return r && (i.title = r), i.addedAt = o ?? Date.now(), i;
}
function mo(e, t) {
  const n = wn(e), r = wn(t).toLowerCase();
  return /^https?:\/\//i.test(n) ? "rss" : r || wt;
}
function _o(e) {
  return wn(e);
}
function Kc(e) {
  return wn(e) || "";
}
function wn(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function Wc(e) {
  if (e == null)
    return;
  const t = Number(e);
  if (Number.isFinite(t) && t > 0)
    return t;
  const n = Date.parse(e);
  return Number.isFinite(n) ? n : void 0;
}
const Xc = 15e3;
async function Gc(e) {
  const {
    entity: t,
    sourceRef: n,
    source: r = wt,
    timeoutMs: o = Xc
  } = e ?? {}, i = Wn(t).toLowerCase(), s = Wn(r).toLowerCase() || wt, a = Wn(n);
  if (!i)
    throw dt("ERR_MISSING_ENTITY", "Missing entity type for fetch dispatcher");
  if (!a)
    throw dt("ERR_MISSING_SOURCE_REF", "Missing sourceRef for fetch dispatcher");
  const c = el(i), l = {
    type: "xyz.fetch",
    requestId: c,
    payload: {
      entity: i,
      source: s,
      sourceRef: a
    }
  }, d = tl(e);
  d && (l.payload.cache = d);
  const u = await Zc(l, o);
  if (!u || typeof u != "object")
    throw dt("ERR_EMPTY_RESPONSE", "No response received from background dispatcher");
  const { ok: h, data: f, error: g, meta: _ } = u;
  if (!h) {
    const m = g?.message ?? "Fetch dispatcher reported a failure", E = dt(g?.code ?? "ERR_DISPATCH_FAILED", m);
    throw E.meta = _ || {
      entity: i,
      source: s,
      sourceRef: a
    }, E;
  }
  return {
    data: f,
    meta: _,
    requestId: u.requestId ?? c
  };
}
function Jc(e, t = {}) {
  return Gc({
    entity: Qc,
    sourceRef: e,
    ...t
  });
}
async function Zc(e, t) {
  if (!chrome?.runtime?.sendMessage)
    throw dt("ERR_NO_RUNTIME", "chrome.runtime.sendMessage is not available in this context");
  return new Promise((n, r) => {
    let o = !1;
    const i = setTimeout(() => {
      if (o)
        return;
      o = !0;
      const s = dt(
        "ERR_DISPATCH_TIMEOUT",
        `Request ${e.requestId ?? "(unknown)"} timed out after ${t}ms`
      );
      s.meta = {
        type: e.type,
        timeoutMs: t
      }, r(s);
    }, t);
    chrome.runtime.sendMessage(e, (s) => {
      if (o)
        return;
      o = !0, clearTimeout(i);
      const a = chrome.runtime.lastError;
      if (a) {
        const c = dt("ERR_RUNTIME_LAST_ERROR", a.message || "Runtime messaging error");
        c.meta = { type: e.type }, r(c);
        return;
      }
      n(s);
    });
  });
}
function el(e) {
  const t = Math.random().toString(16).slice(2, 8);
  return `req:${e || "unknown"}:${Date.now()}:${t}`;
}
function Wn(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function dt(e, t) {
  const n = new Error(t);
  return n.code = e, n;
}
function tl(e) {
  if (!e || typeof e != "object")
    return null;
  const t = {}, n = [];
  return e.cache && typeof e.cache == "object" && n.push(e.cache), n.push(e), n.forEach((r) => {
    if (!r || typeof r != "object")
      return;
    (r.force === !0 || r.forceRefresh === !0 || r.refresh === !0) && (t.force = !0, t.forceRefresh = !0), (r.bypass === !0 || r.bypassCache === !0 || r.skip === !0 || r.skipCache === !0) && (t.bypass = !0, t.bypassCache = !0);
    const o = Number(r.ttlMs);
    Number.isFinite(o) && o > 0 && (t.ttlMs = o), (r.deferStore === !0 || r.defer === !0) && (t.deferStore = !0);
  }), Object.keys(t).length ? t : null;
}
async function nl(e) {
  const t = lt(e);
  if (!/^https?:\/\//i.test(t))
    throw new Error("Invalid RSS feed url");
  const n = await fetch(t, { headers: { Accept: "application/rss+xml, application/xml, text/xml;q=0.9, */*;q=0.8" } });
  if (!n.ok)
    throw new Error(`RSS request failed with status ${n.status}`);
  const r = await n.text(), o = (/* @__PURE__ */ new Date()).toISOString(), i = me(r, /<channel[\s\S]*?<\/channel>/i) || r, s = Re(me(i, /<title[\s\S]*?>([\s\S]*?)<\/title>/i) || "") || t, a = Xn(i) || t, c = mt(i, /<itunes:image[^>]*href="([^"]+)"/i) || Re(me(i, /<image[\s\S]*?<url[\s\S]*?>([\s\S]*?)<\/url>[\s\S]*?<\/image>/i) || ""), l = [], d = yo(r, /<item[\s\S]*?<\/item>/gi), u = yo(r, /<entry[\s\S]*?<\/entry>/gi);
  (d.length ? d : u).forEach((g) => {
    const _ = Re(
      me(g, /<guid[\s\S]*?>([\s\S]*?)<\/guid>/i) || me(g, /<id[\s\S]*?>([\s\S]*?)<\/id>/i) || Xn(g) || ""
    );
    if (!_) return;
    const m = Re(me(g, /<title[\s\S]*?>([\s\S]*?)<\/title>/i) || _), E = Re(me(g, /<description[\s\S]*?>([\s\S]*?)<\/description>/i) || "") || Re(me(g, /<content:encoded[\s\S]*?>([\s\S]*?)<\/content:encoded>/i) || "") || Re(me(g, /<summary[\s\S]*?>([\s\S]*?)<\/summary>/i) || ""), w = mt(g, /<enclosure[^>]*type="audio\/[^"]+"[^>]*url="([^"]+)"/i) || mt(g, /<enclosure[^>]*url="([^"]+)"[^>]*type="audio\/[^"]+"/i) || mt(g, /<media:content[^>]*url="([^"]+)"/i) || "", y = Re(me(g, /<pubDate[\s\S]*?>([\s\S]*?)<\/pubDate>/i) || "") || Re(me(g, /<updated[\s\S]*?>([\s\S]*?)<\/updated>/i) || "") || Re(me(g, /<published[\s\S]*?>([\s\S]*?)<\/published>/i) || "") || null, R = me(g, /<itunes:duration[\s\S]*?>([\s\S]*?)<\/itunes:duration>/i) || "", x = rl(R), C = Xn(g) || "", A = mt(g, /<itunes:image[^>]*href="([^"]+)"/i) || "";
    l.push({
      id: _,
      title: m,
      description: E,
      audioUrl: w,
      publishedAt: y,
      duration: x,
      link: C,
      image: A
    });
  });
  const f = l.map((g, _) => ({
    id: lt(g.id || `${t}:${_}`),
    // 统一字段命名，兼容 Options/Popup 渲染
    episodeTitle: lt(g.title || ""),
    episodeDescription: lt(g.description || ""),
    audioUrl: lt(g.audioUrl || ""),
    publishedAt: g.publishedAt || null,
    duration: g.duration || void 0,
    episodeLink: lt(g.link || ""),
    // 节目封面统一使用播客封面
    cover: lt(c || ""),
    podcastTitle: s,
    podcastSourceRef: t,
    podcastLink: a,
    source: "rss"
  }));
  return {
    data: {
      podcast: {
        title: s,
        link: a,
        cover: c || void 0
      },
      episodes: f
    },
    meta: {
      source: "rss",
      sourceRef: t,
      fetchedAt: o,
      cache: { status: "updated", cachedAt: o }
    }
  };
}
function me(e, t) {
  const n = t.exec(e);
  return n ? n[1] : "";
}
function yo(e, t) {
  const n = [];
  let r;
  for (; r = t.exec(e); )
    n.push(r[0]);
  return n;
}
function mt(e, t) {
  const n = t.exec(e);
  return n ? n[1] : "";
}
function Re(e) {
  return String(e || "").replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
}
function Xn(e) {
  const t = mt(e, /<link[^>]*href="([^"]+)"/i);
  return t || Re(me(e, /<link[\s\S]*?>([\s\S]*?)<\/link>/i) || "");
}
function rl(e) {
  const t = (e || "").trim();
  if (!t) return;
  const n = t.split(":").map((r) => Number(r));
  if (!n.some((r) => !Number.isFinite(r))) {
    if (n.length === 3)
      return n[0] * 3600 + n[1] * 60 + n[2];
    if (n.length === 2)
      return n[0] * 60 + n[1];
    if (n.length === 1)
      return n[0];
  }
}
function lt(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
const Vt = "xyzSettings", he = {
  autoFetchIntervalMinutes: 120,
  podcastCacheLimit: 200,
  episodeCacheLimit: 600,
  autoClearCacheThresholdMb: 256,
  showCacheCounts: !1,
  enablePlayerDebugLogs: !1,
  playerDebugLogLimit: 200
};
let Ne = { ...he }, Rr = !1;
async function Bi() {
  return Rr || await qi(), { ...Ne };
}
async function ol(e = {}) {
  const t = Dr({ ...Ne, ...e });
  return Ne = t, await chrome.storage.sync.set({ [Vt]: t }), { ...Ne };
}
function cr(e) {
  if (typeof e != "function")
    return () => {
    };
  const t = (n, r) => {
    if (r !== "sync" || !n[Vt])
      return;
    const { newValue: o } = n[Vt];
    Ne = Dr(o), e({ ...Ne });
  };
  return chrome.storage.onChanged.addListener(t), Rr ? e({ ...Ne }) : qi().then(() => e({ ...Ne })).catch(() => {
  }), () => {
    chrome.storage.onChanged.removeListener(t);
  };
}
function Dr(e) {
  const t = typeof e == "object" && e ? { ...e } : {};
  return {
    autoFetchIntervalMinutes: $t(t.autoFetchIntervalMinutes, he.autoFetchIntervalMinutes, {
      min: 60,
      max: 1440
    }),
    podcastCacheLimit: $t(t.podcastCacheLimit, he.podcastCacheLimit, { min: 50, max: 2e3 }),
    episodeCacheLimit: $t(t.episodeCacheLimit, he.episodeCacheLimit, { min: 100, max: 5e3 }),
    autoClearCacheThresholdMb: $t(
      t.autoClearCacheThresholdMb,
      he.autoClearCacheThresholdMb,
      { min: 0, max: 2048 }
    ),
    showCacheCounts: !!t.showCacheCounts,
    enablePlayerDebugLogs: !!t.enablePlayerDebugLogs,
    playerDebugLogLimit: $t(t.playerDebugLogLimit, he.playerDebugLogLimit, { min: 200, max: 5e3 })
  };
}
async function qi() {
  try {
    const t = (await chrome.storage.sync.get({ [Vt]: he }))?.[Vt];
    Ne = Dr(t);
  } catch (e) {
    console.warn("[核桃FM] Failed to load settings from storage:", e), Ne = { ...he };
  } finally {
    Rr = !0;
  }
  return Ne;
}
function $t(e, t, { min: n = Number.NEGATIVE_INFINITY, max: r = Number.POSITIVE_INFINITY } = {}) {
  const o = Number(e);
  return Number.isFinite(o) ? o < n ? n : o > r ? r : Math.round(o) : t;
}
const il = Number.POSITIVE_INFINITY, sl = {
  podcast: Number.POSITIVE_INFINITY,
  episode: Number.POSITIVE_INFINITY
}, yt = {
  podcast: he.podcastCacheLimit,
  episode: he.episodeCacheLimit
};
let rt = he.autoClearCacheThresholdMb * 1024 * 1024, pn = !1;
const Hi = {
  podcast: "podcastCache",
  episode: "episodeCache"
}, lr = /* @__PURE__ */ new Map(), Gn = /* @__PURE__ */ new Set();
let En = { ...yt };
ll();
async function Qi({ entity: e, source: t, sourceRef: n }) {
  const r = ur(e, t, n);
  if (!r)
    return null;
  const { entityKey: o, cacheKey: i } = r, s = ft(o), a = s.get(i);
  if (a) {
    if (!Yt(a))
      return a;
    s.delete(i);
  }
  await An(o);
  const c = s.get(i);
  return c ? Yt(c) ? (s.delete(i), await $n(o), null) : c : null;
}
async function ji(e, t, { ttlMs: n, source: r } = {}) {
  const o = Vi(e);
  if (!o || !Array.isArray(t) || t.length === 0)
    return;
  await An(o);
  const i = ft(o), s = al(o, n), a = Date.now();
  if (t.forEach((c) => {
    if (!c || typeof c != "object")
      return;
    const { source: l, sourceRef: d, data: u, meta: h, cachedAt: f } = c, g = ur(e, l, d);
    if (!g)
      return;
    const _ = Number.isFinite(s) ? a + s : null, m = {
      data: Yi(o, u),
      meta: h || {},
      cachedAt: f || new Date(a).toISOString(),
      expiresAt: _
    };
    i.set(g.cacheKey, Nr(m));
  }), await $n(o), o === "podcast")
    try {
      const l = (await chrome.storage.local.get({ fetchStatus: {} })).fetchStatus || {};
      let d = !1;
      t.forEach((u) => {
        const { source: h, sourceRef: f } = u, g = ur(e, h, f);
        g && (l[g.cacheKey] = {
          lastSuccessAt: a,
          lastErrorAt: null,
          lastError: null
        }, d = !0);
      }), d && await chrome.storage.local.set({ fetchStatus: l });
    } catch (c) {
      console.warn("[cache-store] failed to update fetchStatus", c);
    }
  try {
    console.log("[cache-store] setCacheEntriesBatch entity=", o, "size=", t.length, "memorySize=", ft(o).size);
    try {
      chrome.runtime.sendMessage({
        type: "xyz.cache.entityUpdated",
        entity: o,
        size: ft(o).size,
        updated: Date.now(),
        source: r || "background"
      });
    } catch {
    }
  } catch {
  }
}
function al(e, t) {
  return typeof t == "number" && t > 0 ? t : sl[e] ?? il;
}
async function An(e) {
  if (Gn.has(e))
    return;
  const t = Hi[e];
  if (!t) {
    Gn.add(e);
    return;
  }
  const n = ft(e);
  try {
    const o = (await chrome.storage.local.get(t))?.[t];
    o && typeof o == "object" && (Object.entries(o).forEach(([i, s]) => {
      s && typeof s == "object" && n.set(i, Nr(s));
    }), await $n(e));
  } catch (r) {
    console.error("[核桃FM] Failed to load cache from storage:", r);
  } finally {
    Gn.add(e);
  }
}
async function $n(e) {
  const t = Hi[e];
  if (!t)
    return;
  const n = ft(e);
  bo(e, n);
  const r = {};
  n.forEach((o, i) => {
    Yt(o) || (r[i] = vo(e, o));
  });
  try {
    await chrome.storage.local.set({ [t]: r });
  } catch (o) {
    if (cl(o)) {
      console.warn("[核桃FM] Cache quota exceeded, pruning and retrying…"), bo(e, n, { aggressive: !0 });
      const i = {};
      n.forEach((s, a) => {
        Yt(s) || (i[a] = vo(e, s));
      });
      try {
        await chrome.storage.local.set({ [t]: i }), await hn();
        return;
      } catch (s) {
        console.error("[核桃FM] Failed to persist cache after pruning:", s);
      }
    }
    console.error("[核桃FM] Failed to persist cache:", o), await hn();
    return;
  }
  await hn();
}
function ft(e) {
  const t = lr.get(e);
  if (t)
    return t;
  const n = /* @__PURE__ */ new Map();
  return lr.set(e, n), n;
}
function ur(e, t, n) {
  const r = Vi(e), o = dr(t) || "xiaoyuzhou", i = dr(n);
  return !r || !i ? null : {
    entityKey: r,
    cacheKey: `${o}:${i}`
  };
}
function Vi(e) {
  const t = dr(e).toLowerCase();
  return t || "";
}
function dr(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function Yt(e) {
  if (!e || typeof e != "object")
    return !0;
  const t = e.expiresAt;
  if (t == null)
    return !1;
  const n = Number(t);
  return Number.isFinite(n) ? n <= Date.now() : !1;
}
function bo(e, t, { aggressive: n = !1 } = {}) {
  if (!t || typeof t.size != "number") return;
  for (const [a, c] of t.entries())
    Yt(c) && t.delete(a);
  const r = ul(e);
  if (!r || r <= 0) return;
  const o = n ? Math.max(10, Math.floor(r * 0.6)) : r;
  if (t.size <= o) return;
  const i = Array.from(t.entries()).sort((a, c) => {
    const l = Number(new Date(a[1]?.cachedAt || 0)), d = Number(new Date(c[1]?.cachedAt || 0));
    return !Number.isFinite(l) && !Number.isFinite(d) ? 0 : Number.isFinite(l) ? Number.isFinite(d) ? l - d : 1 : -1;
  }), s = Math.max(0, i.length - o);
  for (let a = 0; a < s; a += 1)
    t.delete(i[a][0]);
}
function cl(e) {
  if (!e) return !1;
  const t = String(e?.message || e || "").toLowerCase();
  return t.includes("quota") || t.includes("kquotabytes");
}
function Nr(e) {
  if (!e || typeof e != "object") return e;
  const t = { ...e };
  return t.raw && delete t.raw, t.data && typeof t.data == "object" && t.data.raw && delete t.data.raw, t.meta && typeof t.meta == "object" && t.meta.raw && delete t.meta.raw, t;
}
function Yi(e, t) {
  try {
    if (!t || typeof t != "object" || !(String(e).toLowerCase() === "podcast")) return t;
    const r = { ...t || {} }, o = Array.isArray(r.episodes) ? r.episodes.slice(0, 25) : [];
    if (r.episodes = o.map((i) => {
      const s = { ...i || {} };
      return {
        id: s.id,
        title: s.title || s.episodeTitle,
        episodeTitle: s.episodeTitle || s.title,
        audioUrl: s.audioUrl,
        backupAudioUrls: s.backupAudioUrls,
        publishedAt: s.publishedAt || s.publishAt || null,
        duration: s.duration,
        cover: s.cover || s.image || "",
        link: s.link || s.episodeLink || "",
        episodeLink: s.episodeLink || s.link || ""
      };
    }), r.podcast && typeof r.podcast == "object") {
      const i = r.podcast;
      r.podcast = {
        title: i.title,
        cover: i.cover || i.image || "",
        link: i.link || i.shareUrl || i.url || ""
      };
    }
    return r;
  } catch {
    return t;
  }
}
function vo(e, t) {
  const n = { ...t || {} };
  return n.data = Yi(e, n.data), Nr(n);
}
function ll() {
  Bi().then(So).catch((e) => {
    console.warn("[核桃FM] Failed to load settings for cache limits:", e), En = { ...yt }, rt = he.autoClearCacheThresholdMb * 1024 * 1024;
  }), cr(So);
}
function So(e) {
  if (!e || typeof e != "object") {
    En = { ...yt }, rt = he.autoClearCacheThresholdMb * 1024 * 1024;
    return;
  }
  En = {
    podcast: wo(e.podcastCacheLimit, yt.podcast),
    episode: wo(e.episodeCacheLimit, yt.episode)
  };
  const n = Number(e.autoClearCacheThresholdMb);
  rt = Number.isFinite(n) && n > 0 ? Math.round(n) * 1024 * 1024 : 0, pn || hn().catch((r) => {
    console.warn("[核桃FM] Failed to enforce quota after settings update:", r);
  });
}
function wo(e, t) {
  const n = Number(e);
  return !Number.isFinite(n) || n <= 0 ? t : Math.round(n);
}
function ul(e) {
  return En[e] ?? yt[e] ?? 0;
}
async function hn() {
  if (!pn && !(!rt || rt <= 0)) {
    pn = !0;
    try {
      let e = await fr();
      if (!Number.isFinite(e) || e <= rt)
        return;
      await dl(), e = await fr(), Number.isFinite(e) && e > rt && console.warn("[核桃FM] Storage usage remains above threshold after cleanup:", e, "bytes");
    } catch (e) {
      console.warn("[核桃FM] Failed to enforce cache quota:", e);
    } finally {
      pn = !1;
    }
  }
}
async function dl() {
  await An("podcast"), await An("episode");
  const e = fl();
  if (e.length) {
    e.sort((t, n) => t.cachedAt - n.cachedAt);
    for (const t of e) {
      if (!ft(t.entity).delete(t.cacheKey))
        continue;
      await $n(t.entity);
      const r = await fr();
      if (Number.isFinite(r) && r <= rt)
        return;
    }
  }
}
function fl() {
  const e = [];
  for (const [t, n] of lr.entries())
    if (!(t !== "podcast" && t !== "episode"))
      for (const [r, o] of n.entries()) {
        const i = Number(new Date(o?.cachedAt || o?.meta?.cachedAt || 0));
        e.push({ entity: t, cacheKey: r, cachedAt: Number.isFinite(i) ? i : 0 });
      }
  return e;
}
function fr() {
  return new Promise((e, t) => {
    chrome.storage.local.getBytesInUse(null, (n) => {
      const r = chrome.runtime.lastError;
      if (r) {
        t(new Error(r.message || "Failed to read storage usage"));
        return;
      }
      e(n);
    });
  });
}
const Pn = 5, pl = Number.POSITIVE_INFINITY, Ki = 5, Wi = 1200, hl = 1800 * 1e3, gl = 3600 * 1e3;
async function ml(e, t = {}) {
  const n = Array.isArray(e) ? e.slice() : [], r = n.filter((c) => c && typeof c == "object" ? (K(c.source) || "xiaoyuzhou") !== "rss" : !0).map((c) => K(c && typeof c == "object" ? c.sourceRef : c)).filter(Boolean), o = n.filter((c) => c && typeof c == "object" ? (K(c.source) || "xiaoyuzhou") === "rss" : !1).map((c) => K(c.sourceRef)).filter(Boolean);
  console.log("[aggregator]", (/* @__PURE__ */ new Date()).toISOString(), "aggregateEpisodesForSubscriptions xyRefs=", r.length, "rssRefs=", o.length, "deferStore=", t.deferStore, "source=", t.source);
  const [i, s] = await Promise.all([
    yl(r, t),
    _l(o, t)
  ]), a = [...i, ...s];
  return a.sort((c, l) => {
    const d = c.publishedAt ? Date.parse(c.publishedAt) : 0;
    return (l.publishedAt ? Date.parse(l.publishedAt) : 0) - d;
  }), Number.isFinite(t.maxItems) ? a.slice(0, Math.max(1, Number(t.maxItems))) : a;
}
async function _l(e, t = {}) {
  const n = Array.isArray(e) ? e.map(K).filter(Boolean) : [];
  if (!n.length) return [];
  const r = Gi(t), o = Number.isFinite(t.limitPerPodcast) ? Math.max(1, Number(t.limitPerPodcast)) : Pn, i = !!t.force, s = !!t.deferStore;
  console.log("[aggregator] RSS START refs=", n.length, "force=", i, "deferStore=", s, "source=", t.source);
  const a = [];
  if (i) {
    const u = Number.isFinite(t.forceBatchSize) ? Math.max(1, Number(t.forceBatchSize)) : Ki, h = Number.isFinite(t.forceBatchDelayMs) ? Math.max(0, Number(t.forceBatchDelayMs)) : Wi;
    for (let f = 0; f < n.length; f += u) {
      const _ = n.slice(f, f + u).map((E) => () => Co(E, { force: !0, perPodcast: o, deferStore: s })), m = await Cn(_, r);
      a.push(...m), f + u < n.length && h > 0 && await Xi(h);
    }
  } else {
    const u = n.map((f) => () => Co(f, { force: !1, perPodcast: o, deferStore: s })), h = await Cn(u, r);
    a.push(...h);
  }
  const c = [], l = /* @__PURE__ */ new Set(), d = [];
  if (a.forEach((u) => {
    if (u.status !== "fulfilled") return;
    const { podcast: h, episodes: f, rawData: g, meta: _, fromCache: m } = u.value || {};
    (f || []).forEach((E, w) => {
      const y = K(E.id || `${h.sourceRef}:${w}`);
      !y || l.has(y) || (l.add(y), c.push(E));
    }), s && h?.sourceRef && g && !m && d.push({ source: "rss", sourceRef: h.sourceRef, data: g, meta: _ || {}, cachedAt: Date.now() });
  }), s && d.length)
    try {
      console.log("[aggregator] RSS batch write count=", d.length, "source=", t.source || "background"), await ji("podcast", d, { ttlMs: t.ttlMs, source: t.source || "background" });
    } catch (u) {
      console.warn("[episodes-aggregator] batch cache update for rss failed", u);
    }
  return c.sort((u, h) => {
    const f = u.publishedAt ? Date.parse(u.publishedAt) : 0;
    return (h.publishedAt ? Date.parse(h.publishedAt) : 0) - f;
  }), Number.isFinite(t.maxItems) ? c.slice(0, Math.max(1, Number(t.maxItems))) : c;
}
async function yl(e, t = {}) {
  const n = Array.isArray(e) ? e.map(K).filter(Boolean) : [];
  if (!n.length) return [];
  const r = Gi(t), o = Number.isFinite(t.limitPerPodcast) ? Math.max(1, Number(t.limitPerPodcast)) : Pn, i = Number.isFinite(t.maxItems) ? Math.max(1, Number(t.maxItems)) : pl, s = !!t.force, a = !!t.deferStore;
  console.log("[aggregator] START refs=", n.length, "force=", s, "deferStore=", a, "source=", t.source);
  const c = [];
  if (s) {
    const f = Number.isFinite(t.forceBatchSize) ? Math.max(1, Number(t.forceBatchSize)) : Ki, g = Number.isFinite(t.forceBatchDelayMs) ? Math.max(0, Number(t.forceBatchDelayMs)) : Wi;
    for (let _ = 0; _ < n.length; _ += f) {
      const E = n.slice(_, _ + f).map((y) => () => Eo(y, { force: !0, perPodcast: o, deferStore: a })), w = await Cn(E, r);
      c.push(...w), _ + f < n.length && g > 0 && await Xi(g);
    }
  } else {
    const f = n.map((_) => () => Eo(_, { force: !1, perPodcast: o, deferStore: a })), g = await Cn(f, r);
    c.push(...g);
  }
  console.log("[aggregator] fetched podcasts=", c.length, "deferStore=", a);
  const l = [], d = /* @__PURE__ */ new Set(), u = [];
  c.forEach((f) => {
    if (f.status !== "fulfilled") return;
    const { podcast: g, episodes: _, rawData: m, meta: E, fromCache: w } = f.value || {};
    (_ || []).forEach((y, R) => {
      const x = K(y.id || `${g.sourceRef}:${R}`);
      !x || d.has(x) || (d.add(x), l.push(y));
    }), a && g?.sourceRef && m && !w && u.push({
      source: wt,
      sourceRef: g.sourceRef,
      data: m,
      meta: E || {},
      cachedAt: Date.now()
    });
  }), l.sort((f, g) => {
    const _ = f.publishedAt ? Date.parse(f.publishedAt) : 0;
    return (g.publishedAt ? Date.parse(g.publishedAt) : 0) - _;
  });
  const h = l.slice(0, i);
  if (a && u.length)
    try {
      console.log("[aggregator] batch write count=", u.length, "source=", t.source || "background", "caller=", new Error().stack.split(`
`)[2]), await ji("podcast", u, {
        ttlMs: t.ttlMs,
        source: t.source || "background"
      });
    } catch (f) {
      console.warn("[episodes-aggregator] batch cache update failed", f);
    }
  return h;
}
async function Eo(e, { force: t = !1, perPodcast: n = Pn, deferStore: r = !1 } = {}) {
  const o = await Qi({ entity: "podcast", source: wt, sourceRef: e }), i = Date.now(), s = o?.cachedAt ? i - o.cachedAt : 1 / 0;
  if (!t && o && s < gl) {
    console.log("[aggregator] fetchOnePodcast SKIP ref=", e, "cacheAge=", Math.round(s / 6e4), "min");
    const h = o.data?.podcast ?? {}, f = Array.isArray(o.data?.episodes) ? o.data.episodes.slice(0, n) : [], g = Ao(e, h, f, o.data, o.meta);
    return g.fromCache = !0, g;
  }
  console.log("[aggregator] fetchOnePodcast FETCH ref=", e, "force=", t, "deferStore=", r, "cacheAge=", o ? Math.round(s / 6e4) + "min" : "none");
  const a = r ? { cache: { bypass: !1, deferStore: !0 } } : t ? { cache: { forceRefresh: !0 } } : {}, { data: c, meta: l } = await Jc(e, a), d = c?.podcast ?? {}, u = Array.isArray(c?.episodes) ? c.episodes.slice(0, n) : [];
  return Ao(e, d, u, c, l);
}
function Ao(e, t, n, r, o) {
  const i = {
    sourceRef: e,
    title: K(t.title),
    cover: K(t.cover || t.image || ""),
    link: K(t.link || t.shareUrl || t.url || "")
  }, s = n.map((a, c) => {
    const l = Ji(a);
    return {
      id: K(a.id || `${e}:${c}`),
      episodeTitle: K(a.title || a.name || ""),
      episodeDescription: K(a.description || a.brief || ""),
      audioUrl: l.audioUrl,
      backupAudioUrls: l.backupAudioUrls,
      publishedAt: a.publishedAt || a.publishAt || a.updatedAt || a.createdAt || null,
      duration: bl(
        a.duration || a.durationSec || a.durationSeconds || a.audio?.duration
      ),
      cover: i.cover,
      episodeLink: K(
        a.link || a.url || a.shareUrl || (a.sourceRef ? `https://www.xiaoyuzhoufm.com/episode/${a.sourceRef}` : "")
      ),
      podcastTitle: K(i.title || i.sourceRef),
      podcastSourceRef: i.sourceRef,
      podcastLink: K(i.link) || `https://www.xiaoyuzhoufm.com/podcast/${i.sourceRef}`,
      source: "xiaoyuzhou"
    };
  });
  return { podcast: i, episodes: s, rawData: r, meta: o };
}
async function Co(e, { force: t = !1, perPodcast: n = Pn, deferStore: r = !1 } = {}) {
  const o = await Qi({ entity: "podcast", source: "rss", sourceRef: e }), i = Date.now(), s = o?.cachedAt ? i - o.cachedAt : 1 / 0;
  if (!t && o && s < hl) {
    console.log("[aggregator] fetchOneRss SKIP url=", e, "cacheAge=", Math.round(s / 6e4), "min");
    const u = o.data?.podcast ?? {}, h = Array.isArray(o.data?.episodes) ? o.data.episodes.slice(0, n) : [], f = ko(e, u, h, o.data, o.meta);
    return f.fromCache = !0, f;
  }
  console.log("[aggregator] fetchOneRss FETCH url=", e, "force=", t, "cacheAge=", o ? Math.round(s / 6e4) + "min" : "none");
  const { data: a, meta: c } = await nl(e), l = a?.podcast ?? {}, d = Array.isArray(a?.episodes) ? a.episodes.slice(0, n) : [];
  return ko(e, l, d, a, c);
}
function ko(e, t, n, r, o) {
  const i = {
    sourceRef: e,
    title: K(t.title),
    cover: K(t.cover || ""),
    link: K(t.link || "")
  }, s = n.map((a, c) => ({
    ...a,
    id: K(a.id || `${e}:${c}`),
    podcastTitle: K(i.title || i.sourceRef),
    podcastSourceRef: i.sourceRef,
    podcastLink: K(i.link || ""),
    cover: K(i.cover || ""),
    source: "rss"
  }));
  return { podcast: i, episodes: s, rawData: r, meta: o };
}
function Xi(e) {
  return new Promise((t) => setTimeout(t, Number(e) || 0));
}
async function Cn(e, t = 3) {
  const n = new Array(e.length), r = [];
  let o = 0;
  const i = async () => {
    for (; o < e.length; ) {
      const a = o++, c = e[a];
      try {
        const l = await c();
        n[a] = { status: "fulfilled", value: l };
      } catch (l) {
        n[a] = { status: "rejected", reason: l };
      }
    }
  }, s = Math.min(Math.max(1, t), e.length || 1);
  for (let a = 0; a < s; a++)
    r.push(i());
  return await Promise.allSettled(r), n;
}
function Gi(e) {
  if (!e) return 3;
  if (e.sequential === !0) return 1;
  const t = Number(e.concurrency);
  return Number.isFinite(t) && t > 0 ? t : 3;
}
function Ji(e) {
  const t = /* @__PURE__ */ new Set();
  let n = "";
  const r = [];
  [
    e?.audioUrl,
    e?.audio?.url,
    e?.audio?.src,
    e?.enclosure?.url,
    e?.enclosures?.[0]?.url,
    e?.media?.source?.url,
    e?.media?.url
  ].some((c) => {
    const l = xo(c);
    return l && !n ? (n = l, t.add(l), !0) : !1;
  });
  const i = (c) => {
    const l = xo(c);
    !l || t.has(l) || (r.push(l), t.add(l));
  }, s = e?.media || {};
  return s.backupSource && i(s.backupSource.url || s.backupSource.src || s.backupSource), Array.isArray(s.backupSources) && s.backupSources.forEach((c) => {
    c && i(typeof c == "string" ? c : c.url || c.src);
  }), Array.isArray(s.sources) && s.sources.forEach((c) => {
    c && i(typeof c == "string" ? c : c.url || c.src);
  }), s.backupUrl && i(s.backupUrl), s.fallbackUrl && i(s.fallbackUrl), [
    e?.backupAudioUrl,
    e?.alternativeAudioUrl,
    e?.fallbackAudioUrl
  ].forEach(i), Array.isArray(e?.backupAudioUrls) && e.backupAudioUrls.forEach(i), Array.isArray(e?.audioAlternatives) && e.audioAlternatives.forEach(i), Array.isArray(e?.alternateAudioUrls) && e.alternateAudioUrls.forEach(i), !n && r.length && (n = r.shift()), {
    audioUrl: n || "",
    backupAudioUrls: r
  };
}
function xo(e) {
  const t = K(e);
  return t ? /^https?:\/\//i.test(t) ? t : t.startsWith("//") ? `https:${t}` : "" : "";
}
function K(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function bl(e) {
  if (e == null) return;
  const t = Number(e);
  return Number.isFinite(t) ? t : void 0;
}
const we = {
  queue: "playbackQueue",
  removed: "removedEpisodes",
  history: "playHistory"
};
async function vl() {
  const e = await chrome.storage.local.get({ [we.queue]: [] }), t = Array.isArray(e[we.queue]) ? e[we.queue] : [], n = t.filter((r) => r && typeof r == "object" && Se(r.id)).map((r) => El(r));
  return n.length !== t.length && await chrome.storage.local.set({ [we.queue]: n }), n;
}
async function Zi() {
  const e = await chrome.storage.local.get({ [we.removed]: [] }), t = Array.isArray(e[we.removed]) ? e[we.removed] : [], n = Array.from(new Set(t.map((r) => Se(r)).filter(Boolean)));
  return n.length !== t.length && await chrome.storage.local.set({ [we.removed]: n }), n;
}
async function Sl(e) {
  const t = Se(e);
  if (!t) return [];
  const n = await Zi();
  if (!n.includes(t)) {
    const r = [t, ...n];
    return await chrome.storage.local.set({ [we.removed]: r }), r;
  }
  return n;
}
async function wl() {
  const e = await chrome.storage.local.get({ [we.history]: [] }), t = Array.isArray(e[we.history]) ? e[we.history] : [], n = t.map((r) => Al(r)).filter(Boolean).sort((r, o) => (o.playedAt || 0) - (r.playedAt || 0));
  return n.length !== t.length && await chrome.storage.local.set({ [we.history]: n }), n;
}
function El(e) {
  if (!e || typeof e != "object") return null;
  const t = Se(e.id);
  if (!t) return null;
  let n = Se(e.audioUrl || e.audio?.url);
  const r = Cl(e);
  return !n && r.length && (n = r[0]), {
    id: t,
    episodeTitle: Se(e.episodeTitle || e.title || t),
    audioUrl: n,
    backupAudioUrls: r,
    cover: Se(e.cover || e.image || ""),
    publishedAt: e.publishedAt || e.publishAt || e.updatedAt || e.createdAt || null,
    duration: pr(
      e.duration || e.durationSec || e.durationSeconds || e.audio?.duration
    ),
    episodeLink: Se(e.episodeLink || e.link || ""),
    podcastTitle: Se(e.podcastTitle || e.podcast?.title || ""),
    podcastSourceRef: Se(e.podcastSourceRef || e.podcast?.sourceRef || ""),
    podcastLink: Se(e.podcastLink || e.podcast?.link || "")
  };
}
function Al(e) {
  if (!e || typeof e != "object") return null;
  const t = Se(e.episodeId);
  if (!t) return null;
  const n = pr(e.lastPosition) || 0, r = pr(e.playedAt) || Date.now();
  return { episodeId: t, lastPosition: n, playedAt: r };
}
function Se(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function pr(e) {
  if (e == null) return;
  const t = Number(e);
  return Number.isFinite(t) ? t : void 0;
}
function Cl(e) {
  const t = [], n = /* @__PURE__ */ new Set(), r = (s) => {
    const a = kl(s);
    !a || n.has(a) || (n.add(a), t.push(a));
  }, o = e?.media || {};
  return o.backupSource && r(o.backupSource.url || o.backupSource.src || o.backupSource), Array.isArray(o.backupSources) && o.backupSources.forEach((s) => {
    s && r(typeof s == "string" ? s : s.url || s.src);
  }), Array.isArray(o.sources) && o.sources.forEach((s) => {
    s && r(typeof s == "string" ? s : s.url || s.src);
  }), o.backupUrl && r(o.backupUrl), o.fallbackUrl && r(o.fallbackUrl), [
    e?.backupAudioUrl,
    e?.alternativeAudioUrl,
    e?.fallbackAudioUrl
  ].forEach(r), Array.isArray(e?.backupAudioUrls) && e.backupAudioUrls.forEach(r), Array.isArray(e?.audioAlternatives) && e.audioAlternatives.forEach(r), Array.isArray(e?.alternateAudioUrls) && e.alternateAudioUrls.forEach(r), t;
}
function kl(e) {
  const t = Se(e);
  return t ? /^https?:\/\//i.test(t) ? t : t.startsWith("//") ? `https:${t}` : "" : "";
}
const xl = "xyz.playback.control", Tl = "xyz.playback.state";
async function To() {
  return ke({ action: "getState" });
}
async function Rl(e) {
  return console.log("[核桃FM][ui] playNow", e?.id), ke({ action: "playNow", episode: es(e) });
}
async function Dl(e) {
  return console.log("[核桃FM][ui] enqueueNext", e?.id), ke({ action: "enqueueNext", episode: es(e) });
}
async function Nl(e) {
  return console.log("[核桃FM][ui] removeFromQueue", e), ke({ action: "removeFromQueue", episodeId: De(e) });
}
async function Ml(e) {
  return console.log("[核桃FM][ui] complete", e), ke({ action: "complete", episodeId: De(e) });
}
async function Ro() {
  console.log("[核桃FM][ui] pause");
  try {
    return await en({ type: "pause" }), !0;
  } catch {
    return ke({ action: "pause" });
  }
}
async function Do() {
  console.log("[核桃FM][ui] resume");
  try {
    return await en({ type: "play" }), !0;
  } catch {
    return ke({ action: "resume" });
  }
}
async function Il() {
  return console.log("[核桃FM][ui] skipNext"), ke({ action: "skipNext" });
}
async function Ll(e) {
  console.log("[核桃FM][ui] seekBy", e);
  const t = Number(e) || 0;
  try {
    return await en({ type: "seekBy", seconds: t }), !0;
  } catch {
    return ke({ action: "seekBy", seconds: t });
  }
}
async function $l(e) {
  const t = Number(e), n = Number.isFinite(t) ? Math.max(0, t) : 0;
  console.log("[核桃FM][ui] seekTo", n);
  try {
    return await en({ type: "seekTo", positionSec: n }), !0;
  } catch {
    return ke({ action: "seekTo", positionSec: n });
  }
}
async function Pl(e) {
  const t = Number(e);
  console.log("[核桃FM][ui] setRate", t);
  const n = Number.isFinite(t) && t > 0 ? t : 1;
  try {
    return await en({ type: "setRate", rate: n }), !0;
  } catch {
    return ke({ action: "setRate", rate: n });
  }
}
async function Fl(e) {
  const t = Array.isArray(e) ? e.filter(Boolean).map(String) : [];
  return console.log("[核桃FM][ui] reorderQueue", t), ke({ action: "reorderQueue", ids: t });
}
function Ol(e) {
  function t(n) {
    n && n.type === Tl && e(n.state);
  }
  return chrome.runtime.onMessage.addListener(t), () => chrome.runtime.onMessage.removeListener(t);
}
async function ke(e) {
  const t = { type: xl, payload: e };
  return new Promise((n, r) => {
    const s = (c) => {
      const l = String(c || "").toLowerCase();
      return l.includes("message port closed") || l.includes("receiving end does not exist") || l.includes("no receiving end") || l.includes("extension context invalidated");
    }, a = (c) => {
      try {
        chrome.runtime.sendMessage(t, (l) => {
          const d = chrome.runtime.lastError;
          if (d) {
            if (c < 1 && s(d.message || d)) {
              const u = Math.floor(Math.random() * 40), h = 80 * (1 + c) + u;
              setTimeout(() => a(c + 1), h);
              return;
            }
            console.warn("[核桃FM][ui] control failed", e?.action, d);
            try {
              chrome.runtime.sendMessage({ type: "ui.playback.error", action: e?.action || "", error: d?.message || String(d) });
            } catch {
            }
            r(new Error(d.message || "runtime error"));
            return;
          }
          if (!l || l.ok !== !0) {
            console.warn("[核桃FM][ui] control rejected", e?.action, l);
            try {
              chrome.runtime.sendMessage({ type: "ui.playback.error", action: e?.action || "", error: l?.error || "playback control failed" });
            } catch {
            }
            r(new Error(l?.error || "playback control failed"));
            return;
          }
          n(l.state || l.result || null);
        });
      } catch (l) {
        if (c < 1 && s(l?.message || l)) {
          const d = Math.floor(Math.random() * 40), u = 80 * (1 + c) + d;
          setTimeout(() => a(c + 1), u);
          return;
        }
        console.warn("[核桃FM][ui] control threw", e?.action, l);
        try {
          chrome.runtime.sendMessage({ type: "ui.playback.error", action: e?.action || "", error: l?.message || String(l) });
        } catch {
        }
        r(new Error(l?.message || "runtime error"));
      }
    };
    a(0);
  });
}
function en(e) {
  const t = { type: "offscreen.playback.control", payload: e }, n = (r) => {
    const o = String(r || "").toLowerCase();
    return o.includes("receiving end does not exist") || o.includes("no receiving end") || o.includes("message port closed");
  };
  return new Promise((r, o) => {
    const i = (s) => {
      try {
        chrome.runtime.sendMessage(t, (a) => {
          const c = chrome.runtime.lastError;
          if (c) {
            if (s > 0 && n(c.message || c)) {
              setTimeout(() => i(s - 1), 60);
              return;
            }
            try {
              chrome.runtime.sendMessage({ type: "ui.playback.error", action: String(e?.type || ""), error: c?.message || String(c) });
            } catch {
            }
            o(new Error(c.message || "runtime error"));
            return;
          }
          if (!a || a.ok !== !0) {
            try {
              chrome.runtime.sendMessage({ type: "ui.playback.error", action: String(e?.type || ""), error: a?.error || "offscreen control failed" });
            } catch {
            }
            o(new Error(a?.error || "offscreen control failed"));
            return;
          }
          r(a.result || !0);
        });
      } catch (a) {
        if (s > 0 && n(a?.message || a)) {
          setTimeout(() => i(s - 1), 60);
          return;
        }
        try {
          chrome.runtime.sendMessage({ type: "ui.playback.error", action: String(e?.type || ""), error: a?.message || String(a) });
        } catch {
        }
        o(a);
      }
    };
    i(1);
  });
}
function es(e) {
  if (!e || typeof e != "object") return null;
  const t = De(e.id);
  let n = De(e.audioUrl || e.audio?.url);
  const r = zl(e);
  return !n && r.length && (n = r[0]), !t || !n ? null : {
    id: t,
    episodeTitle: De(e.episodeTitle || e.title || t),
    audioUrl: n,
    backupAudioUrls: r,
    cover: De(e.cover || e.image || ""),
    publishedAt: e.publishedAt || e.publishAt || e.updatedAt || e.createdAt || null,
    duration: Ul(
      e.duration || e.durationSec || e.durationSeconds || e.audio?.duration
    ),
    episodeLink: De(e.episodeLink || e.link || ""),
    podcastTitle: De(e.podcastTitle || e.podcast?.title || ""),
    podcastSourceRef: De(e.podcastSourceRef || e.podcast?.sourceRef || ""),
    podcastLink: De(e.podcastLink || e.podcast?.link || "")
  };
}
function De(e) {
  return typeof e == "string" ? e.trim() : typeof e == "number" ? String(e) : "";
}
function Ul(e) {
  if (e == null) return;
  const t = Number(e);
  return Number.isFinite(t) ? t : void 0;
}
function zl(e) {
  const t = [], n = /* @__PURE__ */ new Set(), r = (s) => {
    const a = Bl(s);
    !a || n.has(a) || (n.add(a), t.push(a));
  }, o = e?.media || {};
  return o.backupSource && r(o.backupSource.url || o.backupSource.src || o.backupSource), Array.isArray(o.backupSources) && o.backupSources.forEach((s) => {
    s && r(typeof s == "string" ? s : s.url || s.src);
  }), Array.isArray(o.sources) && o.sources.forEach((s) => {
    s && r(typeof s == "string" ? s : s.url || s.src);
  }), o.backupUrl && r(o.backupUrl), o.fallbackUrl && r(o.fallbackUrl), [
    e?.backupAudioUrl,
    e?.alternativeAudioUrl,
    e?.fallbackAudioUrl
  ].forEach(r), Array.isArray(e?.backupAudioUrls) && e.backupAudioUrls.forEach(r), Array.isArray(e?.audioAlternatives) && e.audioAlternatives.forEach(r), Array.isArray(e?.alternateAudioUrls) && e.alternateAudioUrls.forEach(r), t;
}
function Bl(e) {
  const t = De(e);
  return t ? /^https?:\/\//i.test(t) ? t : t.startsWith("//") ? `https:${t}` : "" : "";
}
const kn = 999, ql = 3, Hl = 240, tn = 20;
function gt(e, t) {
  if (t <= 0) return 0;
  const n = Math.max(e, tn);
  return Math.min(n, t);
}
function Ql(e) {
  return e <= 0 ? 0 : Math.min(e, tn);
}
const jl = {
  currentEpisodeId: null,
  playing: !1,
  positionSec: 0,
  durationSec: 0,
  playbackRate: 1,
  queue: []
}, No = {
  subscriptions: [],
  latestAllEpisodes: [],
  filteredLatestEpisodes: [],
  latestVisibleCount: tn,
  playbackQueue: [],
  removedEpisodeIds: /* @__PURE__ */ new Set(),
  playedEpisodeIds: /* @__PURE__ */ new Set(),
  playedPositions: {},
  playbackState: jl,
  currentEpisode: null,
  showAllLatest: !1,
  activeTab: "latest",
  isLoading: !1,
  refreshError: null,
  playerMessage: null,
  playerMessageIsError: !1
};
function Vl() {
  const [e, t] = j({ ...No, showCounts: !1 }), [n, r] = j({ message: "" }), [o, i] = j({ message: "" }), [s, a] = j(""), [c, l] = j([]), [d, u] = j(!1), h = z([]), [f, g] = j(!1), _ = z(!1), m = z(!1), E = z(No), w = z(he), y = P((v) => {
    t((S) => {
      const p = v(S);
      return E.current = p, p;
    });
  }, []);
  U(() => {
    w.current = he;
    const v = cr((S) => {
      w.current = S;
      try {
        t((p) => ({ ...p, showCounts: !!S?.showCacheCounts }));
      } catch {
      }
      try {
        u(!!S?.enablePlayerDebugLogs);
      } catch {
      }
    });
    return () => {
      v();
    };
  }, []);
  const R = P(
    async (v, S = 1) => {
      try {
        await v();
      } catch (p) {
        const T = String(p?.message || p || "");
        if (S > 0 && T.includes("message port closed")) {
          await To().catch(() => {
          }), await new Promise((k) => setTimeout(k, Hl)), await R(v, S - 1);
          return;
        }
        throw p;
      }
    },
    []
  );
  U(() => {
    const v = () => {
      try {
        const p = E.current, T = Array.isArray(p.latestAllEpisodes) ? p.latestAllEpisodes : [], k = Array.isArray(p.filteredLatestEpisodes) ? p.filteredLatestEpisodes : [], N = Array.isArray(p.playbackQueue) ? p.playbackQueue : [];
        console.log("[popup] subscriptions:", p.subscriptions.map((M) => M.sourceRef)), console.log("[popup] latestAllEpisodes:", T.length), console.table(T.map((M, L) => ({ index: L, id: M.id, title: M.episodeTitle }))), console.log("[popup] filteredLatestEpisodes:", k.length, "showAllLatest=", p.showAllLatest), console.table(k.map((M, L) => ({ index: L, id: M.id, title: M.episodeTitle }))), console.log("[popup] playbackQueue:", N.length), console.table(N.map((M, L) => ({ index: L, id: M.id, title: M.episodeTitle })));
      } catch (p) {
        console.warn("[popup] debugPrintLatest failed", p);
      }
    }, S = {
      snapshot: v,
      cacheKeys: async () => {
        try {
          const p = await chrome.storage.local.get({ podcastCache: {} }), T = Object.keys(p?.podcastCache || {});
          return console.log("[debug][popup] cache keys", T.length, T.slice(0, 20)), T;
        } catch (p) {
          return console.warn("[debug][popup] cacheKeys failed", p), [];
        }
      },
      refresh: () => B()
    };
    try {
      const p = window;
      p.debugPrintLatest = v, p.debugPopup = S;
    } catch {
    }
    return () => {
      try {
        const p = window;
        p.debugPrintLatest === v && delete p.debugPrintLatest, p.debugPopup === S && delete p.debugPopup;
      } catch {
      }
    };
  }, []);
  const x = P((v, S = !1) => {
    r({ message: v, isError: S });
  }, []), C = P((v, S = !1) => {
    i({ message: v, isError: S });
  }, []);
  U(() => {
    const v = { 0: "EMPTY", 1: "IDLE", 2: "LOADING", 3: "NO_SOURCE" }, S = { 0: "NOTHING", 1: "METADATA", 2: "CURRENT", 3: "FUTURE", 4: "ENOUGH" }, p = { marks: {} }, T = (k) => {
      try {
        if (!w.current?.enablePlayerDebugLogs || !k || k.type !== "offscreen.playback.timing" && k.type !== "offscreen.playback.error" && k.type !== "ui.playback.error") return;
        const N = k.type === "offscreen.playback.timing", M = k.type === "ui.playback.error", L = N ? k.timing || {} : {}, Q = Number(L.at) || Date.now(), ue = Number(L.sinceLoadMs) || 0, de = N ? String(L.event || "") : "error";
        p.t0 || (p.t0 = Q - ue), N && de && ((Dt) => {
          p.marks[Dt] = ue;
        })(de);
        const V = p.marks.loadedmetadata, _e = p.marks.canplay || p.marks.canplaythrough, O = p.marks.playing, oe = [];
        typeof V == "number" && oe.push(`meta ${Math.round(V)}ms`), typeof _e == "number" && oe.push(`canplay ${Math.round(_e)}ms`), typeof O == "number" && oe.push(`playing ${Math.round(O)}ms`);
        const Te = Number(L.bufferedEndSec) || 0, Rt = Number(L.durationSec) || 0, Fn = Rt > 0 ? Math.round(Math.min(Te, Rt) / Rt * 100) : 0, Ge = N ? v[Number(L.networkState) || 0] || String(L.networkState) : "", Je = N ? S[Number(L.readyState) || 0] || String(L.readyState) : "", Ve = N ? de || "progress" : "error", st = k?.error || (M ? { message: String(k?.error || "") } : null), Fe = !N && st ? ` · err ${String(st.code ?? "")}:${String(st.message ?? "")}` : "", at = new Date(Q), On = `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}:${String(at.getSeconds()).padStart(2, "0")}.${String(at.getMilliseconds()).padStart(3, "0")}`, nn = N ? `状态: ${Ve} · ${oe.join(" · ")} · 缓冲 ${Fn}% · 网络 ${Ge} · 就绪 ${Je}` : `状态: ${Ve}${Fe}`, pt = N ? `${Ve}:${Math.round(Q / 50)}` : `uierr:${String(st?.message || "")}:${Math.round(Q / 50)}`, ct = h.current;
        if (ct.includes(pt))
          return;
        ct.unshift(pt), ct.length > 300 && (ct.length = 300), a(nn), l((Dt) => {
          const zn = [`[${On}] ${nn}`, ...Dt], rn = Number(w.current?.playerDebugLogLimit), Bn = Number.isFinite(rn) ? Math.max(200, Math.round(rn)) : 200;
          return zn.slice(0, Bn);
        });
      } catch {
      }
    };
    return chrome.runtime.onMessage.addListener(T), () => {
      chrome.runtime.onMessage.removeListener(T);
    };
  }, []), U(() => {
    const v = cr((S) => {
      S?.enablePlayerDebugLogs || (l([]), a(""));
    });
    return () => {
      v();
    };
  }, []);
  const A = P(() => {
    setTimeout(() => i({ message: "" }), 1600);
  }, []), D = P(
    (v, S, p, T, k) => {
      const N = new Set(S.map((M) => M.id));
      return Lt(v, {
        queueIds: N,
        removedIds: p,
        playedIds: T,
        showAllLatest: k
      });
    },
    []
  ), I = P(
    (v, S, p, T) => {
      const k = p.currentEpisodeId ? v.find((M) => M.id === p.currentEpisodeId) : null, N = p.currentEpisodeId ? S.find((M) => M.id === p.currentEpisodeId) : null;
      return k || N || T || v[0] || null;
    },
    []
  ), B = P(async () => {
    if (_.current) {
      m.current = !0;
      return;
    }
    _.current = !0, g(!0), m.current = !1, x("加载中…", !1);
    try {
      const [v, S, p, T] = await Promise.all([
        jc(),
        vl(),
        Zi(),
        wl()
      ]), k = new Set(Array.isArray(p) ? p : []), N = new Set(Array.isArray(T) ? T.map((O) => O.episodeId) : []), M = {};
      Array.isArray(T) && T.forEach((O) => {
        const oe = Y(O?.episodeId), Te = Number(O?.lastPosition) || 0;
        oe && Te > 0 && (M[oe] = Te);
      });
      const L = Array.isArray(S) ? S.map((O) => cn(O)).filter(Boolean) : [];
      if (!Array.isArray(v) || v.length === 0) {
        y((O) => ({
          ...O,
          subscriptions: [],
          latestAllEpisodes: [],
          filteredLatestEpisodes: [],
          latestVisibleCount: 0,
          playbackQueue: [],
          currentEpisode: L[0] || null,
          removedEpisodeIds: k,
          playedEpisodeIds: N,
          playedPositions: M,
          activeTab: "latest"
        })), x("请先前往配置页添加订阅。", !0), g(!1), _.current = !1;
        return;
      }
      const Q = Kl(w.current.episodeCacheLimit), ue = Q, de = await Yl(v, {
        limitPerPodcast: ue,
        maxItems: Q
      });
      console.log("[popup] quickLoadLatestFromCache count=", de.length, "subs=", v.length), de.length > 0 && y((O) => {
        const oe = D(de, L, k, N, O.showAllLatest), Te = O.activeTab === "queue" && L.length === 0 ? "latest" : O.activeTab;
        return {
          ...O,
          subscriptions: v,
          latestAllEpisodes: de,
          filteredLatestEpisodes: oe,
          latestVisibleCount: gt(O.latestVisibleCount, oe.length),
          playbackQueue: L,
          removedEpisodeIds: k,
          playedEpisodeIds: N,
          playedPositions: M,
          activeTab: Te,
          currentEpisode: I(L, oe, O.playbackState, O.currentEpisode)
        };
      });
      const ee = await ml(v, {
        concurrency: ql,
        limitPerPodcast: ue,
        maxItems: Q,
        deferStore: !0,
        source: "user-action"
      }), V = Array.isArray(ee) ? ee.map((O) => cn(O)).filter((O) => !!O) : [];
      console.log("[popup] aggregated normalized count=", V.length);
      const _e = Wl(L, V);
      y((O) => {
        if (V.length === 0 && O.latestAllEpisodes.length > 0)
          return console.warn("[popup] aggregated empty, keep cached list"), {
            ...O,
            isLoading: !1,
            refreshError: null
          };
        const oe = D(
          V,
          _e,
          k,
          N,
          O.showAllLatest
        ), Te = O.activeTab === "queue" && _e.length === 0 ? "latest" : O.activeTab;
        return {
          ...O,
          subscriptions: v,
          latestAllEpisodes: V,
          filteredLatestEpisodes: oe,
          latestVisibleCount: gt(O.latestVisibleCount, oe.length),
          playbackQueue: _e,
          removedEpisodeIds: k,
          playedEpisodeIds: N,
          playedPositions: M,
          activeTab: Te,
          currentEpisode: I(_e, oe, O.playbackState, O.currentEpisode)
        };
      }), x("", !1);
    } catch (v) {
      console.error("[核桃FM][popup] refresh failed", v), x("加载失败，请稍后重试。", !0);
    } finally {
      _.current = !1, g(!1), m.current = !1;
    }
  }, [I, D, x, y]), $ = P(() => {
    B();
  }, [B]), G = P(() => {
    y((v) => {
      const S = !v.showAllLatest, p = Lt(v.latestAllEpisodes, {
        queueIds: new Set(v.playbackQueue.map((T) => T.id)),
        removedIds: v.removedEpisodeIds,
        playedIds: v.playedEpisodeIds,
        showAllLatest: S
      });
      return {
        ...v,
        showAllLatest: S,
        filteredLatestEpisodes: p,
        latestVisibleCount: Ql(p.length)
      };
    });
  }, [y]), ce = P(() => {
    t((v) => ({ ...v, activeTab: "latest" }));
  }, [t]), pe = P(() => {
    t((v) => ({ ...v, activeTab: "queue" }));
  }, [t]), Le = P(
    async (v) => {
      if (!v?.id) return;
      const { playbackState: S } = E.current || {};
      if (S?.currentEpisodeId === v.id) {
        try {
          const p = !!S?.playing;
          await R(() => p ? Ro() : Do(), 1);
        } catch (p) {
          console.error("[核桃FM][popup] toggle failed when re-clicking current episode", p), C("播放控制失败，请稍后重试。", !0), A();
        }
        return;
      }
      try {
        await R(() => Rl(v), 1), y((p) => {
          const T = p.playbackQueue.filter((k) => k.id !== v.id);
          return T.unshift(v), {
            ...p,
            playbackQueue: T,
            currentEpisode: v,
            playbackState: {
              ...p.playbackState,
              currentEpisodeId: v.id,
              playing: !0,
              // 留待后台广播来纠正精确位置（可能从历史恢复）
              positionSec: p.playbackState.positionSec,
              durationSec: v.duration ?? p.playbackState.durationSec
            }
          };
        }), C(`正在播放：${v.episodeTitle || v.id}`, !1), A();
      } catch (p) {
        console.error("[核桃FM][popup] playNow failed", p), C("播放后台未就绪，已尝试重连，请再试一次。", !0), A();
      }
    },
    [A, R, C, y]
  ), He = P(
    async (v) => {
      if (v?.id)
        try {
          await Dl(v), y((S) => {
            const p = S.playbackQueue.filter((T) => T.id !== v.id);
            return p.splice(Math.min(1, p.length), 0, v), {
              ...S,
              playbackQueue: p
            };
          }), C("已加入待播列表", !1), A();
        } catch (S) {
          console.error("[核桃FM][popup] enqueueNext failed", S), C("加入待播失败，请稍后重试。", !0), A();
        }
    },
    [A, C, y]
  ), te = P(() => {
    y((v) => {
      const S = v.filteredLatestEpisodes.length;
      if (v.latestVisibleCount >= S)
        return v;
      const p = Math.min(S, v.latestVisibleCount + tn);
      return {
        ...v,
        latestVisibleCount: p
      };
    });
  }, [y]), Qe = P(
    async (v) => {
      const S = Y(v);
      if (S) {
        console.log("[popup]", (/* @__PURE__ */ new Date()).toISOString(), "completeEpisode", S);
        try {
          await Ml(S), y((p) => {
            const T = p.playbackQueue.filter((ue) => ue.id !== S), k = new Set(p.playedEpisodeIds);
            k.add(S);
            const N = Lt(p.latestAllEpisodes, {
              queueIds: new Set(T.map((ue) => ue.id)),
              removedIds: p.removedEpisodeIds,
              playedIds: k,
              showAllLatest: p.showAllLatest
            });
            let M = p.currentEpisode;
            p.currentEpisode?.id === S && (M = T[0] || null);
            const L = p.activeTab === "queue" && T.length === 0 ? "latest" : p.activeTab, Q = gt(p.latestVisibleCount, N.length);
            return {
              ...p,
              playbackQueue: T,
              playedEpisodeIds: k,
              filteredLatestEpisodes: N,
              latestVisibleCount: Q,
              currentEpisode: M,
              activeTab: L,
              playbackState: {
                ...p.playbackState,
                currentEpisodeId: M?.id ?? null,
                playing: T.length ? p.playbackState.playing : !1,
                positionSec: T.length ? p.playbackState.positionSec : 0
              }
            };
          }), C("已完成播放。", !1), A();
        } catch (p) {
          console.error("[核桃FM][popup] complete failed", p), C("操作失败，请稍后再试。", !0), A();
        }
      }
    },
    [A, C, y]
  ), le = P(
    async (v) => {
      const S = Y(v);
      if (S) {
        console.log("[popup]", (/* @__PURE__ */ new Date()).toISOString(), "removeFromQueue", S);
        try {
          await Nl(S), y((p) => {
            const T = p.playbackQueue.filter((ee) => ee.id !== S), k = p.playbackQueue.find((ee) => ee.id === S) || p.latestAllEpisodes.find((ee) => ee.id === S) || null, N = new Set(p.removedEpisodeIds);
            N.has(S) && N.delete(S);
            let M = p.latestAllEpisodes;
            k && !M.some((ee) => ee.id === S) && (M = [k, ...M]);
            let L = Lt(M, {
              queueIds: new Set(T.map((ee) => ee.id)),
              removedIds: N,
              playedIds: p.playedEpisodeIds,
              showAllLatest: p.showAllLatest
            });
            k && !L.some((ee) => ee.id === S) && (L = [k, ...L]);
            const Q = p.currentEpisode?.id === S ? T[0] || null : p.currentEpisode, ue = p.activeTab === "queue" && T.length === 0 ? "latest" : p.activeTab, de = gt(p.latestVisibleCount, L.length);
            return {
              ...p,
              playbackQueue: T,
              removedEpisodeIds: N,
              latestAllEpisodes: M,
              filteredLatestEpisodes: L,
              latestVisibleCount: de,
              currentEpisode: Q,
              activeTab: ue,
              playbackState: {
                ...p.playbackState,
                currentEpisodeId: Q?.id ?? null,
                playing: Q ? p.playbackState.playing : !1,
                positionSec: Q ? p.playbackState.positionSec : 0,
                queue: T
              }
            };
          }), C("已移出播放列表。", !1), A();
        } catch (p) {
          console.error("[核桃FM][popup] removeFromQueue failed", p), C("操作失败，请稍后再试。", !0), A();
        }
      }
    },
    [A, C, y]
  ), $e = P(
    async (v) => {
      const S = Y(v);
      if (S) {
        console.log("[popup]", (/* @__PURE__ */ new Date()).toISOString(), "removeFromLatest", S);
        try {
          await Sl(S), y((p) => {
            const T = new Set(p.removedEpisodeIds);
            T.add(S);
            const k = p.filteredLatestEpisodes.filter((N) => N.id !== S);
            return {
              ...p,
              removedEpisodeIds: T,
              filteredLatestEpisodes: k,
              latestVisibleCount: gt(p.latestVisibleCount, k.length)
            };
          }), x("已从最新节目移除。", !1);
        } catch (p) {
          console.error("[核桃FM][popup] removeFromLatest failed", p), x("移除失败，请稍后重试。", !0);
        }
      }
    },
    [x, y]
  ), je = P(
    (v) => {
      y((S) => {
        if (!v.length) return S;
        const p = new Map(S.playbackQueue.map((k) => [k.id, k])), T = [];
        return v.forEach((k) => {
          const N = p.get(k);
          N && (T.push(N), p.delete(k));
        }), p.forEach((k) => T.push(k)), Fl(T.map((k) => k.id)).catch((k) => console.warn("[核桃FM][popup] reorderQueue sync failed", k)), {
          ...S,
          playbackQueue: T
        };
      });
    },
    [y]
  ), X = P(async () => {
    try {
      const v = !!E.current?.playbackState?.playing;
      await R(() => v ? Ro() : Do(), 1);
    } catch (v) {
      console.error("[核桃FM][popup] toggle playback failed", v), C("播放控制失败。", !0), A();
    }
  }, [A, R, C]), se = P(
    async (v) => {
      try {
        await Ll(v);
      } catch (S) {
        console.error("[核桃FM][popup] seekBy failed", S), C("快进/快退失败。", !0), A();
      }
    },
    [A, C]
  ), Ee = P(
    async (v) => {
      try {
        await $l(v);
      } catch (S) {
        console.error("[核桃FM][popup] seekTo failed", S), C("调整进度失败。", !0), A();
      }
    },
    [A, C]
  ), Pe = P(
    async (v) => {
      try {
        await Pl(v);
      } catch (S) {
        console.error("[核桃FM][popup] setRate failed", S), C("调节倍速失败。", !0), A();
      }
    },
    [A, C]
  ), ne = P(async () => {
    try {
      await Il();
    } catch (v) {
      console.error("[核桃FM][popup] skipNext failed", v), C("跳过失败。", !0), A();
    }
  }, [A, C]);
  return U(() => {
    B();
  }, [B]), U(() => {
    const v = Ol((S) => {
      S && y((p) => {
        const T = Array.isArray(S.queue) ? S.queue.map((Q) => cn(Q)).filter((Q) => !!Q) : p.playbackQueue, k = {
          currentEpisodeId: Y(S.currentEpisodeId),
          playing: !!S.playing,
          positionSec: Number(S.positionSec) || 0,
          durationSec: Number(S.durationSec) || p.playbackState.durationSec,
          playbackRate: Number(S.playbackRate) || p.playbackState.playbackRate,
          queue: T
        }, N = Lt(p.latestAllEpisodes, {
          queueIds: new Set(T.map((Q) => Q.id)),
          removedIds: p.removedEpisodeIds,
          playedIds: p.playedEpisodeIds,
          showAllLatest: p.showAllLatest
        }), M = I(T, N, k, p.currentEpisode), L = p.activeTab === "queue" && T.length === 0 ? "latest" : p.activeTab;
        return {
          ...p,
          playbackQueue: T,
          playbackState: k,
          filteredLatestEpisodes: N,
          latestVisibleCount: gt(p.latestVisibleCount, N.length),
          currentEpisode: M,
          activeTab: L
        };
      });
    });
    return To().then((S) => {
      S && y((p) => {
        const T = Array.isArray(S.queue) ? S.queue.map((L) => cn(L)).filter((L) => !!L) : p.playbackQueue, k = {
          currentEpisodeId: Y(S.currentEpisodeId),
          playing: !!S.playing,
          positionSec: Number(S.positionSec) || 0,
          durationSec: Number(S.durationSec) || p.playbackState.durationSec,
          playbackRate: Number(S.playbackRate) || p.playbackState.playbackRate,
          queue: T
        }, N = I(T, p.filteredLatestEpisodes, k, p.currentEpisode), M = p.activeTab === "queue" && T.length === 0 ? "latest" : p.activeTab;
        return {
          ...p,
          playbackQueue: T,
          playbackState: k,
          currentEpisode: N,
          activeTab: M
        };
      });
    }).catch(() => {
    }), () => {
      typeof v == "function" && v();
    };
  }, [I, y]), U(() => {
    const v = (S, p) => {
      if (p === "sync" && S.subscriptions) {
        B();
        return;
      }
    };
    return chrome.storage.onChanged.addListener(v), () => {
      chrome.storage.onChanged.removeListener(v);
    };
  }, [B]), U(() => {
    const v = (S) => {
      try {
        const p = S;
        if (!p || p.type !== "xyz.cache.entityUpdated" || p.entity !== "podcast") return;
      } catch {
      }
    };
    return chrome.runtime.onMessage.addListener(v), () => {
      chrome.runtime.onMessage.removeListener(v);
    };
  }, [B]), H(
    () => ({
      state: e,
      refreshStatus: n,
      playerStatus: o,
      loadingHint: s,
      loadingLogs: c,
      debugEnabled: d,
      isRefreshing: f,
      forceRefresh: $,
      toggleShowAllLatest: G,
      showLatestTab: ce,
      showQueueTab: pe,
      completeEpisode: Qe,
      removeFromLatest: $e,
      playEpisodeNow: Le,
      enqueueEpisodeNext: He,
      loadMoreLatest: te,
      skipCurrentEpisode: ne,
      togglePlayback: X,
      seekBy: se,
      seekTo: Ee,
      setPlaybackRate: Pe,
      reorderQueue: je,
      removeFromQueue: le
    }),
    [
      s,
      c,
      d,
      Qe,
      He,
      $,
      f,
      te,
      Le,
      o,
      n,
      $e,
      le,
      je,
      se,
      Ee,
      Pe,
      ce,
      pe,
      ne,
      e,
      X,
      G
    ]
  );
}
async function Yl(e, { limitPerPodcast: t = kn, maxItems: n = kn } = {}) {
  try {
    const o = (await chrome.storage.local.get({ podcastCache: {} }))?.podcastCache || {}, i = [], s = /* @__PURE__ */ new Set();
    return e.forEach((a) => {
      const c = Y(a?.source) || "xiaoyuzhou", l = Y(a?.sourceRef);
      if (!l) return;
      const d = `${c}:${l}`, h = o[d]?.data, f = h?.podcast || {}, g = Array.isArray(h?.episodes) ? h.episodes.slice(0, t) : [], _ = Y(f.cover || f.image || f.logo || "");
      g.forEach((m, E) => {
        const w = Y(m?.id || m?.sourceRef || `${l}:${E}`);
        if (!w || s.has(w))
          return;
        s.add(w);
        const y = Ji(m);
        i.push({
          id: w,
          episodeTitle: Y(m?.title || m?.name || w),
          episodeDescription: Y(m?.description || m?.brief || ""),
          audioUrl: y.audioUrl,
          backupAudioUrls: y.backupAudioUrls,
          publishedAt: m?.publishedAt || m?.publishAt || m?.updatedAt || m?.createdAt || null,
          duration: Xl(
            m?.duration || m?.durationSec || m?.durationSeconds || m?.audio?.duration
          ),
          cover: _,
          episodeLink: Y(
            m?.link || m?.url || m?.shareUrl || (m?.sourceRef ? `https://www.xiaoyuzhoufm.com/episode/${m.sourceRef}` : "")
          ),
          podcastTitle: Y(a?.title || f.title || l),
          podcastSourceRef: l,
          source: c,
          podcastLink: Y(a?.link) || Y(f.link || f.shareUrl || f.url || "") || `https://www.xiaoyuzhoufm.com/podcast/${l}`
        });
      });
    }), i.sort((a, c) => {
      const l = a.publishedAt ? Date.parse(a.publishedAt) : 0;
      return (c.publishedAt ? Date.parse(c.publishedAt) : 0) - l;
    }), i.slice(0, n);
  } catch (r) {
    return console.warn("[核桃FM][popup] quickLoadLatestFromCache failed:", r), [];
  }
}
function Kl(e) {
  const t = Number(e);
  if (!Number.isFinite(t) || t <= 0)
    return kn;
  const n = Math.round(t), r = Math.max(tn, n);
  return Math.min(r, kn);
}
function Wl(e, t) {
  const n = new Map(t.map((r) => [r.id, r]));
  return e.map((r) => {
    const o = r.id ? n.get(r.id) : null;
    return o ? { ...r, ...o } : r;
  });
}
function Xl(e) {
  const t = Number(e);
  return Number.isFinite(t) ? t : void 0;
}
function Gl() {
  const {
    state: e,
    playerStatus: t,
    loadingHint: n,
    loadingLogs: r,
    debugEnabled: o,
    toggleShowAllLatest: i,
    showLatestTab: s,
    showQueueTab: a,
    completeEpisode: c,
    removeFromLatest: l,
    removeFromQueue: d,
    playEpisodeNow: u,
    enqueueEpisodeNext: h,
    loadMoreLatest: f,
    skipCurrentEpisode: g,
    togglePlayback: _,
    seekBy: m,
    seekTo: E,
    setPlaybackRate: w,
    reorderQueue: y
  } = Vl(), {
    subscriptions: R,
    playbackState: x,
    currentEpisode: C,
    playbackQueue: A,
    latestAllEpisodes: D,
    filteredLatestEpisodes: I,
    showAllLatest: B,
    latestVisibleCount: $,
    activeTab: G,
    removedEpisodeIds: ce,
    playedEpisodeIds: pe,
    showCounts: Le
  } = e, He = D.length, te = I.length, Qe = te > 0 ? te : $, le = Math.min($, Qe), $e = I.slice(0, le), je = le < te, [X, se] = j("none"), Ee = X === "queue", Pe = X === "latest", ne = z(null), xe = z(!1), v = z(null), [S, p] = j(""), T = () => {
    ne.current && (clearTimeout(ne.current), ne.current = null);
  }, k = () => {
    v.current && (clearTimeout(v.current), v.current = null), v.current = window.setTimeout(() => p(""), 1500);
  }, N = async () => {
    try {
      const V = await Bi(), O = !!(await ol({ enablePlayerDebugLogs: !V?.enablePlayerDebugLogs }))?.enablePlayerDebugLogs;
      p(O ? "调试日志：已开启" : "调试日志：已关闭"), k();
    } catch {
      p("切换调试失败"), k();
    }
  }, M = (V) => {
    try {
      xe.current = !1;
    } catch {
    }
    T(), ne.current = window.setTimeout(() => {
      xe.current = !0, N();
    }, 3e3);
  }, L = (V) => {
    xe.current && (V.preventDefault(), V.stopPropagation()), T();
  }, Q = (V) => {
    T();
  }, ue = (V) => {
    xe.current && (V.preventDefault(), V.stopPropagation(), xe.current = !1);
  }, de = () => {
    if (X === "latest") {
      se("none");
      return;
    }
    se("latest"), s();
  }, ee = () => {
    if (X === "queue") {
      se("none");
      return;
    }
    se("queue"), a();
  };
  return /* @__PURE__ */ b("div", { class: "root", children: [
    /* @__PURE__ */ b("header", { class: "header", children: [
      /* @__PURE__ */ b(
        "a",
        {
          class: "branding",
          href: "https://fm.hetaozi.xyz/",
          target: "_blank",
          rel: "noreferrer",
          title: S || "核桃FM",
          onPointerDown: M,
          onPointerUp: L,
          onPointerLeave: Q,
          onPointerCancel: Q,
          onClick: ue,
          children: [
            /* @__PURE__ */ b("img", { class: "logo-image", src: Mc, alt: "核桃FM" }),
            /* @__PURE__ */ b("span", { class: "logo", children: "核桃FM" })
          ]
        }
      ),
      /* @__PURE__ */ b("div", { class: "header-actions", children: /* @__PURE__ */ b("a", { class: "header-link", href: po, target: "_blank", rel: "noreferrer", children: [
        "管理订阅（",
        R.length,
        "）"
      ] }) })
    ] }),
    /* @__PURE__ */ b("section", { class: "player", children: [
      /* @__PURE__ */ b(
        qc,
        {
          playbackState: x,
          currentEpisode: C,
          activeTab: G,
          hasQueue: !!A.length,
          loadingHint: n,
          onTogglePlayback: _,
          onSelectLatest: de,
          onSelectQueue: ee,
          onSeekBy: m,
          onSeekTo: E,
          onSetRate: w,
          onSkipNext: g
        }
      ),
      o || Array.isArray(r) && r.length > 0 ? /* @__PURE__ */ b(Jl, { logs: r }) : null,
      R.length === 0 ? /* @__PURE__ */ b("div", { class: "player-empty-overlay", role: "region", "aria-label": "导入订阅引导", children: /* @__PURE__ */ b("div", { class: "player-empty-content", children: [
        /* @__PURE__ */ b("p", { class: "player-empty-title", children: "尚未添加订阅" }),
        /* @__PURE__ */ b(
          "a",
          {
            class: "player-empty-action",
            href: `${po}?openAdd=1`,
            target: "_blank",
            rel: "noreferrer",
            onClick: () => {
              try {
                globalThis.close?.();
              } catch {
              }
            },
            children: "去导入小宇宙播客列表"
          }
        )
      ] }) }) : null
    ] }),
    /* @__PURE__ */ b(
      "div",
      {
        id: "playerStatus",
        role: "status",
        "aria-live": "polite",
        class: `player-status-toast${t.message ? " is-visible" : ""}${t.isError ? " error" : ""}`,
        children: t.message
      }
    ),
    /* @__PURE__ */ b("main", { class: "content", children: [
      /* @__PURE__ */ b("div", { class: "content-switcher", children: [
        /* @__PURE__ */ b(
          "button",
          {
            type: "button",
            class: `switcher-button${Pe ? " is-active" : ""}`,
            onClick: de,
            children: "最新节目"
          }
        ),
        /* @__PURE__ */ b(
          "button",
          {
            type: "button",
            class: `switcher-button${Ee ? " is-active" : ""}`,
            onClick: ee,
            children: "播放列表"
          }
        )
      ] }),
      X !== "none" ? /* @__PURE__ */ b("div", { class: "content-panel", children: X === "queue" ? /* @__PURE__ */ b(
        Hc,
        {
          episodes: A,
          playbackState: x,
          playedPositions: e.playedPositions,
          onPlayNow: u,
          onComplete: c,
          onReorder: y,
          onRemove: d
        }
      ) : /* @__PURE__ */ b(
        Bc,
        {
          episodes: $e,
          playbackState: x,
          showAllLatest: B,
          onToggleFilter: i,
          onPlayNow: u,
          onEnqueueNext: h,
          onRemoveFromLatest: l,
          removedIds: ce,
          playedIds: pe,
          canLoadMore: je,
          onLoadMore: f,
          totalCount: He,
          visibleCount: le,
          filteredCount: te,
          showCounts: !!Le
        }
      ) }) : null
    ] })
  ] });
}
function Jl({ logs: e }) {
  const [t, n] = j(!1);
  return /* @__PURE__ */ b("div", { class: `dev-log${t ? " collapsed" : ""}`, role: "log", "aria-live": "polite", children: [
    /* @__PURE__ */ b("div", { class: "dev-log__toolbar", children: [
      /* @__PURE__ */ b("span", { class: "dev-log__title", children: "调试日志" }),
      /* @__PURE__ */ b("div", { style: "display:flex;gap:6px;align-items:center;", children: [
        /* @__PURE__ */ b("button", { type: "button", class: "dev-log__button", onClick: () => n(!t), children: t ? "展开" : "收起" }),
        /* @__PURE__ */ b("button", { type: "button", class: "dev-log__button", onClick: async () => {
          try {
            const o = Array.isArray(e) ? e.slice().reverse().join(`
`) : "";
            if (navigator?.clipboard?.writeText)
              await navigator.clipboard.writeText(o);
            else {
              const i = document.createElement("textarea");
              i.value = o, document.body.appendChild(i), i.select(), document.execCommand("copy"), document.body.removeChild(i);
            }
          } catch {
          }
        }, children: "复制全部" })
      ] })
    ] }),
    /* @__PURE__ */ b("div", { class: "dev-log__body", children: Array.isArray(e) && e.length > 0 ? e.map((o, i) => /* @__PURE__ */ b("div", { class: "dev-log__line", children: o }, i)) : /* @__PURE__ */ b("div", { class: "dev-log__line", children: "（暂无日志）" }) })
  ] });
}
const Mo = "xyz-popup-preact-root";
function Zl() {
  const e = document.getElementById(Mo);
  if (e)
    return e;
  const t = document.createElement("div");
  return t.id = Mo, t.style.display = "contents", document.body.appendChild(t), t;
}
const eu = Zl();
vt(/* @__PURE__ */ b(Gl, {}), eu);
//# sourceMappingURL=popup-app.js.map
