import { h, r as registerInstance, c as Host } from './index-38ad4957.js';
import { i as intl } from './global-96c14d63.js';
import { b as browser, j as useReducer, f as useEffect, n as h$1, u as useMemo } from './dom-context-hooks.module-50442785.js';
import { d as dist, J, H, L, w as wn, R as Rn, i as isDemo } from './index.module-b23fdad8.js';
import { c as cjs } from './cjs-bdfb4486.js';
import { l as luxonLocale } from './utils-334c1e34.js';
import { c as createStyleSheet } from './JSS-67b5cff8.js';
import './mixins-f750863a.js';
import { G as GenericTableView } from './GenericTableView-8c72ac30.js';
import { u as useRerenderListener, a as useRequestRerender } from './re-render-f30aeb6b.js';
import { u as useChildElements } from './useChildElements-9bccfb72.js';
import { l as luxon } from './luxon-1be92a8e.js';
import { m as mockRewardData } from './mockRewardData-9b27d6f1.js';
import { g as generateUserError } from './useReferralTable-92af4133.js';

const debug = browser("sq:useRewardsTable");
const CSS_NAMESPACE = "sqm-rewards-table";
const GET_REWARDS = dist.gql `
  query getRewards(
    $limit: Int!
    $offset: Int!
    $rewardFilter: RewardFilterInput
    $locale: RSLocale
  ) {
    viewer {
      ... on User {
        id
        rewards(
          limit: $limit
          offset: $offset
          filter: $rewardFilter
          sortBy: { field: "dateCreated", order: DESC }
        ) {
          totalCount
          count
          data {
            meta {
              status
              integration {
                name
              }
              message
              customMeta
            }
            id
            type
            value
            unit
            name
            dateGiven
            dateCreated
            dateExpires
            dateCancelled
            dateRedeemed
            dateScheduledFor
            fuelTankCode
            fuelTankType
            currency
            prettyValue(locale: $locale)
            prettyValueNumber: prettyValue(
              formatType: NUMBER_FORMATTED
              locale: $locale
            )
            prettyAvailableNumber: prettyAvailableValue(
              formatType: NUMBER_FORMATTED
              locale: $locale
            )
            prettyRedeemedNumber: prettyRedeemedCredit(
              formatType: NUMBER_FORMATTED
              locale: $locale
            )
            programId
            program {
              name
            }
            partnerFundsTransfer {
              id
              status
              dateScheduled
              dateCreated
              dateTransferred
            }
            statuses
            pendingReasons
            cancelledReason
            globalRewardKey
            programRewardKey
            rewardSource
            prettyRedeemedCredit(locale: $locale)
            prettyAssignedCredit(locale: $locale)
            prettyAvailableValue(locale: $locale)
            exchangedRewardRedemptionTransaction {
              id
              creditRedeemed
              prettyRedeemedCredit(locale: $locale)
              unit
              dateRedeemed
            }
            referral {
              id
              dateModerated
              referrerUser {
                id
                firstName
                lastName
              }
              referredUser {
                id
                firstName
                lastName
              }
              fraudData {
                moderationStatus
                autoModerationStatus
                manualModerationStatus
              }
            }

            rewardRedemptionTransactions {
              data {
                exchangedRewards {
                  data {
                    prettyValue(locale: $locale)
                    type
                    fuelTankCode
                    globalRewardKey
                  }
                }
              }
            }
          }
        }
      }
    }
  }
`;
const GET_IMPACT_TAX = dist.gql `
  query getImpactTax {
    viewer {
      ... on User {
        id
        impactConnection {
          connected
          taxHandlingEnabled
          publisher {
            requiredTaxDocumentType
            currentTaxDocument {
              status
              type
              dateCreated
            }
            withdrawalSettings {
              paymentMethod
            }
            payoutsAccount {
              hold
              holdReasons
              balance
            }
          }
        }
      }
    }
  }
`;
function useRewardsTable(props, emptyElement, loadingElement) {
  var _a, _b, _c;
  const user = J();
  const programIdContext = H();
  const locale = L();
  // Default to context, overriden by props
  const resolvedProgramId = (_a = props.programId) !== null && _a !== void 0 ? _a : programIdContext;
  const programId = resolvedProgramId === "GLOBAL" ? null : resolvedProgramId;
  const rewardFilter = {
    userId_eq: user === null || user === void 0 ? void 0 : user.id,
    accountId_eq: user === null || user === void 0 ? void 0 : user.accountId,
    // If no program ID, shows all programs
    ...(programId
      ? programId === "classic"
        ? { programId_exists: false }
        : { programId_eq: programId }
      : {}),
  };
  const [content, setContent] = useReducer((state, next) => ({
    ...state,
    ...next,
  }), {
    columns: [],
    rows: [],
    loading: false,
    page: 0,
  });
  const { data: impactTaxData, loading: taxLoading } = wn(GET_IMPACT_TAX, {}, !(user === null || user === void 0 ? void 0 : user.jwt));
  const { envelope: rewardsData, states, callbacks, } = Rn(GET_REWARDS, (data) => { var _a; return (_a = data === null || data === void 0 ? void 0 : data.viewer) === null || _a === void 0 ? void 0 : _a.rewards; }, {
    limit: props.perPage,
    offset: 0,
  }, {
    rewardFilter,
    locale,
  }, !(user === null || user === void 0 ? void 0 : user.jwt));
  const tick = useRerenderListener();
  const components = useChildElements();
  const data = rewardsData === null || rewardsData === void 0 ? void 0 : rewardsData.data;
  const taxConnection = (_b = impactTaxData === null || impactTaxData === void 0 ? void 0 : impactTaxData.viewer) === null || _b === void 0 ? void 0 : _b.impactConnection;
  async function getComponentData(components) {
    // filter out loading and empty states from columns array
    const columnComponents = components.filter((component) => component.slot !== "loading" && component.slot !== "empty");
    // get the column titles (renderLabel is asynchronous)
    const columnsPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c) => tryMethod(c, () => c.renderLabel()));
    // get the column cells (renderCell is asynchronous)
    const cellsPromise = data === null || data === void 0 ? void 0 : data.map(async (r) => {
      const cellPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c) => tryMethod(c, () => c.renderCell(r, { locale, taxConnection }, h)));
      const cells = (await Promise.all(cellPromise));
      return cells;
    });
    const rows = cellsPromise && (await Promise.all(cellsPromise)).filter((i) => i);
    setContent({ rows });
    const columns = columnsPromise && (await Promise.all(columnsPromise));
    // Set the content to render and finish loading components
    setContent({ columns, loading: false, page: states.currentPage });
  }
  useEffect(() => {
    setContent({ loading: true });
    rewardsData && getComponentData(components);
  }, [rewardsData, components, tick]);
  const isEmpty = !((_c = content === null || content === void 0 ? void 0 : content.rows) === null || _c === void 0 ? void 0 : _c.length) && !(data === null || data === void 0 ? void 0 : data.length);
  const show = 
  // 1 - Loading if loading
  states.loading || content.loading || taxLoading
    ? "loading"
    : // 2 - Empty if empty
      isEmpty
        ? "empty"
        : // 3 - Then show rows
          "rows";
  return {
    states: {
      hasNext: states.currentPage < states.pageCount - 1,
      hasPrev: states.currentPage > 0,
      show,
      namespace: CSS_NAMESPACE,
    },
    data: {
      textOverrides: {
        showLabels: !props.hideLabels,
        prevLabel: props.prevLabel,
        moreLabel: props.moreLabel,
      },
      hiddenColumns: props.hiddenColumns,
      smBreakpoint: props.smBreakpoint,
      mdBreakpoint: props.mdBreakpoint,
    },
    elements: {
      columns: content.columns,
      rows: content.rows,
      emptyElement,
      loadingElement,
    },
    callbacks: {
      nextPage: () => {
        callbacks.setCurrentPage(states.currentPage + 1);
      },
      prevPage: () => {
        callbacks.setCurrentPage(states.currentPage - 1);
      },
    },
  };
}
async function tryMethod(c, callback) {
  const tag = c.tagName.toLowerCase();
  await customElements.whenDefined(tag);
  let labelPromise;
  try {
    labelPromise = callback();
  }
  catch (e) {
    // renderLabel did not return a promise, so this method probably doesn't exist
    // therefore, we IGNORE the label
    debug("label promise failed", e);
    return h("span", null);
  }
  try {
    return await labelPromise;
  }
  catch (e) {
    // The column returned a promise, and that promise failed.
    // This should not happen so we fail fast
    debug("Error rendering label", e);
    const userError = generateUserError(e);
    return (h("details", null,
      h("summary", null, "Error"),
      userError));
  }
}

const RewardsTable = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /** @uiName Rewards per page */
    this.perPage = 4;
    /** @uiName Hide column labels */
    this.hideLabels = false;
    /** @uiName Previous button text  */
    this.prevLabel = "Prev";
    /** @uiName View more button text  */
    this.moreLabel = "Next";
    /**
     * Provide the column numbers (0 indexed) that should not be displayed in mobile views. Ex. 0,2,3
     *
     *  @uiName Mobile hidden columns  */
    this.hiddenColumns = "0";
    /** @uiName Mobile breakpoint  */
    this.smBreakpoint = 599;
    /** @uiName Tablet breakpoint  */
    this.mdBreakpoint = 799;
    h$1(this);
  }
  disconnectedCallback() { }
  render() {
    const empty = h(EmptySlot, null);
    const loading = h(LoadingSlot, null);
    const { states, data, callbacks, elements } = isDemo()
      ? useRewardsTableDemo(this, empty, loading)
      : useRewardsTable(this, empty, loading);
    useRequestRerender([this.perPage]);
    return (h(GenericTableView, { states: states, data: data, callbacks: callbacks, elements: elements }));
  }
};
function EmptySlot() {
  return (h("slot", { name: "empty" }, h("sqm-empty", { "empty-state-image": "https://res.cloudinary.com/saasquatch/image/upload/v1644360953/squatch-assets/empty_reward2.png", "empty-state-header": "View your rewards", "empty-state-text": "Refer friends and complete tasks to view the details of your rewards" })));
}
function LoadingSlot() {
  return (h("slot", { name: "loading" }, h(LoadingRow, null), h(LoadingRow, null), h(LoadingRow, null), h(LoadingRow, null)));
}
function LoadingRow() {
  return (h("sqm-table-row", null, h("sqm-table-cell", { colspan: 5 }, h("sqm-skeleton", null))));
}
function useRewardsTableDemo(props, emptyElement, loadingElement) {
  const [content, setContent] = useReducer((state, next) => ({
    ...state,
    ...next,
  }), {
    columns: [],
    rows: [],
    loading: false,
    page: 0,
  });
  const tick = useRerenderListener();
  const { data } = useMemo(() => { var _a; return ((_a = props.demoData) === null || _a === void 0 ? void 0 : _a.mockData) || mockRewardData(props.perPage); }, [props.perPage]);
  const components = useChildElements();
  async function getComponentData(components) {
    let componentData = data;
    componentData = data.slice(0, props.perPage);
    // filter out loading and empty states from columns array
    const columnComponents = components.filter((component) => {
      var _a, _b;
      return component.slot !== "loading" &&
        component.slot !== "empty" &&
        ((_a = component === null || component === void 0 ? void 0 : component.firstElementChild) === null || _a === void 0 ? void 0 : _a.getAttribute("slot")) !== "loading" &&
        ((_b = component === null || component === void 0 ? void 0 : component.firstElementChild) === null || _b === void 0 ? void 0 : _b.getAttribute("slot")) !== "empty";
    });
    // get the column titles (renderLabel is asynchronous)
    const columnsPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c, idx) => {
      var _a;
      const slot = (_a = c === null || c === void 0 ? void 0 : c.firstElementChild) === null || _a === void 0 ? void 0 : _a.getAttribute("slot");
      // Custom plop targets
      if (c.tagName === "RAISINS-PLOP-TARGET" &&
        slot !== "loading" &&
        slot !== "empty") {
        c.style.position = "absolute";
        c.setAttribute("slot", "column-" + idx);
        // Replace add text with a simple + button
        const plopTarget = c.firstElementChild.childNodes[1];
        plopTarget.innerHTML = "＋";
        plopTarget.style.lineHeight = "20px";
        return tryMethod(c, () => c.renderLabel(idx));
      }
      return tryMethod(c, () => c.renderLabel());
    });
    // get the column cells (renderCell is asynchronous)
    //@ts-ignore
    const cellsPromise = componentData === null || componentData === void 0 ? void 0 : componentData.map(async (r) => {
      const cellPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c) => tryMethod(c, () => c.renderCell(r, undefined, {})));
      const cells = (await Promise.all(cellPromise));
      return cells;
    });
    const rows = cellsPromise && (await Promise.all(cellsPromise)).filter((i) => i);
    // @ts-ignore
    setContent({ rows });
    const columns = columnsPromise && (await Promise.all(columnsPromise));
    // Set the content to render and finish loading components
    setContent({ columns, loading: false, page: 0 });
  }
  useEffect(() => {
    setContent({ loading: true });
    data && getComponentData(components);
  }, [data, components, tick]);
  const demoProps = cjs({
    states: {
      hasPrev: false,
      hasNext: false,
      loading: false,
      show: "rows",
    },
    callbacks: {
      prevPage: () => console.log("Prev"),
      nextPage: () => console.log("Next"),
    },
    data: {
      textOverrides: {
        showLabels: !props.hideLabels,
        prevLabel: props.prevLabel,
        moreLabel: props.moreLabel,
      },
      referralData: [],
      mdBreakpoint: 799,
      smBreakpoint: 599,
    },
    elements: {
      columns: content.columns,
      rows: content.rows,
      emptyElement,
      loadingElement,
    },
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
  return demoProps;
}

const RewardTableDateCell = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ignored = true;
    this.locale = "en";
    h$1(this);
  }
  disconnectedCallback() { }
  render() {
    var _a, _b;
    const date = !this.date
      ? "-"
      : (_b = (_a = luxon.DateTime.fromMillis(this.date)) === null || _a === void 0 ? void 0 : _a.setLocale(luxonLocale(this.locale))) === null || _b === void 0 ? void 0 : _b.toLocaleString(luxon.DateTime.DATE_MED);
    return date;
  }
};

const RewardTableDateColumn = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /**
     * @uiName Date column title
     */
    this.columnTitle = "Date received";
    /**
     * @uiName Date displayed
     * @uiType string
     * @uiEnum ["dateGiven",
     * "dateExpires",
     * "dateCancelled",
     * "dateRedeemed",
     * "dateScheduledFor"]
     * @uiEnumNames ["Date Given", "Date Expires", "Date Cancelled", "Date Redeemed", "Date Scheduled For"]
     */
    this.dateShown = "dateGiven";
    h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    return (h("sqm-rewards-table-date-cell", { date: data[this.dateShown], locale: options === null || options === void 0 ? void 0 : options.locale }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  render() {
    useRequestRerender([this.dateShown, this.columnTitle]);
    return h(Host, { style: { display: "none" } });
  }
};

const style = {
  DetailsContainer: {
    width: "100%",
    display: "flex",
    "align-items": "center",
    "justify-content": "space-between",
    "margin-right": "var(--sl-spacing-small)",
    "flex-wrap": "wrap",
  },
  Details: {
    "padding-bottom": "var(--sl-spacing-small)",
    "max-width": "500px",
    "padding-right": "var(--sl-spacing-x-small)",
    "&::part(header)": {
      padding: "var(--sl-spacing-x-small)",
      cursor: "default",
    },
    "&::part(content)": {
      padding: "var(--sl-spacing-x-small) var(--sl-spacing-medium)",
    },
    "&::part(base)": {
      opacity: "1",
    },
    "&::part(summary-icon)": {
      display: "flex",
    },
  },
  BadgeContainer: {
    "& > :not(:last-child)": {
      "margin-right": "var(--sl-spacing-x-small)",
    },
  },
  BoldText: {
    "font-weight": "var(--sl-font-weight-semibold)",
  },
  StatusBadge: {
    paddingLeft: "var(--sl-spacing-xxx-small)",
    "&::part(base)": {
      textAlign: "center",
      maxWidth: "170px",
      whiteSpace: "pre-line",
    },
  },
  Fueltank: {
    "& .code": {
      display: "flex",
      cursor: "pointer",
      userSelect: "none",
      color: "var(--sl-color-neutral-500)",
      "&:hover": {
        color: "var(--sl-color-sky-500)",
      },
    },
    "& .text": {
      maxWidth: "90%",
      overflow: "hidden",
      textOverflow: "ellipsis",
      color: "inherit",
      fontSize: "var(--sl-font-size-small)",
      fontWeight: "var(--sl-font-weight-bold)",
    },
    "& .icon": {
      position: "relative",
      top: "1px",
      marginLeft: "var(--sl-spacing-x-small)",
      color: "inherit",
    },
  },
};
const sheet = createStyleSheet(style);
const styleString = sheet.toString();
const RewardTableRewardsCell = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
  }
  // TODO: value function from portalv2
  render() {
    intl.locale = this.locale;
    const RewardValue = ({ reward }) => {
      var _a;
      const pimpedPrettyValue = reward.unit === "CENTS"
        ? reward.prettyValue.replace(/USD/gi, "$")
        : (_a = reward.prettyValue) !== null && _a !== void 0 ? _a : "-";
      const singleReward = reward.prettyValueNumber === "1" ||
        (reward.dateRedeemed && reward.prettyAvailableNumber === "0");
      if (reward.type === "FUELTANK") {
        return (h("div", { class: sheet.classes.Fueltank }, reward.prettyValue, reward.fuelTankCode && (h("div", { class: "code", onClick: () => navigator.clipboard.writeText(reward.fuelTankCode) }, h("sl-tooltip", { trigger: "click", placement: "top", distance: 5, skidding: 11, content: this.copyText, "onSl-show": (e) => setTimeout(() => e.path[0].hide(), 1000) }, h("span", { class: "text" }, reward.fuelTankCode), h("span", { class: "icon" }, h("sl-icon", { name: "files" })))))));
      }
      if (reward.type === "CREDIT" && !singleReward) {
        const remainingValue = parseFloat(reward.prettyValueNumber) -
          parseFloat(reward.prettyRedeemedNumber);
        const progress = Math.round((remainingValue / parseFloat(reward.prettyValueNumber)) * 100);
        const progressBarSubtext = reward.statuses.includes("EXPIRED") ||
          reward.statuses.includes("CANCELLED") ? (h("div", null, intl.formatMessage({
          id: "redeemedText",
          defaultMessage: this.redeemedText,
        }, {
          redeemedAmount: reward.prettyRedeemedCredit,
        }))) : (h("div", null, intl.formatMessage({
          id: "availableText",
          defaultMessage: this.availableText,
        }, {
          availableAmount: reward.statuses.includes("PENDING")
            ? reward.prettyAssignedCredit
            : reward.prettyAvailableValue,
        })));
        const style = {
          Progress: {
            height: "3px",
            width: "100%",
            margin: "var(--sl-spacing-xx-small) 0",
            background: "var(--sqm-border-color)",
            "&:after": {
              content: '""',
              display: "block",
              background: "var(--sqm-accent-color-icon)",
              borderRadius: "100px",
              width: `${progress}%`,
              height: "100%",
            },
          },
          Container: {
            display: "inline-block",
            verticalAlign: "top",
            width: "150px",
            whiteSpace: "break",
            overflow: "hidden",
            textOverflow: "ellipsis",
          },
          Text: {
            fontSize: "var(--sl-font-size-medium)",
            color: "var(--sqm-text)",
          },
          Subtext: {
            fontSize: "var(--sl-font-size-small)",
            color: "var(--sqm-text-subdued)",
          },
        };
        const sheet = createStyleSheet(style);
        const styleString = sheet.toString();
        return (h("div", null, h("style", { type: "text/css" }, styleString), h("div", { class: sheet.classes.Container }, h("span", { part: "sqm-reward-cell-value" }, pimpedPrettyValue + " "), h("br", null), " ", h("div", { part: "sqm-reward-cell-progress", class: sheet.classes.Progress }), h("span", { part: "sqm-reward-cell-subtext", class: sheet.classes.Subtext }, progressBarSubtext))));
      }
      return h("div", null, pimpedPrettyValue);
    };
    return (h("div", { style: { display: "contents" } }, h("style", { type: "text/css" }, styleString), h(RewardValue, { reward: this.reward })));
  }
};

const RewardsTableColumn = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /**
     * @uiName Reward column title
     */
    this.columnTitle = "Reward";
    /**
     * @uiName Redeemed amount text
     */
    this.redeemedText = "{redeemedAmount} redeemed";
    /**
     * @uiName Remaining amount text
     */
    this.availableText = "{availableAmount} remaining";
    /**
     * @uiName Copied fuel tank text
     */
    this.copyText = "Copied!";
    h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    return (h("sqm-rewards-table-reward-cell", { reward: data, redeemedText: this.redeemedText, availableText: this.availableText, copyText: this.copyText, locale: options === null || options === void 0 ? void 0 : options.locale, exportparts: "sqm-rewards-cell-value, sqm-rewards-cell-progress-bar, sqm-rewards-cell-subtext" }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  render() {
    useRequestRerender([
      this.columnTitle,
      this.redeemedText,
      this.availableText,
      this.copyText,
    ]);
    return h(Host, { style: { display: "none" } });
  }
};

const RewardTableSourceCell = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.locale = "en";
  }
  render() {
    intl.locale = this.locale;
    const RewardSource = ({ reward }) => {
      var _a;
      return (h("span", null, intl.formatMessage({
        id: "rewardSourceText",
        defaultMessage: this.rewardSourceText,
      }, {
        rewardSource: reward.rewardSource,
        programName: (_a = reward === null || reward === void 0 ? void 0 : reward.program) === null || _a === void 0 ? void 0 : _a.name,
      })));
    };
    const SOURCE_COLUMN_LENGTH = 21;
    const RewardExchangeBadge = ({ reward }) => {
      var _a;
      const rewardExchange = (h("div", null, h("span", { style: {
          fontSize: "var(--sl-font-size-small)",
          color: "var(--sqm-text-subdued)",
        } }, this.rewardExchangeText), h("br", null), (_a = reward.exchangedRewardRedemptionTransaction) === null || _a === void 0 ? void 0 :
        _a.prettyRedeemedCredit, " → ", reward.prettyValue));
      return reward.exchangedRewardRedemptionTransaction.prettyRedeemedCredit
        .length +
        reward.prettyValue.length <
        SOURCE_COLUMN_LENGTH ? (rewardExchange) : (h("div", { style: {
          display: "inline-block",
          verticalAlign: "top",
        } }, rewardExchange));
    };
    const getFullName = (user) => {
      if (!user)
        return this.deletedUserText;
      if (!user.firstName && !user.lastName)
        return this.anonymousUserText;
      if (!user.firstName)
        return `${user.lastName}`;
      if (!user.lastName)
        return `${user.firstName}`;
      return `${user.firstName} ${user.lastName}`;
    };
    const Source = () => this.reward.rewardSource === "FRIEND_SIGNUP" ||
      this.reward.rewardSource === "REFERRED" ? (this.reward.referral === null ? (h("p", { style: {
        color: "var(--sqm-text-subdued)",
      } }, this.deletedReferralText)) : (h("div", null, h("div", { style: {
        fontSize: "var(--sl-font-size-small)",
        color: "var(--sqm-text-subdued)",
      } }, intl.formatMessage({
      id: "referralText",
      defaultMessage: this.referralText,
    }, {
      rewardSource: this.reward.rewardSource,
    })), h("div", null, this.reward.rewardSource == "FRIEND_SIGNUP"
      ? getFullName(this.reward.referral.referredUser)
      : getFullName(this.reward.referral.referrerUser))))) : this.reward.exchangedRewardRedemptionTransaction ? (h(RewardExchangeBadge, { reward: this.reward })) : (h(RewardSource, { reward: this.reward }));
    return h(Source, null);
  }
};

const RewardTableUserColumn = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /**
     * @uiName Soruce column title
     */
    this.columnTitle = "Source";
    /**
     * Name displayed for unknown users
     *
     * @uiName Anonymous user text
     */
    this.anonymousUser = "Your Friend";
    /**
     * Name displayed for deleted users
     *
     * @uiName Deleted user text
     */
    this.deletedUser = "Deleted User";
    /**
     * @uiName Reward exchange label
     */
    this.rewardExchangeText = "Reward Exchange";
    /**
     * Shown when a reward has been created by a referral
     *
     * @uiName Referral text
     * @uiWidget textArea
     */
    this.referralText = "{rewardSource, select, FRIEND_SIGNUP {Referral to} REFERRED {Referred by} other {}}";
    /**
     * Shown when a reward has been created by a source other than a referral.
     *
     * @uiName Reward source text
     * @uiWidget textArea
     */
    this.rewardSourceText = "{rewardSource, select, MANUAL {Manual} AUTOMATED {{programName}} other {}}";
    h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    return (h("sqm-rewards-table-source-cell", { reward: data, anonymousUserText: this.anonymousUser, deletedUserText: this.deletedUser, rewardExchangeText: this.rewardExchangeText, referralText: this.referralText, rewardSourceText: this.rewardSourceText, locale: options === null || options === void 0 ? void 0 : options.locale }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  render() {
    useRequestRerender([
      this.deletedUser,
      this.anonymousUser,
      this.columnTitle,
      this.rewardExchangeText,
      this.referralText,
      this.rewardSourceText,
    ]);
    return h(Host, { style: { display: "none" } });
  }
};

const style$1 = {
  Badge: {
    "&::part(base)": {
      fontSize: "var(--sl-font-size-small)",
      padding: "4px 8px",
      paddingLeft: "10px",
      whiteSpace: "pre-line",
    },
  },
  RedeemBadge: {
    "&::part(base)": {
      padding: "4px 8px",
      fontSize: "var(--sl-font-size-small)",
      textAlign: "center",
      whiteSpace: "pre-line",
      background: "var(--sqm-informative-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  DangerBadge: {
    "&::part(base)": {
      padding: "4px 8px",
      fontSize: "var(--sl-font-size-small)",
      textAlign: "center",
      whiteSpace: "pre-line",
      background: "var(--sqm-danger-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  WarningBadge: {
    "&::part(base)": {
      padding: "4px 8px",
      fontSize: "var(--sl-font-size-small)",
      textAlign: "center",
      whiteSpace: "pre-line",
      background: "var(--sqm-warning-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  SuccessBadge: {
    "&::part(base)": {
      padding: "4px 8px",
      fontSize: "var(--sl-font-size-small)",
      textAlign: "center",
      whiteSpace: "pre-line",
      background: "var(--sqm-success-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  Date: {
    fontSize: "var(--sl-font-size-small)",
    color: "var(--sqm-text-subdued)",
    margin: "0",
  },
};
const sheet$1 = createStyleSheet(style$1);
const styleString$1 = sheet$1.toString();
const RewardTableStatusCell = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.expiryText = "Expires";
    this.locale = "en";
    this.pendingUsTax = "W-9 required";
    this.pendingTaxReview = "Awaiting tax form review.";
    this.pendingNewTaxForm = "Invalid tax form. Submit a new form to receive your rewards.";
    this.pendingTaxSubmission = "Submit your tax documents to receive your rewards.";
    this.pendingPartnerCreation = "Complete your tax and cash payout setup to receive your rewards.";
    this.pendingScheduled = "Until";
    this.pendingUnhandled = "Fulfillment error";
    this.pendingReviewText = "Awaiting review";
    this.deniedText = "Detected self-referral";
    this.payoutFailed = "Payout failed due to a fulfillment issue and is currently being retried.";
    this.payoutApproved = "Payout approved and scheduled for payment based on your settings.";
    this.payoutCancelled = "If you think this is a mistake, contact our Support team.";
    this.payoutProcessing = "Processing until {date}. Payout is then scheduled based on your settings.";
  }
  rewardStatus(reward) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    const hasExpired = (_a = reward.statuses) === null || _a === void 0 ? void 0 : _a.includes("EXPIRED");
    const isPending = (_b = reward.statuses) === null || _b === void 0 ? void 0 : _b.includes("PENDING");
    const integrationOrFueltankReward = reward.type === "INTEGRATION" || reward.type === "FUELTANK";
    const fraudStatus = (_d = (_c = reward.referral) === null || _c === void 0 ? void 0 : _c.fraudData) === null || _d === void 0 ? void 0 : _d.moderationStatus;
    if (fraudStatus === "DENIED")
      return "DENIED";
    if (fraudStatus === "PENDING")
      return "PENDING_REVIEW";
    const partnerTransferStatus = (_e = reward.partnerFundsTransfer) === null || _e === void 0 ? void 0 : _e.status;
    if (reward.partnerFundsTransfer) {
      if (partnerTransferStatus === "REVERSED")
        return "PAYOUT_CANCELLED";
      if (partnerTransferStatus === "OVERDUE")
        return "PAYOUT_FAILED";
      if (reward.partnerFundsTransfer.dateScheduled &&
        reward.partnerFundsTransfer.dateScheduled > Date.now()) {
        return "PROCESSING";
      }
      if (partnerTransferStatus === "TRANSFERRED" ||
        partnerTransferStatus === "NOT_YET_DUE" ||
        (reward.partnerFundsTransfer.dateScheduled &&
          reward.partnerFundsTransfer.dateScheduled < Date.now() &&
          partnerTransferStatus !== "OVERDUE" &&
          partnerTransferStatus !== "REVERSED"))
        return "PAYOUT_APPROVED";
    }
    if (reward.dateCancelled)
      return "CANCELLED";
    if (hasExpired)
      return "EXPIRED";
    if (isPending)
      return "PENDING";
    if (reward.type === "CREDIT") {
      return ((_f = reward.statuses) === null || _f === void 0 ? void 0 : _f.includes("REDEEMED")) ? "REDEEMED" : "AVAILABLE";
    }
    if (reward.type === "PCT_DISCOUNT" && ((_g = reward.statuses) === null || _g === void 0 ? void 0 : _g.includes("AVAILABLE"))) {
      return "AVAILABLE";
    }
    if (integrationOrFueltankReward && isPending) {
      return "PENDING";
    }
    if (integrationOrFueltankReward && ((_h = reward.statuses) === null || _h === void 0 ? void 0 : _h.includes("CANCELLED"))) {
      return "CANCELLED";
    }
    if (integrationOrFueltankReward && ((_j = reward.statuses) === null || _j === void 0 ? void 0 : _j.includes("AVAILABLE"))) {
      return "AVAILABLE";
    }
    return "";
  }
  getTaxPendingReasons(reward, taxConnection) {
    var _a, _b, _c, _d, _e;
    if ((_a = reward === null || reward === void 0 ? void 0 : reward.pendingReasons) === null || _a === void 0 ? void 0 : _a.includes("US_TAX")) {
      if (!(taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.taxHandlingEnabled))
        return this.pendingUsTax;
      if (!(taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.connected))
        return this.pendingPartnerCreation;
      if ((_b = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _b === void 0 ? void 0 : _b.requiredTaxDocumentType) {
        if (!((_c = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _c === void 0 ? void 0 : _c.currentTaxDocument))
          return this.pendingTaxSubmission;
        const status = taxConnection.publisher.currentTaxDocument.status;
        if (status === "INACTIVE")
          return this.pendingNewTaxForm;
        if (status === "NOT_VERIFIED")
          return this.pendingTaxReview;
      }
      if (!((_d = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _d === void 0 ? void 0 : _d.withdrawalSettings))
        return this.pendingPartnerCreation;
    }
    if ((_e = reward === null || reward === void 0 ? void 0 : reward.pendingReasons) === null || _e === void 0 ? void 0 : _e.includes("MISSING_PAYOUT_CONFIGURATION")) {
      return this.pendingPartnerCreation;
    }
    return "";
  }
  getBadgeType(rewardStatus) {
    switch (rewardStatus) {
      case "AVAILABLE":
        return "success";
      case "REDEEMED":
      case "PAYOUT_APPROVED":
        return "primary";
      case "PENDING":
      case "PENDING_REVIEW":
      case "PROCESSING":
        return "warning";
      default:
        return "danger";
    }
  }
  getPayoutStatusText(taxStatus) {
    var _a;
    switch (taxStatus) {
      case "US_TAX":
        return this.pendingUsTax;
      case "PAYOUT_APPROVED":
        return this.payoutApproved;
      case "PAYOUT_FAILED":
        return this.payoutFailed;
      case "PAYOUT_CANCELLED":
        return this.payoutCancelled;
      case "PENDING_TAX_REVIEW":
        return this.pendingTaxReview;
      case "PENDING_NEW_TAX_FORM":
        return this.pendingNewTaxForm;
      case "PENDING_TAX_SUBMISSION":
        return this.pendingTaxSubmission;
      case "PENDING_PARTNER_CREATION":
        return this.pendingPartnerCreation;
      case "PROCESSING":
        return intl.formatMessage({
          id: "payoutProcessingText",
          defaultMessage: this.payoutProcessing,
        }, {
          date: (_a = luxon.DateTime.fromMillis(this.reward.partnerFundsTransfer.dateScheduled)) === null || _a === void 0 ? void 0 : _a.setLocale(luxonLocale(this.locale)).toLocaleString(luxon.DateTime.DATE_MED),
        });
    }
  }
  render() {
    var _a;
    intl.locale = this.locale;
    const rewardStatus = this.rewardStatus(this.reward);
    const statusText = intl.formatMessage({ id: "statusMessage", defaultMessage: this.statusText }, {
      status: rewardStatus,
    });
    const badgeType = this.getBadgeType(rewardStatus);
    const dateShown = this.reward.dateCancelled ||
      this.reward.dateExpires ||
      this.reward.dateRedeemed ||
      "";
    const date = dateShown &&
      `${rewardStatus === "AVAILABLE" && this.reward.dateExpires
        ? this.expiryText + " "
        : ""}${(_a = luxon.DateTime.fromMillis(dateShown)) === null || _a === void 0 ? void 0 : _a.setLocale(luxonLocale(luxonLocale(this.locale))).toLocaleString(luxon.DateTime.DATE_MED)}`;
    const pendingReasons = rewardStatus === "PENDING"
      ? this.getTaxPendingReasons(this.reward, this.taxConnection) ||
        getRewardPendingReasons(this)
      : null;
    const fraudStatusText = rewardStatus === "PENDING_REVIEW"
      ? this.pendingReviewText
      : rewardStatus === "DENIED"
        ? this.deniedText
        : null;
    const getBadgeCSSClass = () => {
      switch (rewardStatus) {
        case "AVAILABLE":
          return sheet$1.classes.SuccessBadge;
        case "REDEEMED":
        case "PAYOUT_APPROVED":
          return sheet$1.classes.RedeemBadge;
        case "PENDING":
        case "PENDING_REVIEW":
        case "PROCESSING":
          return sheet$1.classes.WarningBadge;
        default:
          return sheet$1.classes.DangerBadge;
      }
    };
    const badgeCSSClass = getBadgeCSSClass();
    return (h("div", { style: { display: "contents" } }, h("style", { type: "text/css" }, styleString$1), h("sl-badge", { type: badgeType, pill: true, class: badgeCSSClass }, statusText), h("p", { class: sheet$1.classes.Date }, fraudStatusText ||
      pendingReasons ||
      this.getPayoutStatusText(rewardStatus) ||
      date)));
    function getRewardPendingReasons(prop) {
      var _a;
      const pendingCodeMap = {
        SCHEDULED: prop.reward.dateScheduledFor &&
          prop.pendingScheduled +
            " " + ((_a = luxon.DateTime.fromMillis(prop.reward.dateScheduledFor)) === null || _a === void 0 ? void 0 : _a.setLocale(luxonLocale(luxonLocale(prop.locale || "en"))).toLocaleString(luxon.DateTime.DATE_MED)),
        UNHANDLED_ERROR: prop.pendingUnhandled,
        SUSPECTED_FRAUD: prop.pendingReview,
      };
      const taxReason = prop.getTaxPendingReasons(prop.reward, prop.taxConnection);
      return [
        ...(taxReason ? [taxReason] : []),
        ...prop.reward.pendingReasons.map((s) => {
          var _a;
          return (_a = pendingCodeMap[s]) !== null && _a !== void 0 ? _a : s;
        }),
      ].join(", ");
    }
  }
};

const RewardTableStatusColumn = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /**
     * @uiName Column title
     */
    this.columnTitle = "Status";
    /**
     * @uiName Reward status text
     * @uiWidget textArea
     */
    this.statusText = "{status, select, AVAILABLE {Available} CANCELLED {Cancelled} PENDING {Pending} PENDING_REVIEW {Pending} PAYOUT_APPROVED {Payout Approved} PROCESSING {Payment Processing} PAYOUT_CANCELLED {Payout Cancelled} PAYOUT_FAILED {Payout Failed} EXPIRED {Expired} REDEEMED {Redeemed} DENIED {Denied} other {Not available} }";
    /**
     * Text shown before the date of an expiring reward.
     *
     * @uiName Expiry date prefix
     */
    this.expiryText = "Expires on ";
    /**
     * Displayed when a reward is pending due to W-9 compliance.
     *
     * @uiName W-9 pending text
     */
    this.pendingUsTax = "W-9 required";
    /**
     * Text shown before the available date of a pending reward.
     *
     * @uiName Pending date prefix
     */
    this.pendingScheduled = "Until";
    /**
     * Displayed when fulfillment error occured when creating a reward.
     *
     * @uiName Unhandled error text
     */
    this.pendingUnhandled = "Fulfillment error";
    /**
     *  Displayed when flagged for fraud.
     *
     * @uiName Pending review text
     */
    this.pendingReviewText = "Awaiting review";
    /**
     *  Displayed when denied for fraud.
     *
     * @uiName Denied text
     */
    this.deniedText = "Detected self-referral";
    /**
     * Displayed when pending due to tax document review.
     *
     * @uiName Pending tax review text
     */
    this.pendingTaxReview = "Awaiting tax form review.";
    /**
     * Displayed when pending due to requiring a new tax document
     *
     * @uiName Pending new tax form text
     */
    this.pendingNewTaxForm = "Invalid tax form. Submit a new form to receive your rewards.";
    /**
     * Displayed when pending due to lack of tax document submission.
     *
     * @uiName Pending tax submission text
     */
    this.pendingTaxSubmission = "Submit your tax documents to receive your rewards.";
    /**
     * Displayed when pending due to need to connect to an Impact partner
     *
     * @uiName Pending partner creation text
     */
    this.pendingPartnerCreation = "Complete your tax and cash payout setup to receive your rewards.";
    /**
     * Displayed when reward payout has failed (based on Impact cash payout configuration).
     *
     * @uiName Payout failed text
     */
    this.payoutFailed = "Payout failed due to a fulfillment issue and is currently being retried.";
    /**
     * Displayed when a reward payout is processing.
     *
     * @uiName Payout processing text
     */
    this.payoutProcessing = "Processing until {date}. Payout is then scheduled based on your settings.";
    /**
     * Displayed when reward payout was reversed (based on Impact cash payout configuration).
     *
     * @uiName Payout cancelled text
     */
    this.payoutCancelled = "If you think this is a mistake, contact our Support team.";
    /**
     * Displayed when reward payout is approved (based on Impact cash payout configuration).
     *
     * @uiName Payout approved text
     */
    this.payoutApproved = "Reward was scheduled for payment based on your settings, barring any account holds.";
    h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    return (h("sqm-rewards-table-status-cell", { statusText: this.statusText, reward: data, taxConnection: options === null || options === void 0 ? void 0 : options.taxConnection, expiryText: this.expiryText, pendingScheduled: this.pendingScheduled, pendingUsTax: this.pendingUsTax, pendingUnhandled: this.pendingUnhandled, pendingReviewText: this.pendingReviewText, payoutFailed: this.payoutFailed, payoutApproved: this.payoutApproved, payoutProcessing: this.payoutProcessing, payoutCancelled: this.payoutCancelled, deniedText: this.deniedText, locale: options === null || options === void 0 ? void 0 : options.locale }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  render() {
    useRequestRerender([
      this.columnTitle,
      this.statusText,
      this.expiryText,
      this.pendingReviewText,
      this.pendingScheduled,
      this.pendingUsTax,
      this.pendingUnhandled,
    ]);
    return h(Host, { style: { display: "none" } });
  }
};

export { RewardsTable as sqm_rewards_table, RewardTableDateCell as sqm_rewards_table_date_cell, RewardTableDateColumn as sqm_rewards_table_date_column, RewardTableRewardsCell as sqm_rewards_table_reward_cell, RewardsTableColumn as sqm_rewards_table_reward_column, RewardTableSourceCell as sqm_rewards_table_source_cell, RewardTableUserColumn as sqm_rewards_table_source_column, RewardTableStatusCell as sqm_rewards_table_status_cell, RewardTableStatusColumn as sqm_rewards_table_status_column };
