import { isBrowser as Nn } from "@qwik.dev/core/build";
const si = Nn ? document : void 0;
const config = { t: 0, i: 25, S: 0.65 };
const oi = Nn && si.createElement("link").relList.supports("modulepreload") ? "modulePreload" : "preload";
const loadStart = Date.now();
const li = /\.[mc]?js$/;
const BundleImportState_None = 0;
const BundleImportState_Queued = 1;
const BundleImportState_Preload = 2;
const BundleImportState_Alias = 3;
const BundleImportState_Loaded = 4;
const ui = /* @__PURE__ */ new Map();
let queueDirty;
let fi = 0;
const ai = [];
const log = (...e) => {
  console.log(`Preloader ${Date.now() - loadStart}ms ${fi}/${ai.length} queued>`, ...e);
};
const sortQueue = () => {
  if (queueDirty) {
    ai.sort((e, t) => e.Tt - t.Tt);
    queueDirty = 0;
  }
};
const hi = () => {
  if (!ai.length) return;
  sortQueue();
  while (ai.length) {
    const e = ai[0];
    const t = e.Tt;
    const o = 1 - t;
    const n = graph ? config.i : (
      // While the graph is not available, we limit to 5 preloads
      5
    );
    if (o >= 0.99 || fi < n) {
      ai.shift();
      di(e);
    } else break;
  }
  if (config.t && !ai.length) {
    const e = [...ui.values()].filter((e2) => e2.Nt > BundleImportState_None);
    const t = e.reduce((e2, t2) => e2 + t2.Lt, 0);
    const o = e.reduce((e2, t2) => e2 + t2.zt, 0);
    log(`>>>> done ${e.length}/${ui.size} total: ${t}ms waited, ${o}ms loaded`);
  }
};
const di = (e) => {
  if (e.Nt >= BundleImportState_Preload) return;
  fi++;
  const t = Date.now();
  e.Lt = t - e.Ft;
  e.Nt = BundleImportState_Preload;
  config.t && log(`<< load ${Math.round((1 - e.Tt) * 100)}% after ${`${e.Lt}ms`}`, e.It);
  const o = si.createElement("link");
  o.href = new URL(`${base}${e.It}`, si.baseURI).toString();
  o.rel = oi;
  o.as = "script";
  o.onload = o.onerror = () => {
    fi--;
    const n = Date.now();
    e.zt = n - t;
    e.Nt = BundleImportState_Loaded;
    config.t && log(`>> done after ${e.zt}ms`, e.It);
    o.remove();
    hi();
  };
  si.head.appendChild(o);
};
const pi = (e, t, o) => {
  if (o?.has(e)) return;
  const n = e.Tt;
  e.Tt = t;
  if (n - e.Tt < 0.01) return;
  if (
    // don't queue until we have initialized the preloader
    base != null && e.Nt < BundleImportState_Preload
  ) {
    if (e.Nt === BundleImportState_None) {
      e.Nt = BundleImportState_Queued;
      ai.push(e);
      config.t && log(`queued ${Math.round((1 - e.Tt) * 100)}%`, e.It);
    }
    queueDirty = 1;
  }
  if (e.Mt) {
    o ||= /* @__PURE__ */ new Set();
    o.add(e);
    const t2 = 1 - e.Tt;
    for (const n2 of e.Mt) {
      const e2 = ci(n2.It);
      if (e2.Tt === 0) continue;
      let r;
      if (t2 === 1 || t2 >= 0.99 && yi < 100) {
        yi++;
        r = Math.min(0.01, 1 - n2.Dt);
      } else {
        const o2 = 1 - n2.Dt * t2;
        const s = n2.Wt;
        const l = o2 / s;
        r = Math.max(0.02, e2.Tt * l);
        n2.Wt = l;
      }
      pi(e2, r, o);
    }
  }
};
const $i = (e, t) => {
  const o = ci(e);
  if (o && o.Tt > t) pi(o, t);
};
let yi;
const preload = (e, t) => {
  if (!e?.length) return;
  yi = 0;
  let o = t ? 1 - t : 0.4;
  if (Array.isArray(e)) for (let t2 = e.length - 1; t2 >= 0; t2--) {
    const n = e[t2];
    if (typeof n === "number") o = 1 - n / 10;
    else $i(n, o);
  }
  else $i(e, o);
  if (Nn) hi();
};
if (Nn) document.addEventListener("qsymbol", (e) => {
  const { symbol: t, href: o } = e.detail;
  if (o) {
    const e2 = t.slice(t.lastIndexOf("_") + 1);
    preload(e2, 1);
  }
});
let base;
let graph;
const makeBundle = (e, t) => ({ It: e, Nt: li.test(e) ? BundleImportState_None : BundleImportState_Alias, Mt: t, Tt: 1, Ft: Date.now(), Lt: 0, zt: 0 });
const parseBundleGraph = (e) => {
  const t = /* @__PURE__ */ new Map();
  let o = 0;
  while (o < e.length) {
    const n = e[o++];
    const r = [];
    let s;
    let l = 1;
    while (s = e[o], typeof s === "number") {
      if (s < 0) l = -s / 10;
      else r.push({ It: e[s], Dt: l, Wt: 1 });
      o++;
    }
    t.set(n, r);
  }
  return t;
};
const ci = (e) => {
  let t = ui.get(e);
  if (!t) {
    let o;
    if (graph) {
      o = graph.get(e);
      if (!o) return;
      if (!o.length) o = void 0;
    }
    t = makeBundle(e, o);
    ui.set(e, t);
  }
  return t;
};
const loadBundleGraph = (e, t, o) => {
  if (o) {
    if ("d" in o) config.t = !!o.d;
    if ("P" in o) config.i = o["P"];
    if ("Q" in o) config.S = 1 - o["Q"];
  }
  if (!Nn || e == null) return;
  base = e;
  if (t) t.then((e2) => e2.text()).then((e2) => {
    graph = parseBundleGraph(JSON.parse(e2));
    const t2 = [];
    for (const [e3, o2] of graph.entries()) {
      const n = ci(e3);
      n.Mt = o2;
      if (n.Tt < 1) {
        t2.push([n, n.Tt]);
        n.Tt = 1;
      }
    }
    config.t && log(`parseBundleGraph got ${graph.size} bundles, adjusting ${t2.length}`);
    for (const [e3, o2] of t2) pi(e3, o2);
    hi();
  }).catch(console.warn);
};
export {
  parseBundleGraph as g,
  $i as h,
  loadBundleGraph as l,
  preload as p
};
