'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-8277cbb3.js');
const global = require('./global-b7b1b8fe.js');
const domContextHooks_module = require('./dom-context-hooks.module-e7b6727c.js');
const index_module = require('./index.module-f8c8495f.js');
const cjs = require('./cjs-1066ec21.js');
const utils = require('./utils-6847bc06.js');
const JSS = require('./JSS-8503a151.js');
require('./mixins-4761d472.js');
const sqmTextSpanView = require('./sqm-text-span-view-b9e10f5d.js');
const GenericTableView = require('./GenericTableView-be5648e4.js');
const reRender = require('./re-render-72a0ef45.js');
const useChildElements = require('./useChildElements-041127d7.js');
const luxon = require('./luxon-c1ad356a.js');
const mockRewardData = require('./mockRewardData-ed603fca.js');
const useReferralTable = require('./useReferralTable-6e9de0d5.js');

const mockReferralData = (count = 4) => {
  const data = [...Array(count)].map(() => getMockData());
  return {
    totalCount: 6,
    count,
    referredByReferral: {
      dateConverted: null,
      dateReferralStarted: 1643912659850,
      referrerUser: {
        firstName: "John",
        lastName: "Snow",
        rewards: [],
      },
    },
    data,
  };
};
const statuses = [
  ["AVAILABLE"],
  ["PENDING"],
  ["CANCELLED"],
  ["EXPIRED"],
  ["REDEEMED"],
];
const firstNames = [
  "Rajesh",
  "Pierre",
  "Ji-Ho",
  "Chinua",
  "Charleston",
  "Sally",
  "Gael",
  "Jill",
  "Jane",
  "Khadija",
];
const lastNames = [
  "Smith",
  "Parker",
  "Kent",
  "Chew",
  "Stark",
  "Banner",
  "Jones",
  "Odinson",
  "Pym",
  "Rogers",
];
const getMockData = () => {
  return {
    id: "5cae6b0fcc540e209db45b53",
    referredUser: {
      id: "5cae6b0ce4b0d81c67b78e82",
      accountId: "SPX1MZBIPTFL3E1H",
      firstName: firstNames[Math.floor(Math.random() * firstNames.length)],
      lastName: lastNames[Math.floor(Math.random() * lastNames.length)],
      email: "example.uexwltgh@mailosaur.io",
      programGoals: [],
    },
    shareLinkUsed: null,
    referralCodeUsed: "JIMBONEUTRON2",
    moderationStatus: "PENDING",
    dateConverted: Math.floor(Math.random() * 10) >= 5
      ? luxon.luxon.DateTime.now().minus({ days: 6 }).toMillis()
      : null,
    dateFraudChecksCompleted: null,
    dateModerated: 1558730033306,
    dateModified: 1554934543447,
    dateReferralEnded: null,
    dateReferralPaid: null,
    dateReferralStarted: luxon.luxon.DateTime.now().minus({ days: 8 }).toMillis(),
    dateUserModified: null,
    programId: "sam-partner-test-2",
    program: {
      id: "sam-partner-test-2",
      name: "Partner Program 2.0",
    },
    rewards: Math.floor(Math.random() * 10) >= 5
      ? [
        {
          id: "5cae6b16cc540e209db45cfa",
          type: "CREDIT",
          value: 1,
          unit: "POINT",
          name: "Partner Reward",
          dateGiven: 1554934550726,
          dateExpires: null,
          dateCancelled: null,
          dateRedeemed: 1637004373582,
          dateScheduledFor: null,
          fuelTankCode: null,
          fuelTankType: null,
          currency: null,
          prettyValue: "1 Point",
          statuses: statuses[Math.floor(Math.random() * statuses.length)],
          // statuses: ["PENDING"],
          // pendingReasons: ["US_TAX", "MISSING_PAYOUT_CONFIGURATION"],
          globalRewardKey: null,
          programRewardKey: "partnerReward",
          meta: {
            ...mockRewardData.getPaypalMeta(),
          },
          rewardRedemptionTransactions: {
            data: [
              {
                exchangedRewards: {
                  data: [
                    {
                      prettyValue: "CAD10.00 Visa* Prepaid Card CAD",
                      type: "INTEGRATION",
                      fuelTankCode: null,
                      globalRewardKey: "gc1",
                    },
                  ],
                },
              },
            ],
          },
        },
      ]
      : [],
    childNodes: {
      data: [
        {
          data: {
            id: "5cae6b16cc540e209db45cb3",
            statuses: statuses[Math.floor(Math.random() * statuses.length)],
            type: "PCT_DISCOUNT",
            value: 50,
          },
          depth: 1,
        },
        {
          data: {
            id: "5cae6b16cc540e209db45cfa",
            statuses: statuses[Math.floor(Math.random() * statuses.length)],
            type: "CREDIT",
            value: 1,
          },
          depth: 1,
        },
      ],
    },
  };
};

const ReferralTable = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * Number of referrals displayed per page
     *
     * @uiName Referrals 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";
    /**
     * Show referred by user in table
     *
     * @uiName Show referrer
     * @default
     */
    this.showReferrer = false;
    /**
     * Provide the column numbers (0 indexed) that should not be displayed in mobile views. Ex. 0,2,3
     *
     * @uiName Hidden mobile columns
     */
    this.hiddenColumns = "0";
    /** @uiName Mobile breakpoint  */
    this.smBreakpoint = 599;
    /** @uiName Tablet breakpoint  */
    this.mdBreakpoint = 799;
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  render() {
    const empty = index.h(EmptySlot, null);
    const loading = index.h(LoadingSlot, null);
    const { states, data, callbacks, elements } = index_module.isDemo()
      ? useReferralTableDemo(this, empty, loading)
      : useReferralTable.useReferralTable(this, empty, loading);
    reRender.useRequestRerender([this.showReferrer, this.perPage]);
    return (index.h(GenericTableView.GenericTableView, { states: states, data: data, callbacks: callbacks, elements: elements }));
  }
};
function EmptySlot() {
  return (index.h("slot", { name: "empty" }, index.h("sqm-empty", { "empty-state-image": "https://res.cloudinary.com/saasquatch/image/upload/v1644000223/squatch-assets/empty_referral2.png", "empty-state-header": "View your referral details", "empty-state-text": "Refer a friend to view the status of your referrals and rewards earned" })));
}
function LoadingSlot() {
  return (index.h("slot", { name: "loading" }, index.h(LoadingRow, null), index.h(LoadingRow, null), index.h(LoadingRow, null), index.h(LoadingRow, null)));
}
function LoadingRow() {
  return (index.h("sqm-table-row", null, index.h("sqm-table-cell", { colspan: 5 }, index.h("sqm-skeleton", null))));
}
function useReferralTableDemo(props, emptyElement, loadingElement) {
  const [content, setContent] = domContextHooks_module.useReducer((state, next) => ({
    ...state,
    ...next,
  }), {
    columns: [],
    rows: [],
    loading: false,
    page: 0,
  });
  const tick = reRender.useRerenderListener();
  const mockData = domContextHooks_module.useMemo(() => { var _a; return ((_a = props.demoData) === null || _a === void 0 ? void 0 : _a.mockData) || mockReferralData(props.perPage); }, [props.perPage]);
  const components = useChildElements.useChildElements();
  async function getComponentData(components) {
    var _a;
    let componentData;
    //@ts-ignore
    const referrerData = mockData === null || mockData === void 0 ? void 0 : mockData.referredByReferral;
    const showReferrerRow = props.showReferrer &&
      //@ts-ignore
      !!((_a = mockData === null || mockData === void 0 ? void 0 : mockData.referredByReferral) === null || _a === void 0 ? void 0 : _a.dateReferralStarted);
    if (showReferrerRow) {
      componentData = mockData.data.slice(0, props.perPage - 1);
    }
    else {
      componentData = mockData.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.setAttribute("slot", "column-" + idx);
        c.style.position = "absolute";
        // Replace add text with a simple + button
        const plopTarget = c.firstElementChild.childNodes[1];
        plopTarget.innerHTML = "＋";
        plopTarget.style.lineHeight = "20px";
        return useReferralTable.tryMethod(c, () => c.renderLabel(idx));
      }
      return useReferralTable.tryMethod(c, () => c.renderLabel());
    });
    // show the referrer row before any other rows (renderReferrerCell is asynchronous)
    let referrerRow;
    if (showReferrerRow) {
      const referrerPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c) => useReferralTable.tryMethod(c, function renderCell() {
        return c.renderCell(referrerData, c);
      }));
      referrerRow = await Promise.all(referrerPromise);
    }
    // get the column cells (renderCell is asynchronous)
    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) => useReferralTable.tryMethod(c, () => c.renderCell(r, undefined)));
      const cells = (await Promise.all(cellPromise));
      return cells;
    });
    const rows = cellsPromise &&
      [referrerRow, ...(await Promise.all(cellsPromise))].filter((value) => value);
    setContent({ rows });
    const columns = columnsPromise && (await Promise.all(columnsPromise));
    // Set the content to render and finish loading components
    setContent({ columns, loading: false, page: 0 });
  }
  domContextHooks_module.useEffect(() => {
    setContent({ loading: true });
    (mockData === null || mockData === void 0 ? void 0 : mockData.data) && getComponentData(components);
  }, [mockData === null || mockData === void 0 ? void 0 : mockData.data, components, tick]);
  const demoProps = cjs.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,
      },
      hiddenColumns: props.hiddenColumns,
      referralData: [],
      mdBreakpoint: 799,
      smBreakpoint: 599,
    },
    elements: {
      columns: content.columns,
      rows: content.rows,
      emptyElement,
      loadingElement,
    },
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
  return demoProps;
}

const ReferralTableCell = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.ignored = true;
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  render() {
    return index.h("div", { innerHTML: this.innerTemplate });
  }
};

const ReferralTableGenericColumn = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(_) {
    // this is insecure, <script> tags can be added
    return (index.h("sqm-referral-table-cell", { "inner-template": index.getElement(this).innerHTML }));
  }
  async renderLabel() {
    return Promise.resolve(this.columnTitle);
  }
  render() {
    reRender.useRequestRerender([this.columnTitle]);
    return (index.h(index.Host, { style: { display: "none" } }, index.h("slot", null)));
  }
};

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

const ReferralTableDateColumn = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName Date column title
     */
    this.columnTitle = "Date converted";
    /**
     * @uiName Date displayed
     * @uiType string
     * @uiEnum ["dateConverted",
     * "dateReferralStarted",
     * "dateFraudChecksCompleted",
     * "dateModerated",
     * "dateModified",
     * "dateReferralEnded",
     * "dateReferralPaid",
     * "dateUserModified"]
     * @uiEnumNames ["Date Converted",
     * "Date Referral Started",
     * "Date Fraud Checks Completed",
     * "Date Moderated",
     * "Date Modified",
     * "Date Referral Ended",
     * "Date Referral Paid",
     * "Date User Modified"]
     */
    this.dateShown = "dateConverted";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    // TODO - Validate `dateShown` against a set of known values
    return (index.h("sqm-referral-table-date-cell", { date: data[this.dateShown], locale: options === null || options === void 0 ? void 0 : options.locale }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  async renderReferrerCell(data) {
    // TODO - Validate `dateShown` against a set of known values
    return (index.h("sqm-referral-table-date-cell", { date: data[this.dateShown] }));
  }
  render() {
    reRender.useRequestRerender([this.dateShown, this.columnTitle]);
    return index.h(index.Host, { style: { display: "none" } });
  }
};

const ReferralTableRewardsCell = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.statusText = "{status, select, AVAILABLE {Available} CANCELLED {Cancelled} PENDING {Pending} PENDING_REVIEW {Pending} PAYOUT_APPROVED {Payout Approved} PROCESSING {Payment Processing} PAYOUT_FAILED {Payout Failed} PAYOUT_CANCELLED {Payout Cancelled} PENDING_TAX_REVIEW {Pending} PENDING_NEW_TAX_FORM {Pending} PENDING_TAX_SUBMISSION {Pending} PENDING_PARTNER_CREATION {Pending} DENIED {Denied} EXPIRED {Expired} REDEEMED {Redeemed} other {Not available} }";
    this.statusLongText = "{status, select, AVAILABLE {Reward expiring on} CANCELLED {Reward cancelled on} PENDING {Available on} PENDING_REVIEW {Pending since} PAYOUT_APPROVED {Processing until {scheduledPayoutDate}. Payout is then scheduled based on your settings.} PAYOUT_FAILED {Payout failed due to a fulfillment issue and is currently being retried.} PAYOUT_CANCELLED {If you think this is a mistake, contact our Support team.} PENDING_TAX_REVIEW {Awaiting tax form review} PENDING_NEW_TAX_FORM {Invalid tax form. Submit a new form to receive your rewards.} PROCESSING {Processing until {scheduledPayoutDate}. Payout is then scheduled based on your settings.} PENDING_TAX_SUBMISSION {Submit your tax documents to receive your rewards} PENDING_PARTNER_CREATION {Complete your tax and cash payout setup to receive your rewards} DENIED {Denied on} EXPIRED {Reward expired on} other {Not available} }";
    this.pendingForText = "{status} for {date}";
    this.locale = "en";
  }
  render() {
    var _a;
    global.intl.locale = this.locale;
    const style = {
      "@keyframes slideRight": {
        from: { opacity: 0 },
        to: { opacity: 1 },
      },
      DetailsContainer: {
        width: "100%",
        display: "flex",
        "align-items": "center",
        "justify-content": "space-between",
        "margin-right": "var(--sl-spacing-small)",
        "flex-wrap": "wrap",
      },
      Details: {
        "max-width": "500px",
        "&::part(header)": {
          padding: "var(--sl-spacing-x-small)",
          cursor: `${this.hideDetails ? "default" : "pointer"}`,
        },
        "&::part(content)": {
          padding: "var(--sl-spacing-x-small) var(--sl-spacing-medium)",
        },
        "&::part(base)": {
          border: "var(--sqm-border-thickness) solid var(--sqm-border-color)",
          opacity: "1",
        },
        "&::part(summary-icon)": {
          display: `${this.hideDetails ? "none" : "flex"}`,
        },
        "&::part(summary-icon[open])": {
          transform: "rotate(-90deg)",
        },
      },
      BadgeContainer: {
        "& > :not(:last-child)": {
          "margin-right": "var(--sl-spacing-x-small)",
        },
      },
      BoldText: {
        "font-weight": "var(--sl-font-weight-semibold)",
      },
      RedeemBadge: {
        paddingLeft: "var(--sl-spacing-xxx-small)",
        "&::part(base)": {
          textAlign: "center",
          maxWidth: "170px",
          whiteSpace: "pre-line",
          background: "var(--sqm-informative-color-icon)",
          color: "var(--sl-color-white)",
        },
      },
      DangerBadge: {
        paddingLeft: "var(--sl-spacing-xxx-small)",
        "&::part(base)": {
          textAlign: "center",
          maxWidth: "170px",
          whiteSpace: "pre-line",
          background: "var(--sqm-danger-color-icon)",
          color: "var(--sl-color-white)",
        },
      },
      WarningBadge: {
        paddingLeft: "var(--sl-spacing-xxx-small)",
        "&::part(base)": {
          textAlign: "center",
          maxWidth: "170px",
          whiteSpace: "pre-line",
          background: "var(--sqm-warning-color-icon)",
          color: "var(--sl-color-white)",
        },
      },
      SuccessBadge: {
        paddingLeft: "var(--sl-spacing-xxx-small)",
        "&::part(base)": {
          textAlign: "center",
          maxWidth: "170px",
          whiteSpace: "pre-line",
          background: "var(--sqm-success-color-icon)",
          color: "var(--sl-color-white)",
        },
      },
    };
    const sheet = JSS.createStyleSheet(style);
    const styleString = sheet.toString();
    const getBadgeCSSClass = (badgeType) => {
      switch (badgeType) {
        case "primary":
          return sheet.classes.RedeemBadge;
        case "danger":
          return sheet.classes.DangerBadge;
        case "success":
          return sheet.classes.SuccessBadge;
        case "warning":
        case "info":
          return sheet.classes.WarningBadge;
        default:
          return sheet.classes.WarningBadge;
      }
    };
    const getState = (reward, taxConnection) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
      const possibleStates = [
        "REDEEMED",
        "CANCELLED",
        "EXPIRED",
        "PENDING",
        "AVAILABLE",
        "PENDING_REVIEW",
        "DENIED",
        "PAYOUT_APPROVED",
        "PAYOUT_CANCELLED",
        "PAYOUT_FAILED",
        "PENDING_TAX_REVIEW",
        "PENDING_NEW_TAX_FORM",
        "PENDING_TAX_SUBMISSION",
        "PENDING_PARTNER_CREATION",
        "PROCESSING",
      ];
      if (((_b = (_a = reward.referral) === null || _a === void 0 ? void 0 : _a.fraudData) === null || _b === void 0 ? void 0 : _b.moderationStatus) !== "APPROVED") {
        if (((_d = (_c = reward.referral) === null || _c === void 0 ? void 0 : _c.fraudData) === null || _d === void 0 ? void 0 : _d.moderationStatus) === "PENDING")
          return "PENDING_REVIEW";
        if (((_f = (_e = reward.referral) === null || _e === void 0 ? void 0 : _e.fraudData) === null || _f === void 0 ? void 0 : _f.moderationStatus) === "DENIED")
          return "DENIED";
      }
      const partnerFundsStatus = (_g = reward.partnerFundsTransfer) === null || _g === void 0 ? void 0 : _g.status;
      if (reward.partnerFundsTransfer) {
        if (partnerFundsStatus === "REVERSED")
          return "PAYOUT_CANCELLED";
        if (partnerFundsStatus === "OVERDUE")
          return "PAYOUT_FAILED";
        if (reward.partnerFundsTransfer.dateScheduled &&
          reward.partnerFundsTransfer.dateScheduled > Date.now()) {
          return "PROCESSING";
        }
        if (partnerFundsStatus === "TRANSFERRED" ||
          partnerFundsStatus === "NOT_YET_DUE" ||
          (reward.partnerFundsTransfer.dateScheduled &&
            reward.partnerFundsTransfer.dateScheduled < Date.now() &&
            partnerFundsStatus !== "OVERDUE" &&
            partnerFundsStatus !== "REVERSED"))
          return "PAYOUT_APPROVED";
      }
      if ((_h = reward === null || reward === void 0 ? void 0 : reward.pendingReasons) === null || _h === void 0 ? void 0 : _h.includes("US_TAX")) {
        if (!(taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.taxHandlingEnabled))
          return "PENDING";
        if (!(taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.connected))
          return "PENDING_PARTNER_CREATION";
        if ((_j = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _j === void 0 ? void 0 : _j.requiredTaxDocumentType) {
          if (!((_k = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _k === void 0 ? void 0 : _k.currentTaxDocument))
            return "PENDING_TAX_SUBMISSION";
          const status = taxConnection.publisher.currentTaxDocument.status;
          if (status === "INACTIVE" ||
            status === "INVALID_W9_ELECTRONIC_DOCUMENT" ||
            status === "INVALID_W9_ELECTRONIC_DOCUMENT_CHECK_INTERNAL")
            return "PENDING_NEW_TAX_FORM";
          if (status === "NOT_VERIFIED")
            return "PENDING_TAX_REVIEW";
        }
        if (!((_l = taxConnection === null || taxConnection === void 0 ? void 0 : taxConnection.publisher) === null || _l === void 0 ? void 0 : _l.withdrawalSettings))
          return "PENDING_PARTNER_CREATION";
      }
      if ((_m = reward === null || reward === void 0 ? void 0 : reward.pendingReasons) === null || _m === void 0 ? void 0 : _m.includes("MISSING_PAYOUT_CONFIGURATION")) {
        return "PENDING_PARTNER_CREATION";
      }
      if (reward.statuses.length === 1)
        return reward.statuses[0];
      return possibleStates.find((state) => reward.statuses.includes(state) && state);
    };
    const getSLBadgeType = (state) => {
      switch (state) {
        case "REDEEMED":
        case "PAYOUT_APPROVED":
          return "primary";
        case "DENIED":
        case "EXPIRED":
        case "CANCELLED":
        case "PAYOUT_FAILED":
        case "PAYOUT_CANCELLED":
          return "danger";
        case "PENDING":
        case "PENDING_REVIEW":
        case "PENDING_TAX_REVIEW":
        case "PENDING_NEW_TAX_FORM":
        case "PENDING_TAX_SUBMISSION":
        case "PENDING_PARTNER_CREATION":
        case "PROCESSING":
          return "warning";
        case "AVAILABLE":
          return "success";
      }
    };
    const getTimeDiff = (endTime) => {
      // Current implementation only calculates the difference from current time
      return luxon.luxon.DateTime.fromMillis(endTime)
        .setLocale(utils.luxonLocale(this.locale))
        .toRelative()
        .replace("in", "")
        .trim();
    };
    return (_a = this.rewards) === null || _a === void 0 ? void 0 : _a.map((reward) => {
      var _a, _b, _c, _d;
      const state = getState(reward, this.taxConnection);
      const slBadgeType = getSLBadgeType(state);
      const badgeText = global.intl.formatMessage({ id: "statusShortMessage", defaultMessage: this.statusText }, {
        status: state,
      });
      const statusText = global.intl.formatMessage({
        id: "statusLongMessage",
        defaultMessage: this.statusLongText,
      }, {
        status: state,
        scheduledPayoutDate: ((_a = reward.partnerFundsTransfer) === null || _a === void 0 ? void 0 : _a.dateScheduled) ? (_b = luxon.luxon.DateTime.fromMillis(reward.partnerFundsTransfer.dateScheduled)) === null || _b === void 0 ? void 0 : _b.setLocale(utils.luxonLocale(this.locale)).toLocaleString(luxon.luxon.DateTime.DATE_MED) : null,
      });
      return (index.h("sl-details", { class: sheet.classes.Details, disabled: this.hideDetails }, index.h("style", { type: "text/css" }, styleString), index.h("div", { slot: "summary", class: sheet.classes.DetailsContainer }, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, index.h("span", { part: "sqm-cell-value", class: sheet.classes.BoldText }, reward.prettyValue)), index.h("div", { class: sheet.classes.BadgeContainer }, state === "PENDING" && reward.dateScheduledFor ? (index.h("sl-badge", { class: getBadgeCSSClass(slBadgeType), type: slBadgeType, pill: true }, global.intl.formatMessage({
        id: "pendingForText",
        defaultMessage: this.pendingForText,
      }, {
        status: badgeText,
        date: getTimeDiff(reward.dateScheduledFor),
      }))) : (index.h("sl-badge", { class: getBadgeCSSClass(slBadgeType), type: slBadgeType, pill: true }, badgeText)), reward.dateExpires && state === "AVAILABLE" && (index.h("sl-badge", { class: getBadgeCSSClass(slBadgeType), type: "info", pill: true }, this.expiringText, ` ${getTimeDiff(reward.dateExpires)}`)))), index.h("div", null, state === "PENDING_REVIEW" && ((_c = reward.referral) === null || _c === void 0 ? void 0 : _c.dateModerated) && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.referral.dateModerated)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), state === "PAYOUT_APPROVED" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PROCESSING" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PAYOUT_FAILED" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PAYOUT_CANCELLED" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PENDING_TAX_REVIEW" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PENDING_NEW_TAX_FORM" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PENDING_TAX_SUBMISSION" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "PENDING_PARTNER_CREATION" && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText))), state === "DENIED" && ((_d = reward.referral) === null || _d === void 0 ? void 0 : _d.dateModerated) && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.referral.dateModerated)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED)), ".", this.deniedHelpText ? ` ${this.deniedHelpText}` : ``))), reward.dateGiven && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, this.rewardReceivedText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.dateGiven)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), state === "EXPIRED" && reward.dateExpires && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.dateExpires)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), state === "CANCELLED" && reward.dateCancelled && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.dateCancelled)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), state === "PENDING" && reward.dateScheduledFor && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.dateScheduledFor)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), " ", state === "AVAILABLE" && reward.dateExpires && (index.h("div", null, index.h(sqmTextSpanView.TextSpanView, { type: "p" }, statusText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, luxon.luxon.DateTime.fromMillis(reward.dateExpires)
        .setLocale(utils.luxonLocale(this.locale))
        .toLocaleString(luxon.luxon.DateTime.DATE_MED))))), reward.fuelTankCode && (index.h("div", null, this.fuelTankText, " ", index.h("span", { class: sheet.classes.BoldText, part: "sqm-cell-value" }, reward.fuelTankCode))))));
    });
  }
};

const ReferralTableRewardsColumn = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName Reward column title
     */
    this.columnTitle = "Rewards";
    /**
     * Text shown in the reward status badge.
     *
     * @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_FAILED {Payout Failed} PAYOUT_CANCELLED {Payout Cancelled} PENDING_TAX_REVIEW {Pending} PENDING_NEW_TAX_FORM {Pending} PENDING_TAX_SUBMISSION {Pending} PENDING_PARTNER_CREATION {Pending} DENIED {Denied} EXPIRED {Expired} REDEEMED {Redeemed} other {Not available} }";
    /**
     * Additional status text shown in the details drop down.
     *
     * @uiName Reward status long text
     * @uiWidget textArea
     */
    this.statusLongText = "{status, select, AVAILABLE {Reward expiring on} CANCELLED {Reward cancelled on} PENDING {Available on} PENDING_REVIEW {Pending since} PAYOUT_APPROVED {Processing until {scheduledPayoutDate}. Payout is then scheduled based on your settings.} PAYOUT_FAILED {Payout failed due to a fulfillment issue and is currently being retried.} PAYOUT_CANCELLED {If you think this is a mistake, contact our Support team.} PENDING_TAX_REVIEW {Awaiting tax form review} PENDING_NEW_TAX_FORM {Invalid tax form. Submit a new form to receive your rewards.} PROCESSING {Processing until {scheduledPayoutDate}. Payout is then scheduled based on your settings.} PENDING_TAX_SUBMISSION {Submit your tax documents to receive your rewards} PENDING_PARTNER_CREATION {Complete your tax and cash payout setup to receive your rewards} DENIED {Denied on} EXPIRED {Reward expired on} other {Not available} }";
    /**
     * Shown in the dropdown details when a reward has an associated fuel tank code.
     *
     * @uiName Fuel tank code text
     */
    this.fuelTankText = "Your code is";
    /**
     * Shown in the dropdown details when a reward has been received.’
     *
     * @uiName Reward received text
     */
    this.rewardReceivedText = "Reward received on";
    /**
     * Shown in the dropdown details when a reward has an expiry date.
     *
     * @uiName Reward expiring text
     */
    this.expiringText = "Expiring in";
    /**
     * Shown in the dropdown details when a reward is pending.
     *
     * @uiName Reward pending text
     */
    this.pendingForText = "{status} for {date}";
    /**
     * Shown in the dropdown details when a reward was denied.
     *
     * @uiName Reward denied help text
     */
    this.deniedHelpText = "Contact support if you think this is a mistake.";
    /**
     * @uiName Hide dropdown details of reward
     * @default
     */
    this.hideDetails = false;
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data, options) {
    return (index.h("sqm-referral-table-rewards-cell", { rewards: data.rewards, taxConnection: options === null || options === void 0 ? void 0 : options.taxConnection, statusText: this.statusText, statusLongText: this.statusLongText, fuelTankText: this.fuelTankText, rewardReceivedText: this.rewardReceivedText, expiringText: this.expiringText, pendingForText: this.pendingForText, hideDetails: this.hideDetails, deniedHelpText: this.deniedHelpText, locale: options === null || options === void 0 ? void 0 : options.locale, exportparts: "sqm-cell-value" }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  async renderReferrerCell(data) {
    // TODO: Do the right thing with many rewards, pending rewards, canceled rewards
    return (index.h("sqm-referral-table-rewards-cell", { rewards: data.rewards, exportparts: "sqm-cell-value" }));
  }
  render() {
    reRender.useRequestRerender([
      this.columnTitle,
      this.statusText,
      this.statusLongText,
      this.fuelTankText,
      this.rewardReceivedText,
      this.expiringText,
      this.pendingForText,
      this.hideDetails,
    ]);
    return index.h(index.Host, { style: { display: "none" } });
  }
};

const style = {
  SubText: {
    fontSize: "var(--sl-font-size-small)",
    color: "var(--sqm-text-subdued)",
    margin: "0",
  },
  RedeemBadge: {
    "&::part(base)": {
      fontSize: "var(--sl-font-size-small)",
      padding: "4px 8px",
      textAlign: "center",
      maxWidth: "170px",
      whiteSpace: "pre-line",
      background: "var(--sqm-informative-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  DangerBadge: {
    "&::part(base)": {
      fontSize: "var(--sl-font-size-small)",
      padding: "4px 8px",
      textAlign: "center",
      maxWidth: "170px",
      whiteSpace: "pre-line",
      background: "var(--sqm-danger-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  WarningBadge: {
    "&::part(base)": {
      fontSize: "var(--sl-font-size-small)",
      padding: "4px 8px",
      textAlign: "center",
      maxWidth: "170px",
      whiteSpace: "pre-line",
      background: "var(--sqm-warning-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
  SuccessBadge: {
    "&::part(base)": {
      fontSize: "var(--sl-font-size-small)",
      padding: "4px 8px",
      textAlign: "center",
      maxWidth: "170px",
      whiteSpace: "pre-line",
      background: "var(--sqm-success-color-icon)",
      color: "var(--sl-color-white)",
    },
  },
};
const sheet = JSS.createStyleSheet(style);
const styleString = sheet.toString();
const ReferralTableStatusCell = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
  }
  render() {
    const sheet = JSS.createStyleSheet(style);
    const styleString = sheet.toString();
    const getBadgeType = (fraudStatus) => {
      if (fraudStatus === "PENDING")
        return "warning";
      if (fraudStatus === "DENIED")
        return "danger";
      if (this.converted)
        return "success";
      return "warning";
    };
    const getBadgeCSSClass = (badgeType) => {
      switch (badgeType) {
        case "primary":
          return sheet.classes.RedeemBadge;
        case "danger":
          return sheet.classes.DangerBadge;
        case "success":
          return sheet.classes.SuccessBadge;
        case "warning":
        case "info":
          return sheet.classes.WarningBadge;
        default:
          return sheet.classes.WarningBadge;
      }
    };
    return (index.h("div", null, index.h("style", { type: "text/css" }, styleString), index.h("sl-badge", { pill: true, type: getBadgeType(this.fraudStatus), class: getBadgeCSSClass(getBadgeType(this.fraudStatus)) }, this.statusText), this.statusSubText ? (index.h("p", { class: sheet.classes.SubText }, this.statusSubText)) : null));
  }
};

const ReferralTableStatusColumn = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName Column title
     */
    this.columnTitle = "Status";
    /**
     * @uiName Converted status text
     */
    this.convertedStatusText = "Converted";
    /**
     * @uiName In progress status text
     */
    this.inProgressStatusText = "In Progress";
    /**
     * @uiName Pending review status text
     */
    this.pendingReviewStatusText = "Pending";
    /**
     * @uiName Denied status text
     */
    this.deniedStatusText = "Denied";
    /**
     * @uiName Pending review status sub-text
     */
    this.pendingReviewStatusSubText = "Awaiting review";
    /**
     * @uiName Denied status sub-text
     */
    this.deniedStatusSubText = "Detected self-referral";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data) {
    var _a;
    // TODO: Make ICU and more complete
    let statusText;
    let statusSubText;
    const fraudStatus = (_a = data === null || data === void 0 ? void 0 : data.fraudData) === null || _a === void 0 ? void 0 : _a.moderationStatus;
    if (fraudStatus === "DENIED") {
      statusText = this.deniedStatusText;
      statusSubText = this.deniedStatusSubText;
    }
    else if (fraudStatus === "PENDING") {
      statusText = this.pendingReviewStatusText;
      statusSubText = this.pendingReviewStatusSubText;
    }
    else {
      statusText = data.dateConverted
        ? this.convertedStatusText
        : this.inProgressStatusText;
    }
    return (index.h("sqm-referral-table-status-cell", { "status-text": statusText, "status-sub-text": statusSubText, "fraud-status": fraudStatus, converted: data.dateConverted ? true : false }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  async renderReferrerCell(data) {
    // TODO: Make ICU and more complete
    const statusText = data.dateConverted
      ? this.convertedStatusText
      : this.inProgressStatusText;
    return (index.h("sqm-referral-table-status-cell", { "status-text": statusText, converted: data.dateConverted ? true : false }));
  }
  render() {
    reRender.useRequestRerender([
      this.columnTitle,
      this.convertedStatusText,
      this.inProgressStatusText,
    ]);
    return index.h(index.Host, { style: { display: "none" } });
  }
};

const ReferralTableUserCell = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
  }
  render() {
    return this.name;
  }
};

const ReferralTableUserColumn = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName User column title
     */
    this.columnTitle = "Customer";
    /**
     * 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";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  async renderCell(data) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    let name;
    if (!(data === null || data === void 0 ? void 0 : data.referredUser) && !(data === null || data === void 0 ? void 0 : data.referrerUser)) {
      name = this.deletedUser;
    }
    else if (!((_a = data === null || data === void 0 ? void 0 : data.referredUser) === null || _a === void 0 ? void 0 : _a.firstName) &&
      !((_b = data === null || data === void 0 ? void 0 : data.referredUser) === null || _b === void 0 ? void 0 : _b.lastName) &&
      !((_c = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _c === void 0 ? void 0 : _c.firstName) &&
      !((_d = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _d === void 0 ? void 0 : _d.lastName)) {
      name = this.anonymousUser;
    }
    else if (data === null || data === void 0 ? void 0 : data.referrerUser) {
      name = `${(_e = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _e === void 0 ? void 0 : _e.firstName} ${(_f = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _f === void 0 ? void 0 : _f.lastName}`;
    }
    else {
      name = `${(_g = data === null || data === void 0 ? void 0 : data.referredUser) === null || _g === void 0 ? void 0 : _g.firstName} ${(_h = data === null || data === void 0 ? void 0 : data.referredUser) === null || _h === void 0 ? void 0 : _h.lastName}`;
    }
    return (index.h("sqm-referral-table-user-cell", { name: name }));
  }
  async renderLabel() {
    return this.columnTitle;
  }
  async renderReferrerCell(data) {
    var _a, _b, _c, _d;
    let name;
    if (!data) {
      name = this.deletedUser;
    }
    else if (!((_a = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _a === void 0 ? void 0 : _a.firstName) && !((_b = data.referrerUser) === null || _b === void 0 ? void 0 : _b.lastName)) {
      name = this.anonymousUser;
    }
    else {
      name = `${(_c = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _c === void 0 ? void 0 : _c.firstName} ${(_d = data === null || data === void 0 ? void 0 : data.referrerUser) === null || _d === void 0 ? void 0 : _d.lastName}`;
    }
    return (index.h("sqm-referral-table-user-cell", { name: name }));
  }
  render() {
    reRender.useRequestRerender([
      this.deletedUser,
      this.anonymousUser,
      this.columnTitle,
    ]);
    return index.h(index.Host, { style: { display: "none" } });
  }
};

exports.sqm_referral_table = ReferralTable;
exports.sqm_referral_table_cell = ReferralTableCell;
exports.sqm_referral_table_column = ReferralTableGenericColumn;
exports.sqm_referral_table_date_cell = ReferralTableDateCell;
exports.sqm_referral_table_date_column = ReferralTableDateColumn;
exports.sqm_referral_table_rewards_cell = ReferralTableRewardsCell;
exports.sqm_referral_table_rewards_column = ReferralTableRewardsColumn;
exports.sqm_referral_table_status_cell = ReferralTableStatusCell;
exports.sqm_referral_table_status_column = ReferralTableStatusColumn;
exports.sqm_referral_table_user_cell = ReferralTableUserCell;
exports.sqm_referral_table_user_column = ReferralTableUserColumn;
