import { r as registerInstance, h as h$1 } from './index-38ad4957.js';
import { k as useState, f as useEffect, n as h } from './dom-context-hooks.module-50442785.js';
import { d as dist, H, J, B, F as Fn, w as wn, $ as $e, i as isDemo } from './index.module-b23fdad8.js';
import { c as cjs } from './cjs-bdfb4486.js';
import { g as getProps } from './utils-334c1e34.js';
import './JSS-67b5cff8.js';
import { a as REFERRAL_CODES_NAMESPACE } from './useReferralCodes-52ca720f.js';
import './ErrorView-74cb3af8.js';
import { Q as QrCodeView } from './sqm-qr-code-view-ce476721.js';

const ShareLinkQuery = dist.gql `
  query shareLink($programId: ID, $engagementMedium: UserEngagementMedium!) {
    user: viewer {
      ... on User {
        shareLink(
          programId: $programId
          engagementMedium: $engagementMedium
          shareMedium: DIRECT
        )
      }
    }
  }
`;
const WIDGET_ENGAGEMENT_EVENT = dist.gql `
  mutation loadEvent($eventMeta: UserAnalyticsEvent!) {
    createUserAnalyticsEvent(eventMeta: $eventMeta)
  }
`;
function useQRCode(props) {
  var _a;
  const programId = H();
  const user = J();
  const engagementMedium = B();
  const contextData = Fn(REFERRAL_CODES_NAMESPACE);
  const [qrLink, setQrUrl] = useState(null);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const { data, errors, loading: requestLoading, } = 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] = $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;
  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) {
    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";
    h(this);
  }
  disconnectedCallback() { }
  render() {
    const thisProps = getProps(this);
    const props = isDemo() ? useDemoQRCode(thisProps) : useQRCode(thisProps);
    return h$1(QrCodeView, Object.assign({}, props));
  }
};
function useDemoQRCode(props) {
  const [dialogIsOpen, setDialog] = useState(false);
  return 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 });
}

export { QrCode as sqm_qr_code };
