import { r as registerInstance, h } from './index-07845439.js';
import { T as Token, f as encode } from './index-265fba1f.js';
import { M as MerchantKeyInfoUnpack } from './model-fad5c7ae.js';
import { h as Card } from './index-e20749b7.js';
import { V as VerificationError } from './VerificationError-f78215c9.js';
import './index-b6cf748e.js';
import './_commonjsHelpers-8fe71198.js';
import './index-63517df5.js';

async function from(error, merchant, value) {
  var _a, _b;
  return {
    show: error.content.details.visible,
    url: await getIframeUrl((_b = (_a = merchant.card) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : "", error.content.details.url, error.content.details.data, merchant, value),
    data: error.content.details.data,
  };
}
async function getIframeUrl(issuer, url, data, merchant, value) {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  let card;
  if (Token.is(value))
    card = (_b = (_a = (await Card.V1.Token.verify(value))) === null || _a === void 0 ? void 0 : _a.card) !== null && _b !== void 0 ? _b : (await Card.Token.verify(value));
  const version = ["2.1.0", "2.2.0"].includes(data.messageVersion)
    ? data.messageVersion
    : undefined;
  const callback = Card.Token.is(card) && issuer
    ? Card.Token.getVerificationTarget(card, issuer, encodeURIComponent(window.location.origin), version)
    : `${issuer}/card/${card}/verification?mode=iframe&merchant=${(_e = (_d = (_c = merchant === null || merchant === void 0 ? void 0 : merchant.card) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : merchant === null || merchant === void 0 ? void 0 : merchant.sub) !== null && _e !== void 0 ? _e : "error"}&parent=${encodeURIComponent(window.location.origin)}${version ? `&v=${version}` : ""}`;
  data = (_h = (_g = (_f = ch3d1Data(data, callback, value)) !== null && _f !== void 0 ? _f : ch3d2MethodData(data, callback)) !== null && _g !== void 0 ? _g : ch3d2ChallengeData(data)) !== null && _h !== void 0 ? _h : data;
  const result = typeof data == "object" && Object.entries(data).length > 0
    ? Object.entries(data).reduce((a, b) => a + "&" + encodeURIComponent(b[0]) + "=" + encodeURIComponent(b[1]), "")
    : "";
  return "https://api.payfunc.com/redirect/post?target=" + encodeURIComponent(url) + result;
}
function ch3d1Data(data, callback, value) {
  let result;
  if (data.PaReq || data.pareq) {
    result = Object.assign({}, data);
    if (result.pareq) {
      result.PaReq = result.pareq;
      delete result.pareq;
    }
    if (!result.TermUrl)
      result.TermUrl = callback;
    if (!result.MD)
      result.MD = value !== null && value !== void 0 ? value : "error";
  }
  return result;
}
function ch3d2MethodData(data, callback) {
  let result;
  if (data.type == "method" && data.threeDSServerTransID)
    result = {
      threeDSMethodData: encode(JSON.stringify({
        threeDSServerTransID: data.threeDSServerTransID,
        threeDSMethodNotificationURL: callback,
      }), "url"),
    };
  return result;
}
function ch3d2ChallengeData(data) {
  let result;
  if (data.type == "challenge" && data.threeDSServerTransID)
    result = {
      creq: encode(JSON.stringify({
        threeDSServerTransID: data.threeDSServerTransID,
        acsTransID: data.acsTransID,
        messageVersion: data.messageVersion,
        messageType: data.messageType,
        challengeWindowSize: data.challengeWindowSize,
      }), "url"),
    };
  return result;
}

const styleCss = ".sc-payfunc-card-input-h{display:block;height:83px;overflow:hidden;width:100%}[hidden].sc-payfunc-card-input-h{display:none}.sc-payfunc-card-input-h>smoothly-dialog.sc-payfunc-card-input{top:60px}.sc-payfunc-card-input-h>smoothly-dialog.sc-payfunc-card-input>*.sc-payfunc-card-input{border:none}";

const PayfuncCardInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.state = "created";
  }
  async componentWillLoad() {
    this.merchant = await MerchantKeyInfoUnpack(this.apiKey);
    const styleLink = document.querySelector("link[rel=stylesheet][href^='https://theme.payfunc.com/']");
    if (styleLink) {
      const themeLink = styleLink.href.substring(26);
      this.theme = themeLink.substring(0, themeLink.indexOf("/"));
    }
  }
  verifyTimer() {
    let data;
    if (!this.verify) {
      window.clearTimeout(this.responseTimer);
      this.responseTimer = undefined;
    }
    else if (this.verify && this.verify.show === false && this.verify.data)
      this.responseTimer = window.setTimeout(() => {
        var _a, _b;
        if ((_b = (data = (_a = this.verify) === null || _a === void 0 ? void 0 : _a.data)) === null || _b === void 0 ? void 0 : _b.threeDSServerTransID) {
          console.log("Method call max server response time reached.");
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
          this.frame.send("card", {
            name: "methodTimeout",
            value: {
              card: this.value,
              key: this.apiKey,
              parent: window.location.origin,
              verificationId: data.threeDSServerTransID,
              version: ["2.1.0", "2.2.0"].includes(data.messageVersion) ? data.messageVersion : undefined,
            },
          });
        }
      }, 15000);
  }
  async handleTrigger(event) {
    if (!VerificationError.is(event.detail.value)) {
      this.verify = undefined;
      if (Token.is(event.detail.value))
        this.value = event.detail.value;
      this.state = event.detail.name == "cardTokenSuccess" ? "succeeded" : "failed";
      if (this.received) {
        this.received(this.state, event.detail.value);
        this.received = undefined;
      }
    }
  }
  async submit(input, error) {
    if (Token.is(input))
      this.value = input;
    if (VerificationError.is(error) && this.merchant && this.value)
      this.verify = await from(error, this.merchant, this.value);
    return new Promise(callback => {
      if (this.frame) {
        this.received = (_, response) => callback(response);
        const value = { card: this.value, key: this.apiKey, parent: window.location.origin };
        this.frame.send("card", !error ? { name: "submit", value } : { name: "cardCheck", value: Object.assign(Object.assign({}, value), { error }) });
        this.state = "processing";
      }
    });
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    const parameters = [];
    this.theme && parameters.push({ key: "theme", value: this.theme });
    this.cosmetic &&
      parameters.push({
        key: "cosmetic",
        value: encodeURIComponent(typeof this.cosmetic == "string" ? this.cosmetic : JSON.stringify(this.cosmetic)),
      });
    const parametersString = parameters.length > 0 ? "?" + parameters.map(param => `${param.key}=${param.value}`).join("&") : "";
    return [
      this.merchant ? (h("smoothly-frame", { url: ((_b = (_a = this.merchant) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.url) + "/ui/card-tokenizer/" + parametersString, origin: ((_d = (_c = this.merchant) === null || _c === void 0 ? void 0 : _c.card) === null || _d === void 0 ? void 0 : _d.url) ? new URL((_f = (_e = this.merchant) === null || _e === void 0 ? void 0 : _e.card) === null || _f === void 0 ? void 0 : _f.url).origin : undefined, name: "card", ref: (element) => (this.frame = element) })) : ([]),
      this.verify ? (this.verify.show ? (h("smoothly-dialog", { color: "default", closable: true }, h("smoothly-frame", { url: this.verify.url, origin: ((_h = (_g = this.merchant) === null || _g === void 0 ? void 0 : _g.card) === null || _h === void 0 ? void 0 : _h.url) ? new URL((_k = (_j = this.merchant) === null || _j === void 0 ? void 0 : _j.card) === null || _k === void 0 ? void 0 : _k.url).origin : undefined, name: "parent", style: { height: "90vh" } }))) : (h("smoothly-frame", { hidden: true, url: this.verify.url, origin: ((_m = (_l = this.merchant) === null || _l === void 0 ? void 0 : _l.card) === null || _m === void 0 ? void 0 : _m.url) ? new URL((_p = (_o = this.merchant) === null || _o === void 0 ? void 0 : _o.card) === null || _p === void 0 ? void 0 : _p.url).origin : undefined, name: "parent", style: { height: "90vh" } }))) : ([]),
    ];
  }
  static get watchers() { return {
    "verify": ["verifyTimer"]
  }; }
};
PayfuncCardInput.style = styleCss;

export { PayfuncCardInput as payfunc_card_input };
