import { useEngagementMedium, useMutation, useProgramId, useQuery, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { useState } from "@saasquatch/universal-hooks";
import { gql } from "graphql-request";
const MessageLinkQuery = gql `
  query ($programId: ID) {
    user: viewer {
      ... on User {
        referralCode(programId: $programId)
      }
    }
  }
`;
const WIDGET_ENGAGEMENT_EVENT = gql `
  mutation loadEvent($eventMeta: UserAnalyticsEvent!) {
    createUserAnalyticsEvent(eventMeta: $eventMeta)
  }
`;
export function useShareCode(props) {
  var _a, _b;
  const { programId = useProgramId() } = props;
  const user = useUserIdentity();
  const engagementMedium = useEngagementMedium();
  const { data } = useQuery(MessageLinkQuery, { programId }, !(user === null || user === void 0 ? void 0 : user.jwt));
  const [sendLoadEvent] = useMutation(WIDGET_ENGAGEMENT_EVENT);
  const copyString = (_b = (_a = data === null || data === void 0 ? void 0 : data.user) === null || _a === void 0 ? void 0 : _a.referralCode) !== null && _b !== void 0 ? _b : 
  // Shown during loading
  "...";
  const [open, setOpen] = useState(false);
  function onClick() {
    // Should well supported: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard#browser_compatibility
    // Only if called from a user-initiated event
    navigator.clipboard.writeText(copyString);
    setOpen(true);
    setTimeout(() => setOpen(false), props.tooltiplifespan);
    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",
        },
      },
    });
  }
  return { ...props, onClick, open, copyString: copyString };
}
