'use strict';

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

const index = require('./index-8277cbb3.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');
require('./JSS-8503a151.js');
const useReferralCodes = require('./useReferralCodes-0f7948af.js');
require('./ErrorView-ee7b0f36.js');
const sqmQrCodeView = require('./sqm-qr-code-view-1f2daa76.js');

const ShareLinkQuery = index_module.dist.gql `
  query shareLink($programId: ID, $engagementMedium: UserEngagementMedium!) {
    user: viewer {
      ... on User {
        shareLink(
          programId: $programId
          engagementMedium: $engagementMedium
          shareMedium: DIRECT
        )
      }
    }
  }
`;
const WIDGET_ENGAGEMENT_EVENT = index_module.dist.gql `
  mutation loadEvent($eventMeta: UserAnalyticsEvent!) {
    createUserAnalyticsEvent(eventMeta: $eventMeta)
  }
`;
function useQRCode(props) {
  var _a;
  const programId = index_module.H();
  const user = index_module.J();
  const engagementMedium = index_module.B();
  const contextData = index_module.Fn(useReferralCodes.REFERRAL_CODES_NAMESPACE);
  const [qrLink, setQrUrl] = domContextHooks_module.useState(null);
  const [error, setError] = domContextHooks_module.useState(false);
  const [loading, setLoading] = domContextHooks_module.useState(false);
  const { data, errors, loading: requestLoading, } = index_module.wn(ShareLinkQuery, { programId, engagementMedium }, !(user === null || user === void 0 ? void 0 : user.jwt) || (contextData === null || contextData === void 0 ? void 0 : contextData.shareLink) !== undefined);
  const [sendLoadEvent] = index_module.$e(WIDGET_ENGAGEMENT_EVENT);
  const shareLink = (_a = data === null || data === void 0 ? void 0 : data.user) === null || _a === void 0 ? void 0 : _a.shareLink;
  const qrPrefix = `${shareLink}?qrCode`;
  const completeLoading = requestLoading || loading;
  domContextHooks_module.useEffect(() => {
    if (!shareLink)
      return;
    const getQrCode = async () => {
      setQrUrl(`${shareLink}?qrCode&qrCodeImageFormat=svg&qrCodeQuietZoneSize=0`);
    };
    getQrCode();
  }, [shareLink]);
  const fireEvent = async () => {
    sendLoadEvent({
      eventMeta: {
        programId,
        id: user === null || user === void 0 ? void 0 : user.id,
        accountId: user === null || user === void 0 ? void 0 : user.accountId,
        type: "USER_REFERRAL_PROGRAM_ENGAGEMENT_EVENT",
        meta: {
          engagementMedium,
          shareMedium: "DIRECT",
        },
      },
    });
  };
  const createDownloadable = async () => {
    try {
      const res = await fetch(`${qrPrefix}&qrCodeSize=800&qrCodeImageFormat=png`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      // Successful
      if (blob)
        fireEvent();
      // Trigger download
      const link = document.createElement("a");
      link.href = url;
      link.download = "qrCode.png";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
    catch (e) {
      console.error("Failed to fetch QR code:", e);
      setError(true);
    }
  };
  const createPrintable = async () => {
    try {
      const res = await fetch(`${qrPrefix}&qrCodeSize=1000&qrCodeImageFormat=png&qrCodeErrorCorrectionLevel=H`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      // Successful
      if (blob)
        fireEvent();
      // Trigger print
      const page = window.open("about:blank", "_new");
      const img = page.document.createElement("img");
      img.src = url;
      img.onload = () => {
        page.print();
        page.close();
      };
      page.document.body.appendChild(img);
    }
    catch (e) {
      console.error("Failed to fetch QR code: ", e);
      setError(true);
    }
  };
  return {
    ...props,
    loading: completeLoading,
    qrLink,
    error: error,
    createDownloadable,
    createPrintable,
  };
}

const QrCode = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName Title
     */
    this.titleText = "Share your QR code";
    /**
     * @uiName View QR code text
     */
    this.viewCodeText = "View QR code";
    /**
     * @uiName Download QR code text
     */
    this.downloadCodeText = "Download";
    /**
     * @uiName Print QR code text
     */
    this.printCodeText = "Print";
    /**
     * @uiName Header for error banner
     */
    this.errorHeaderText = "There was an error loading your QR code";
    /**
     * @uiName Description for error banner
     */
    this.errorDescriptionText = "Please refresh this page and try again";
    /**
     * @uiName Hide title
     */
    this.hideTitle = false;
    /**
     * @uiName QR code alignment
     * @uiType string
     * @uiEnum ["left", "center", "right"]
     * @uiEnumNames ["Left", "Center", "Right"]
     */
    this.alignment = "center";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  render() {
    const thisProps = utils.getProps(this);
    const props = index_module.isDemo() ? useDemoQRCode(thisProps) : useQRCode(thisProps);
    return index.h(sqmQrCodeView.QrCodeView, Object.assign({}, props));
  }
};
function useDemoQRCode(props) {
  const [dialogIsOpen, setDialog] = domContextHooks_module.useState(false);
  return cjs.cjs({
    dialogIsOpen,
    hideTitle: props.hideTitle,
    showDialog: () => setDialog(true),
    hideDialog: () => setDialog(false),
    loading: true,
    titleText: props.titleText,
    viewCodeText: props.viewCodeText,
    downloadCodeText: props.downloadCodeText,
    printCodeText: props.printCodeText,
    alignment: props.alignment,
    qrLink: "https://media.istockphoto.com/id/1251071788/vector/qr-code-bar-code-black-icon-digital-technology.jpg?s=612x612&w=0&k=20&c=maw4OqMSEegAdSo8Drm9HO7i1ddddvP2YaL1UuWbRig=",
    fireViewQrEvent: () => {
      console.log("View QR Code clicked");
    },
    createDownloadable: async () => {
      console.log("Download QR Code clicked");
    },
    createPrintable: async () => {
      console.log("Print QR Code clicked");
    },
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
}

exports.sqm_qr_code = QrCode;
