(function (root, factory) {
  const api = factory();
  if (typeof module === "object" && module.exports) module.exports = api;
  root.MMWPluginFeatureAccess = api;
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  const SOURCE_TRACE = "source_trace";
  const ECOMMERCE_TOOL = "ecommerce_tool";

  function read(auth, featureKey) {
    const account = isObject(auth?.account) ? auth.account : {};
    const features = isObject(account.plugin_features) ? account.plugin_features : {};
    const feature = isObject(features[featureKey]) ? features[featureKey] : {};
    return {
      featureKey,
      visible: feature.visible === true,
      enabled: feature.enabled === true,
      mode: String(feature.mode || "auto"),
      reason: String(feature.reason || "当前账号未开通该插件功能。"),
      unlockThresholdPoints: numberValue(feature.unlock_threshold_points),
      cumulativeRechargedPoints: numberValue(feature.cumulative_recharged_points)
    };
  }

  function isVisible(auth, featureKey) {
    return Boolean(auth?.loggedIn && read(auth, featureKey).visible);
  }

  function canUse(auth, featureKey) {
    return Boolean(auth?.loggedIn && read(auth, featureKey).enabled);
  }

  function deniedReason(auth, featureKey) {
    if (!auth?.loggedIn) return "请先登录 MMW工作台账号";
    return read(auth, featureKey).reason;
  }

  function isObject(value) {
    return Boolean(value && typeof value === "object" && !Array.isArray(value));
  }

  function numberValue(value) {
    const number = Number(value);
    return Number.isFinite(number) ? Math.max(0, Math.trunc(number)) : 0;
  }

  return {
    SOURCE_TRACE,
    ECOMMERCE_TOOL,
    read,
    isVisible,
    canUse,
    deniedReason
  };
});
