import { useLocale, useProgramId, useQuery, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { useMemo } from "@saasquatch/universal-hooks";
import debugFn from "debug";
import { gql } from "graphql-request";
import { pathToRegexp } from "path-to-regexp";
import { useChildElements } from "../../tables/useChildElements";
const debug = debugFn("sq:useBigStat");
const LOADING = "...";
const debugQuery = (query, variables, getStat) => {
  const res = useQuery(query, variables);
  if (!(res === null || res === void 0 ? void 0 : res.data) && !res.loading) {
    console.error("issue getting stat:", res);
  }
  const stat = getStat(res);
  return { ...stat, loading: res.loading };
};
const referralsCountQuery = (programId, 
// locale
_, status) => {
  const programFilter = programId === "classic"
    ? { programId_exists: false }
    : { programId_eq: programId };
  const convertedFilter = status && status == "converted"
    ? { dateConverted_exists: true }
    : status && status == "started"
      ? { dateConverted_exists: false }
      : {};
  const queryFilter = { ...programFilter, ...convertedFilter };
  return debugQuery(gql `
      query ($queryFilter: ReferralFilterInput) {
        viewer {
          ... on User {
            referrals(filter: $queryFilter) {
              totalCount
            }
          }
        }
      }
    `, { queryFilter }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.referrals) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.referrals) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const programGoalsQuery = (programId, locale, metricType, goalId) => {
  // Confirm this behaviour
  if (programId === "classic")
    return null;
  return debugQuery(gql `
      query {
        viewer {
          ... on User {
            programGoals {
              goalId
              programId
              count
              conversionCount
            }
          }
        }
      }
    `, { programId, metricType, goalId, locale }, (res) => {
    var _a, _b, _c, _d, _e, _f;
    const goal = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.programGoals) === null || _c === void 0 ? void 0 : _c.filter((goal) => goal.goalId === goalId && goal.programId === programId);
    return {
      value: ((_d = goal === null || goal === void 0 ? void 0 : goal[0]) === null || _d === void 0 ? void 0 : _d[metricType]) || 0,
      statvalue: ((_f = (_e = goal === null || goal === void 0 ? void 0 : goal[0]) === null || _e === void 0 ? void 0 : _e[metricType]) === null || _f === void 0 ? void 0 : _f.toString()) || 0,
    };
  });
};
const customFieldsQuery = (_programId, locale, fieldName, goalId) => {
  return debugQuery(gql `
      query {
        viewer {
          ... on User {
            customFields
          }
        }
      }
    `, { fieldName, goalId, locale }, (res) => {
    var _a, _b, _c;
    const customField = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.customFields) === null || _c === void 0 ? void 0 : _c[fieldName];
    return {
      value: customField || 0,
      statvalue: (customField === null || customField === void 0 ? void 0 : customField.toString()) || "0",
    };
  });
};
const referralsMonthQuery = (programId, 
// locale
_, status) => {
  const programFilter = programId === "classic"
    ? { programId_exists: false }
    : { programId_eq: programId };
  const convertedFilter = status && status == "converted"
    ? { dateConverted_exists: true }
    : status && status == "started"
      ? { dateConverted_exists: false }
      : {};
  const filter = {
    ...programFilter,
    ...convertedFilter,
    dateReferralStarted_timeframe: "this_month",
  };
  return debugQuery(gql `
      query ($filter: ReferralFilterInput) {
        viewer {
          ... on User {
            referrals(filter: $filter) {
              totalCount
            }
          }
        }
      }
    `, { filter }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.referrals) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.referrals) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const referralsWeekQuery = (programId, 
// locale
_, status) => {
  const programFilter = programId === "classic"
    ? { programId_exists: false }
    : { programId_eq: programId };
  const convertedFilter = status && status == "converted"
    ? { dateConverted_exists: true }
    : status && status == "started"
      ? { dateConverted_exists: false }
      : {};
  const filter = {
    ...programFilter,
    ...convertedFilter,
    dateReferralStarted_timeframe: "this_week",
  };
  return debugQuery(gql `
      query ($filter: ReferralFilterInput) {
        viewer {
          ... on User {
            referrals(filter: $filter) {
              totalCount
            }
          }
        }
      }
    `, { filter }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.referrals) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.referrals) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const rewardsCountQuery = (programId, 
// locale
_, global = "") => {
  return debugQuery(gql `
      query ($programId: ID) {
        viewer {
          ... on User {
            rewards(filter: { programId_eq: $programId }) {
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
  }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.rewards) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const rewardsCountFilteredQuery = (programId, 
// locale
_, type, unit, status, global = "") => {
  const statusFilter = status ? { status } : null;
  return debugQuery(gql `
      query (
        $programId: ID
        $unit: String
        $type: RewardType
        $statusFilter: RewardStatusFilterInput
      ) {
        viewer {
          ... on User {
            rewards(
              filter: {
                programId_eq: $programId
                type_eq: $type
                unit_eq: $unit
                statuses_eq: $statusFilter
              }
            ) {
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    unit,
    type,
    statusFilter,
  }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.rewards) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const integrationRewardsCountFilteredQuery = (programId, 
// locale
_, status, global = "") => {
  const statusFilter = status ? { status } : null;
  return debugQuery(gql `
      query ($programId: ID, $statusFilter: RewardStatusFilterInput) {
        viewer {
          ... on User {
            rewards(
              filter: {
                programId_eq: $programId
                type_eq: INTEGRATION
                statuses_eq: $statusFilter
              }
            ) {
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    statusFilter,
  }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.rewards) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const rewardsMonthQuery = (programId, 
// locale
_, global = "") => {
  return debugQuery(gql `
      query ($programId: ID) {
        viewer {
          ... on User {
            rewards(
              filter: {
                programId_eq: $programId
                dateGiven_timeframe: "this_month"
              }
            ) {
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
  }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.rewards) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const rewardsWeekQuery = (programId, 
// locale
_, global = "") => {
  return debugQuery(gql `
      query ($programId: ID) {
        viewer {
          ... on User {
            rewards(
              filter: {
                programId_eq: $programId
                dateGiven_timeframe: "this_week"
              }
            ) {
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
  }, (res) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return ({
      value: ((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.totalCount) || 0,
      statvalue: (_g = (_f = (_e = (_d = res.data) === null || _d === void 0 ? void 0 : _d.viewer) === null || _e === void 0 ? void 0 : _e.rewards) === null || _f === void 0 ? void 0 : _f.totalCount) === null || _g === void 0 ? void 0 : _g.toString(),
    });
  });
};
const rewardsPendingQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyPendingCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyPendingCredit) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyPendingCredit) || fallback,
    };
  });
};
const rewardsRedeemedQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyRedeemedCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyRedeemedCredit) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyRedeemedCredit) || fallback,
    };
  });
};
const rewardsRedeemedWeekQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query ($programId: ID, $type: RewardType, $unit: String!) {
        viewer: viewer {
          ... on User {
            rewards(
              limit: 1000
              filter: {
                programId_eq: $programId
                type_eq: $type
                unit_eq: $unit
                dateRedeemed_timeframe: "this_week"
              }
            ) {
              data {
                redeemedCredit
              }
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
  }, (res) => {
    var _a, _b, _c, _d;
    const rewardData = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.data;
    const fallback = 0;
    const redeemedTotal = rewardData === null || rewardData === void 0 ? void 0 : rewardData.reduce((total, reward) => (total += reward.redeemedCredit), fallback);
    if (redeemedTotal !== undefined) {
      const query = `query formatRewardPrettyValue(
          $value: Int!
          $unit: String!
          $locale: RSLocale
        ) {
          formatRewardPrettyValue(
          value: $value
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )}`;
      const result = useQuery(query, {
        value: redeemedTotal,
        unit,
        locale,
      });
      return {
        value: redeemedTotal || fallback,
        statvalue: (_d = result === null || result === void 0 ? void 0 : result.data) === null || _d === void 0 ? void 0 : _d.formatRewardPrettyValue,
      };
    }
    return {
      value: fallback,
      statvalue: "...",
    };
  });
};
const rewardsRedeemedMonthQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query ($programId: ID, $type: RewardType, $unit: String!) {
        viewer: viewer {
          ... on User {
            rewards(
              limit: 1000
              filter: {
                programId_eq: $programId
                type_eq: $type
                unit_eq: $unit
                dateRedeemed_timeframe: "this_month"
              }
            ) {
              data {
                redeemedCredit
              }
              totalCount
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
  }, (res) => {
    var _a, _b, _c, _d;
    const rewardData = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewards) === null || _c === void 0 ? void 0 : _c.data;
    const fallback = 0;
    const redeemedTotal = rewardData === null || rewardData === void 0 ? void 0 : rewardData.reduce((total, reward) => (total += reward.redeemedCredit), fallback);
    if (redeemedTotal !== undefined) {
      const query = `query formatRewardPrettyValue(
          $value: Int!
          $unit: String!
          $locale: RSLocale
        ) {
          formatRewardPrettyValue(
          value: $value
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )}`;
      const result = useQuery(query, {
        value: redeemedTotal,
        unit,
        locale,
      });
      return {
        value: redeemedTotal || fallback,
        statvalue: (_d = result === null || result === void 0 ? void 0 : result.data) === null || _d === void 0 ? void 0 : _d.formatRewardPrettyValue,
      };
    }
    return {
      value: fallback,
      statvalue: "...",
    };
  });
};
const rewardsAssignedQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyAssignedCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyAssignedCredit) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyAssignedCredit) || fallback,
    };
  });
};
const rewardsExpiredQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyExpiredCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyExpiredCredit) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyExpiredCredit) || fallback,
    };
  });
};
const rewardsCancelledQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyCancelledCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyCancelledCredit) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyCancelledCredit) || fallback,
    };
  });
};
const rewardsAvailableQuery = (programId, locale, type, unit, global = "") => {
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType
        $unit: String!
        $locale: RSLocale
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: UNIT_FORMATTED
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                prettyAvailableValue
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
  }, (res) => {
    var _a, _b, _c, _d, _e;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    return {
      value: ((_d = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _d === void 0 ? void 0 : _d.prettyAvailableValue) || 0,
      statvalue: ((_e = arr === null || arr === void 0 ? void 0 : arr[0]) === null || _e === void 0 ? void 0 : _e.prettyAvailableValue) || fallback,
    };
  });
};
const parseRewardValueFormat = {
  prettyValue: "UNIT_FORMATTED",
  value: "NUMBER_UNFORMATTED",
};
const rewardsBalanceQuery = (programId, locale, type, unit, format = "prettyValue", global = "") => {
  var _a;
  const formatType = (_a = parseRewardValueFormat[format]) !== null && _a !== void 0 ? _a : "UNIT_FORMATTED";
  return debugQuery(gql `
      query (
        $programId: ID
        $type: RewardType!
        $unit: String!
        $locale: RSLocale
        $format: RewardValueFormatType!
      ) {
        fallback: formatRewardPrettyValue(
          value: 0
          unit: $unit
          locale: $locale
          formatType: $format
        )
        viewer: viewer {
          ... on User {
            rewardBalanceDetails(
              programId: $programId
              filter: { type_eq: $type, unit_eq: $unit }
              locale: $locale
            ) {
              ... on CreditRewardBalance {
                totalAssignedCredit
                totalPendingCredit
              }
            }
          }
        }
      }
    `, {
    programId: !global && programId !== "classic" ? programId : null,
    type,
    unit,
    locale,
    format: formatType,
  }, (res) => {
    var _a, _b, _c, _d;
    const arr = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.rewardBalanceDetails;
    const fallback = (_c = res.data) === null || _c === void 0 ? void 0 : _c.fallback;
    const balance = arr === null || arr === void 0 ? void 0 : arr[0];
    const totalEarned = balance
      ? (balance.totalAssignedCredit || 0) +
        (balance.totalPendingCredit || 0)
      : 0;
    const result = useQuery(gql `
          query (
            $value: Int!
            $unit: String!
            $locale: RSLocale
            $format: RewardValueFormatType!
          ) {
            formatRewardPrettyValue(
              value: $value
              unit: $unit
              locale: $locale
              formatType: $format
            )
          }
        `, {
      value: totalEarned,
      unit,
      locale,
      format: formatType,
    }, res.loading);
    return {
      value: totalEarned,
      statvalue: ((_d = result === null || result === void 0 ? void 0 : result.data) === null || _d === void 0 ? void 0 : _d.formatRewardPrettyValue) || fallback,
    };
  });
};
const trafficQuery = () => {
  return debugQuery(gql `
      query traffic {
        viewer: viewer {
          ... on User {
            stats {
              traffic
            }
          }
        }
      }
    `, {}, (res) => {
    var _a, _b, _c;
    const traffic = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.stats) === null || _c === void 0 ? void 0 : _c.traffic;
    const fallback = 0;
    return {
      value: traffic || fallback,
      statvalue: traffic || fallback,
    };
  });
};
const userStatsQuery = (_programId, _locale, statId) => {
  const statArg = {
    [statId]: true,
  };
  const variables = {
    traffic: false,
    referrals: false,
    conversions: false,
    goals: false,
    rewards: false,
    widgetLoads: false,
    revenue: false,
    generatedRevenue: false,
    referredRevenue: false,
    ...statArg,
  };
  return debugQuery(gql `
      query userStat(
        $traffic: Boolean!
        $referrals: Boolean!
        $conversions: Boolean!
        $goals: Boolean!
        $rewards: Boolean!
        $widgetLoads: Boolean!
        $revenue: Boolean!
        $generatedRevenue: Boolean!
        $referredRevenue: Boolean!
      ) {
        viewer: viewer {
          ... on User {
            stats {
              traffic @include(if: $traffic)
              referrals @include(if: $referrals)
              conversions @include(if: $conversions)
              goals @include(if: $goals)
              rewards @include(if: $rewards)
              widgetLoads @include(if: $widgetLoads)
              revenue @include(if: $revenue)
              generatedRevenue @include(if: $generatedRevenue)
              referredRevenue @include(if: $referredRevenue)
            }
          }
        }
      }
    `, { ...variables }, (res) => {
    var _a, _b, _c;
    const stat = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.stats) === null || _c === void 0 ? void 0 : _c[statId];
    const fallback = 0;
    return {
      value: stat || fallback,
      statvalue: stat || fallback,
    };
  });
};
const payoutBalanceQuery = () => {
  return debugQuery(gql `
      query payoutBalance {
        viewer: viewer {
          ... on User {
            id
            impactConnection {
              publisher {
                payoutsAccount {
                  balance
                }
              }
            }
          }
        }
      }
    `, {}, (res) => {
    var _a, _b, _c, _d;
    const fallback = 0;
    const balance = (_d = (_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.publisher) === null || _c === void 0 ? void 0 : _c.payoutsAccount) === null || _d === void 0 ? void 0 : _d.balance;
    const balanceText = `${balance || fallback}`;
    return {
      value: balance || fallback,
      statvalue: balanceText,
    };
  });
};
// functions are of the form (programId: string, ...args: string) => string
export const queries = {
  rewardsAssigned: {
    label: "Rewards Earned",
    query: rewardsAssignedQuery,
  },
  rewardsPending: {
    label: "Rewards Pending",
    query: rewardsPendingQuery,
  },
  rewardsExpired: {
    label: "Rewards Expired",
    query: rewardsExpiredQuery,
  },
  rewardsCancelled: {
    label: "Rewards Cancelled",
    query: rewardsCancelledQuery,
  },
  rewardsRedeemed: {
    label: "Rewards Paid",
    query: rewardsRedeemedQuery,
  },
  rewardsRedeemedMonth: {
    label: "Rewards Paid - This Month",
    query: rewardsRedeemedMonthQuery,
  },
  rewardsRedeemedWeek: {
    label: "Rewards Paid - This Week",
    query: rewardsRedeemedWeekQuery,
  },
  rewardsAvailable: {
    label: "Rewards Available",
    query: rewardsAvailableQuery,
  },
  referralsCount: {
    label: "Referrals - Count",
    query: referralsCountQuery,
  },
  referralsMonth: {
    label: "Referrals - This Month",
    query: referralsMonthQuery,
  },
  referralsWeek: {
    label: "Referrals - This Week",
    query: referralsWeekQuery,
  },
  rewardsCount: {
    label: "Rewards",
    query: rewardsCountQuery,
  },
  rewardsCountFiltered: {
    label: "Rewards",
    query: rewardsCountFilteredQuery,
  },
  integrationRewardsCountFiltered: {
    label: "Rewards",
    query: integrationRewardsCountFilteredQuery,
  },
  rewardsMonth: {
    label: "Rewards - This Month",
    query: rewardsMonthQuery,
  },
  rewardsWeek: {
    label: "Rewards - This Week",
    query: rewardsWeekQuery,
  },
  rewardBalance: {
    label: "Balance - Credit Earned",
    query: rewardsBalanceQuery,
  },
  programGoals: {
    label: "Program Goals",
    query: programGoalsQuery,
  },
  customFields: {
    label: "Custom Fields",
    query: customFieldsQuery,
  },
  traffic: {
    label: "Traffic",
    query: trafficQuery,
  },
  userStats: {
    label: "User Stat",
    query: userStatsQuery,
  },
  payoutBalance: {
    label: "Payout Balance",
    query: payoutBalanceQuery,
  },
};
// ! Any update to this should be reflected in StatPathBuilder.tsx in the saasquatch repo
// this should be exposed in documentation somehow
export const StatPaths = [
  { name: "programGoals", route: "/(programGoals)/:metricType/:goalId" },
  { name: "customFields", route: "/(customFields)/:customField" },
  { name: "referralsCount", route: "/(referralsCount)/:status?" },
  { name: "referralsMonth", route: "/(referralsMonth)/:status?" },
  { name: "referralsWeek", route: "/(referralsWeek)/:status?" },
  { name: "rewardsCount", route: "/(rewardsCount)/:global?" },
  { name: "rewardsMonth", route: "/(rewardsMonth)/:global?" },
  { name: "rewardsWeek", route: "/(rewardsWeek)/:global?" },
  {
    name: "rewardsCountFiltered",
    route: "/(rewardsCountFiltered)/:statType([FUELTANK|INTEGRATION|PCT_DISCOUNT|CREDIT]*)?/:unit((?!global)(?!PENDING)(?!CANCELLED)(?!EXPIRED)(?!REDEEMED)(?!AVAILABLE)[a-zA-Z0-9%]+)?/:status([PENDING|CANCELLED|EXPIRED|REDEEMED|AVAILABLE]*)?/:global?",
  },
  {
    name: "integrationRewardsCountFiltered",
    route: "/(integrationRewardsCountFiltered)/:status([PENDING|CANCELLED|EXPIRED|REDEEMED|AVAILABLE]*)?/:global?",
  },
  {
    name: "rewardsAssigned",
    route: "/(rewardsAssigned)/:statType/:unit/:global?",
  },
  {
    name: "rewardsExpired",
    route: "/(rewardsExpired)/:statType/:unit/:global?",
  },
  {
    name: "rewardsCancelled",
    route: "/(rewardsCancelled)/:statType/:unit/:global?",
  },
  {
    name: "rewardsPending",
    route: "/(rewardsPending)/:statType/:unit/:global?",
  },
  {
    name: "rewardsRedeemed",
    route: "/(rewardsRedeemed)/:statType/:unit/:global?",
  },
  {
    name: "rewardsRedeemedWeek",
    route: "/(rewardsRedeemedWeek)/:statType/:unit/:global?",
  },
  {
    name: "rewardsRedeemedMonth",
    route: "/(rewardsRedeemedMonth)/:statType/:unit/:global?",
  },
  {
    name: "rewardsAvailable",
    route: "/(rewardsAvailable)/:statType/:unit/:global?",
  },
  {
    name: "rewardBalance",
    route: "/(rewardBalance)/:statType/:unit/:format([prettyValue|value]*)?/:global?",
  },
  {
    name: "traffic",
    route: "/(traffic)",
  },
  {
    name: "userStats",
    route: "/(userStats)/:statId",
  },
  {
    name: "payoutBalance",
    route: "/(payoutBalance)",
  },
];
export const StatPatterns = StatPaths.map((pattern) => pathToRegexp(pattern.route));
export function useBigStat(props) {
  var _a;
  const { statType, flexReverse, alignment, programId = useProgramId(), } = props;
  // triggers a re-render if the label is manually changed
  useChildElements();
  const locale = useLocale();
  const userIdent = useUserIdentity();
  const re = useMemo(() => StatPatterns.find((re) => re.exec(statType)), [statType]);
  if (!(re === null || re === void 0 ? void 0 : re.exec(statType))) {
    return {
      props: {
        value: 0,
        statvalue: "-",
        flexReverse,
        alignment,
        loading: false,
        statTextColor: props.statTextColor,
        statFontSize: props.statFontSize,
        descriptionTextColor: props.descriptionTextColor,
        descriptionFontSize: props.descriptionFontSize,
        statFontWeight: props.statFontWeight,
      },
      label: "BAD PROP TYPE",
    };
  }
  const result = re.exec(statType);
  const queryName = result[1];
  const statPath = StatPaths.find((pattern) => pattern.name === queryName);
  // Get a list all possible keys in path
  const keys = [];
  const regex = pathToRegexp(statPath === null || statPath === void 0 ? void 0 : statPath.route, keys, {
    strict: false,
    sensitive: false,
    end: true,
  });
  const allQueryArgs = regex.exec(statType);
  // Retrieve all key values in order including undefined
  const queryArgs = keys.map((_, i) => allQueryArgs[i + 1] ? decodeURIComponent(allQueryArgs[i + 1]) : undefined);
  //  remove query name from list
  queryArgs.shift();
  const label = queries[queryName].label;
  const stat = (userIdent === null || userIdent === void 0 ? void 0 : userIdent.jwt) && queries[queryName].query(programId, locale, ...queryArgs);
  debug("stat:", stat);
  return {
    props: {
      value: stat === null || stat === void 0 ? void 0 : stat.value,
      statvalue: (_a = stat === null || stat === void 0 ? void 0 : stat.statvalue) !== null && _a !== void 0 ? _a : LOADING,
      loading: stat === null || stat === void 0 ? void 0 : stat.loading,
      flexReverse,
      alignment,
      statTextColor: props.statTextColor,
      statFontSize: props.statFontSize,
      descriptionTextColor: props.descriptionTextColor,
      descriptionFontSize: props.descriptionFontSize,
      statFontWeight: props.statFontWeight,
    },
    label,
  };
}
