import { t as toFinite_1, j as jsxRuntimeExports } from "./root-Dsz7hNn9.js";
import { g as getDefaultExportFromCjs } from "./_commonjsHelpers-LQfde5yM.js";
import { h as _isIterateeCall } from "./_isIterateeCall-CzhxW_H_.js";
import { _ as _arrayMap, k as keys_1, a as isArray_1 } from "./_arrayMap-DyKRs1dR.js";
import { r as reactExports } from "./index-D1lRi4F5.js";
var nativeCeil = Math.ceil, nativeMax = Math.max;
function baseRange$1(start, end, step, fromRight) {
  var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length);
  while (length--) {
    result[fromRight ? length : ++index] = start;
    start += step;
  }
  return result;
}
var _baseRange = baseRange$1;
var baseRange = _baseRange, isIterateeCall = _isIterateeCall, toFinite = toFinite_1;
function createRange$1(fromRight) {
  return function(start, end, step) {
    if (step && typeof step != "number" && isIterateeCall(start, end, step)) {
      end = step = void 0;
    }
    start = toFinite(start);
    if (end === void 0) {
      end = start;
      start = 0;
    } else {
      end = toFinite(end);
    }
    step = step === void 0 ? start < end ? 1 : -1 : toFinite(step);
    return baseRange(start, end, step, fromRight);
  };
}
var _createRange = createRange$1;
var createRange = _createRange;
var range = createRange();
var range_1 = range;
const range$1 = /* @__PURE__ */ getDefaultExportFromCjs(range_1);
var nativeFloor = Math.floor, nativeRandom = Math.random;
function baseRandom$1(lower, upper) {
  return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
var _baseRandom = baseRandom$1;
var baseRandom = _baseRandom;
function arraySample$2(array) {
  var length = array.length;
  return length ? array[baseRandom(0, length - 1)] : void 0;
}
var _arraySample = arraySample$2;
var arrayMap = _arrayMap;
function baseValues$1(object, props) {
  return arrayMap(props, function(key) {
    return object[key];
  });
}
var _baseValues = baseValues$1;
var baseValues = _baseValues, keys = keys_1;
function values$1(object) {
  return object == null ? [] : baseValues(object, keys(object));
}
var values_1 = values$1;
var arraySample$1 = _arraySample, values = values_1;
function baseSample$1(collection) {
  return arraySample$1(values(collection));
}
var _baseSample = baseSample$1;
var arraySample = _arraySample, baseSample = _baseSample, isArray = isArray_1;
function sample(collection) {
  var func = isArray(collection) ? arraySample : baseSample;
  return func(collection);
}
var sample_1 = sample;
const sample$1 = /* @__PURE__ */ getDefaultExportFromCjs(sample_1);
const agents = [
  "Bonzi",
  "Clippy",
  "F1",
  "Genie",
  "Genius",
  "Links",
  "Merlin",
  "Peedy",
  "Rocky",
  "Rover"
];
const cache = /* @__PURE__ */ new Map();
function getAgentUrl(agent) {
  return `https://esm.sh/gh/paperclipjs/paperclip.js/agents/${agent}.js`;
}
function getIconUrl(agent) {
  return `https://esm.sh/gh/paperclipjs/paperclip.js/icons/${agent}.png`;
}
function getSpriteUrl(agent) {
  return `https://esm.sh/gh/paperclipjs/paperclip.js/sprites/${agent}.png`;
}
async function load(agent) {
  if (cache.has(agent))
    return;
  const m = await import(
    /* @vite-ignore */
    getAgentUrl(agent)
  );
  cache.set(agent, m.default);
  await new Promise((resolve, reject) => {
    const img = new Image();
    img.addEventListener("load", resolve);
    img.addEventListener("error", reject);
    img.src = getSpriteUrl(agent);
  });
}
function read(agent) {
  const agentConfig = cache.get(agent);
  if (!agentConfig)
    throw load(agent);
  return agentConfig;
}
const Paperclipjs = reactExports.forwardRef((props, ref) => {
  const agentConfig = read(props.agent);
  const [animations, setAnimations] = reactExports.useState([]);
  function play(name) {
    if (!(name in agentConfig.animations))
      return false;
    setAnimations((animations2) => {
      if (animations2.length > 0)
        animations2[0].exiting = true;
      return [...animations2, { name, index: 0 }];
    });
    return true;
  }
  function animate() {
    const animations2 = Object.keys(agentConfig.animations).filter((name) => !name.includes("Idle"));
    play(String(sample$1(animations2)));
  }
  reactExports.useImperativeHandle(ref, () => ({ play, animate }), [props.agent]);
  reactExports.useEffect(() => {
    setAnimations([]);
  }, [props.agent]);
  reactExports.useEffect(() => {
    if (animations.length === 0) {
      const animations2 = Object.keys(agentConfig.animations).filter((name2) => name2.includes("Idle"));
      setAnimations([{ name: String(sample$1(animations2)), index: 0 }]);
      return;
    }
    const { name, index } = animations[0];
    const animation2 = agentConfig.animations[name];
    if (index === animation2.frames.length) {
      setAnimations((animations2) => animations2.slice(1));
      return;
    }
    const frame2 = animation2.frames[index];
    const timeout = setTimeout(() => {
      setAnimations((animations2) => {
        const { name: name2, index: index2, exiting } = animations2[0];
        const animation3 = agentConfig.animations[name2];
        const frame3 = animation3.frames[index2];
        let nextIndex = index2 + 1;
        if (exiting && frame3.exitBranch) {
          nextIndex = frame3.exitBranch;
        } else if (frame3.branching) {
          let random = Math.random() * 100;
          for (const branch of frame3.branching.branches) {
            if (random <= branch.weight) {
              nextIndex = branch.frameIndex;
              break;
            }
            random -= branch.weight;
          }
        }
        return [{ name: name2, index: nextIndex, exiting }, ...animations2.slice(1)];
      });
    }, frame2.duration);
    return () => clearTimeout(timeout);
  }, [animations]);
  const animation = animations.length > 0 ? agentConfig.animations[animations[0].name] : void 0;
  const frame = animation ? animation.frames[animations[0].index] : void 0;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      width: props.width,
      height: props.height,
      viewBox: `0 0 ${agentConfig.framesize[0]} ${agentConfig.framesize[1]}`,
      className: props.className,
      style: { aspectRatio: agentConfig.framesize[0] / agentConfig.framesize[1], ...props.style },
      onClick: () => animate(),
      children: range$1(agentConfig.overlayCount).map((index) => {
        var _a;
        const image = (_a = frame == null ? void 0 : frame.images) == null ? void 0 : _a[index];
        if (index > 0 && !image)
          return;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "image",
          {
            x: -((image == null ? void 0 : image[0]) ?? 0),
            y: -((image == null ? void 0 : image[1]) ?? 0),
            width: agentConfig.spritesize[0],
            height: agentConfig.spritesize[1],
            href: getSpriteUrl(props.agent)
          },
          index
        );
      })
    }
  );
});
export {
  agents,
  Paperclipjs as default,
  getAgentUrl,
  getIconUrl,
  getSpriteUrl,
  load,
  read
};
//# sourceMappingURL=paperclipjs-CxxcVD81.js.map
