'use strict';

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

const index$1 = require('./index-0b1e2673.js');
require('./App-1647a125.js');
require('./_commonjsHelpers-937cd5b3.js');
const index$2 = require('./index-1a9e1965.js');
require('./index-451ca284.js');
const index$4 = require('./index-ab186017.js');
const index = require('./index-36cf3884.js');
const index$3 = require('./index-061d0ccd.js');
const index$5 = require('./index-8a61808f.js');
const model = require('./model-b8df1873.js');

const sv = {
  "Card Number": "Kortnummer",
  Expires: "Giltigt till",
  Save: "Spara",
  Submit: "Skicka",
  Card: "Kort",
  "The card details are incorrect. Please enter valid card details and try again.": "Kortuppgifterna är felaktiga. Fyll i korrekta uppgifter och försök igen.",
  "The transaction contains incorrect information. The account could not be created.": "Kontot kunde inte skapas då transaktionen innehåller felaktig information.",
  "The Card Network (Acquirer) rules are not met. The account could not be created.": "Kontot kunde inte skapas då kortutfärdarens regler är inte uppfyllda.",
  "Invalid CVC code.": "Ogiltig CVC kod.",
  "Invalid Expire date.": "Ogiltigt utgångsdatum på kortet.",
  "Invalid currency. The account could not be created.": "Kontot kunde inte skapas på grund av ogiltig valuta.",
  "The transaction contains incorrect statement text and could not be completed.": "Kontot kunde inte skapas på grund av ogiltigt kontoutdrag.",
  "There is insufficient funds on the card. The account could not be created.": "Kontot kunde inte skapas då det saknades pengar på kortet.",
  "The amount limit is exceeded. The account could not be created.": "Kontot kunde inte skapas då kontots betalningsgräns överskreds.",
  "The card number is invalid. Please enter a valid number.": "Felaktigt kortnummer, kontrollera och försök igen.",
  "Your card is not supported. Please try another card.": "Ditt kort stöds inte, prova med ett annat kort.",
  "Your card has expired. The account could not be created.": "Kan inte skapa kontot då kortets utgångsdatum har passerats.",
  "Your card was declined. The account could not be created.": "Kan inte skapa kontot då kortet nekades av bank eller kortutfärdare.",
  "Your card is restricted. The account could not be created.": "Kan inte skapa kontot då kortet är begränsat.",
  "Your card has been reported lost or stolen. The account could not be created.": "Kan inte skapa kontot då kortet har rapporterats stulet.",
  "Your card was declined due to suspected fraud. The account could not be created.": "Kan inte skapa kontot på grund av misstänkt bedrägeri.",
  "The cardholder has blocked this merchant from using the card.": "Ägaren av detta kort har blockerat denna handlare från att använda kortet.",
  "3D secure reported an issue. The account could not be created. Please try again.": "Kunde inte skapa kontot då 3D verifieringen misslyckades på grund av okänt fel, var god försök igen.",
  "3D secure failed authentication. The account could not be created. Please try again.": "Kunde inte skapa kontot då 3D verifieringen misslyckades, var god försök igen.",
  "A Card Network (Acquirer) problem occured. The account could not be created.": "Kunde inte skapa kontot, det kan va ett problem med kortutfärdaren.",
  "An unknown Card Network (Acquirer) error occured, possibly due to connection issues. The account could not be created.": "Ett fel uppstod med anslutningen till kortutfärdaren. Kontot kunde inte skapas.",
  "Additional authentication required. The Card Network (Acquirer) configuration might be incorrect.": "Ytterligare autentisering krävs. Inställningarna för anslutningen till kortutfärdaren kan vara felaktiga.",
  "An unknown error occured. Ensure that your card details are correct and try again.": "Ett okänt fel uppstod. Kontrollera kortuppgifterna och försök igen.",
  "No response from payment server within time limit, please try again later.": "Inget respons från kortservrarna inom satt tidsbegränsning, var god försök igen senare.",
};

function create(language) {
  return index.dist.create({
    sv,
  }, language);
}

const styleCss = ".sc-payfunc-onboard-form-h{display:block}[hidden].sc-payfunc-onboard-form-h{display:none}.sc-payfunc-onboard-form-h>main.sc-payfunc-onboard-form{border:solid 2px rgb(var(--smoothly-primary-color))}.sc-payfunc-onboard-form-h>main.sc-payfunc-onboard-form>header.sc-payfunc-onboard-form{font-size:1.2em;padding:.4em;display:flex}.sc-payfunc-onboard-form-h>main.sc-payfunc-onboard-form>header.sc-payfunc-onboard-form>smoothly-icon.sc-payfunc-onboard-form{width:1.1em;height:auto;margin-right:.4em}.sc-payfunc-onboard-form-h>smoothly-submit.sc-payfunc-onboard-form{margin-top:2rem}";

const OnboardForm = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.notice = index$1.createEvent(this, "notice", 7);
    this.createAccount = index$1.createEvent(this, "createAccount", 7);
    this.processing = false;
  }
  async componentWillLoad() {
    this.t = create(this.hostElement);
  }
  onUpdatedNotice(startProcessing) {
    if (this.responseTimer) {
      window.clearTimeout(this.responseTimer);
      this.responseTimer = undefined;
    }
    if (startProcessing) {
      this.responseTimer = window.setTimeout(() => {
        if (this.processing) {
          console.log("Max server response time reached.");
          this.notice.emit(index$2.Notice.failed(this.t("No response from payment server within time limit, please try again later.")));
          this.processing = false;
        }
        if (this.responseTimer) {
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
        }
      }, 30000);
    }
  }
  TriggerListener(event) {
    var _a, _b, _c, _d;
    if (index$2.Trigger.is(event.detail) && (event.detail.name == "cardTokenFailed" || event.detail.name == "fail")) {
      if ((((_b = (_a = event.detail.value) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.property) == "pares" && ((_d = (_c = event.detail.value) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.url)) ||
        model.isCardVerificationError(event.detail.value)) {
        if (this.responseTimer) {
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
        }
      }
      else {
        const message = this.getErrorMessage(event);
        if (message && message != this.getUnknownErrorString())
          this.notice.emit(index$2.Notice.failed(message));
      }
    }
  }
  getErrorMessage(input) {
    var _a, _b, _c, _d, _e;
    const event = !input.detail
      ? { detail: input }
      : input.detail.value
        ? Object.assign(Object.assign({}, input), { detail: input.detail.value }) : input;
    const t = this.t;
    let message;
    const content = event && event.detail && event.detail.content ? event.detail.content : undefined;
    if ((content && content.property == "pares" && content.url) || model.isCardVerificationError(event.detail))
      console.log("Pares fetched, ignoring error message.");
    else if (!content && (event.detail.type == "invalid content" || event.detail.type == "malformed content"))
      message = this.getUnknownErrorString();
    else {
      switch (event.detail.type) {
        case "invalid content":
          switch (content.description) {
            case "General input error.":
              message = t("The card details are incorrect. Please enter valid card details and try again.");
              break;
            case "Invalid transaction.":
              message = t("The transaction contains incorrect information. The account could not be created.");
              break;
            case "Acquirer rule violation.":
              message = t("The Card Network (Acquirer) rules are not met. The account could not be created.");
              break;
            case "3-D Secure authentication failure.":
              message = t("3D secure failed authentication. The account could not be created. Please try again.");
              break;
            default:
              message = this.getUnknownErrorString();
              break;
          }
          break;
        case "malformed content":
          switch (content.property) {
            case "card.csc":
              message = t("Invalid CVC code.");
              break;
            case "card.expires":
              message = t("Invalid Expire date.");
              break;
            case "currency":
              message = t("Invalid currency. The account could not be created.");
              break;
            case "description":
              message = t("The transaction contains incorrect statement text and could not be completed.");
              break;
            case "amount":
              message =
                content.description == "Insufficient funds."
                  ? t("There is insufficient funds on the card. The account could not be created.")
                  : t("The amount limit is exceeded. The account could not be created.");
              break;
            case "card.pan":
              switch (content.description) {
                case "Invalid card number.":
                  message = t("The card number is invalid. Please enter a valid number.");
                  break;
                case "Unsupported card scheme.":
                  message = t("Your card is not supported. Please try another card.");
                  break;
                case "Card expired":
                case "Card expired.":
                  message = t("Your card has expired. The account could not be created.");
                  break;
                case "Declined by issuer or card scheme.":
                  message = t("Your card was declined. The account could not be created.");
                  break;
                case "Card restricted.":
                  message = t("Your card is restricted. The account could not be created.");
                  break;
                case "Card lost or stolen.":
                  message = t("Your card has been reported lost or stolen. The account could not be created.");
                  break;
                case "Suspected fraud.":
                  message = t("Your card was declined due to suspected fraud. The account could not be created.");
                  break;
                case "Merchant blocked by cardholder.":
                  message = t("The cardholder has blocked this merchant from using the card.");
                  break;
                default:
                  message = this.getUnknownErrorString();
                  break;
              }
              break;
            case "pares":
            case "card.pares":
            case "Card.Token":
              if (!content.url && !((_a = content === null || content === void 0 ? void 0 : content.details) === null || _a === void 0 ? void 0 : _a.url))
                message =
                  content.description == "3-D Secure problem."
                    ? t("3D secure reported an issue. The account could not be created. Please try again.")
                    : t("3D secure failed authentication. The account could not be created. Please try again.");
              break;
            default:
              message = this.getUnknownErrorString();
              break;
          }
          break;
        case "backend failure":
          const details = event.detail.details;
          if (!details)
            message = this.getUnknownErrorString();
          else if (typeof details == "string") {
            switch (details) {
              case "Acuirer backend problem.":
              case "Acquirer backend problem.":
                message = t("A Card Network (Acquirer) problem occured. The account could not be created.");
                break;
              case "Unkown acquirer error.":
              case "Unknown acquirer error.":
                message = t("An unknown Card Network (Acquirer) error occured, possibly due to connection issues. The account could not be created.");
                break;
              default:
                message = details.startsWith("Unknown acquirer problem")
                  ? t("Additional authentication required. The Card Network (Acquirer) configuration might be incorrect.")
                  : this.getUnknownErrorString();
                break;
            }
          }
          else if (typeof details == "object" && ((_c = (_b = details.body) === null || _b === void 0 ? void 0 : _b.status) === null || _c === void 0 ? void 0 : _c.code) == 40000)
            message =
              ((_e = (_d = details.body) === null || _d === void 0 ? void 0 : _d.status) === null || _e === void 0 ? void 0 : _e.message) &&
                typeof details.body.status.message == "string" &&
                details.body.status.message.includes("pan")
                ? t("The card number is invalid. Please enter a valid number.")
                : t("The card details are incorrect. Please enter valid card details and try again.");
          else
            message = this.getUnknownErrorString();
          break;
        default:
          message = this.getUnknownErrorString();
          break;
      }
    }
    return message;
  }
  getUnknownErrorString() {
    return this.t("An unknown error occured. Ensure that your card details are correct and try again.");
  }
  findInputFields(event) {
    const entries = Object.entries(event.detail);
    const email = entries.find(k => k[0].match(/email/gi));
    const phone = entries.find(k => k[0].match(/phone/gi));
    const name = entries.find(k => k[0].match(/name/gi));
    this.email = email && email[1] != "" ? email[1] : undefined;
    this.phone = phone && phone[1] != "" ? phone[1] : undefined;
    this.name = name && name[1] != "" ? name[1] : undefined;
  }
  async submit(event) {
    this.processing = true;
    this.findInputFields(event);
    const result = await this.submitHelper();
    this.processing = false;
    return result;
  }
  async submitHelper(error) {
    var _a, _b, _c, _d, _e;
    let result;
    const response = await this.element.submit(this.cardToken, error);
    let message;
    if (index$3.dist.Error.is(response)) {
      message = this.getErrorMessage(response);
      result = response;
    }
    else if (!response)
      result = undefined;
    else if (!this.merchant) {
      message = "Unauthorized merchant, contact your merchant.";
      result = index$3.dist.client.unauthorized();
    }
    else {
      this.cardToken = response;
      const accountPayFunc = {
        number: this.number,
        method: [{ card: this.cardToken, type: "token", client: this.getClientData() }],
        customer: {
          name: this.name,
          email: this.email,
          phone: this.phone,
        },
      };
      let accountResponse;
      if ((_a = this.account) === null || _a === void 0 ? void 0 : _a.id) {
        accountResponse = await fetch(((_b = this.merchant) === null || _b === void 0 ? void 0 : _b.iss) + "/account/" + (((_c = this.merchant) === null || _c === void 0 ? void 0 : _c.aud) == "account" ? "me" : (_d = this.account) === null || _d === void 0 ? void 0 : _d.id) + "/method", {
          method: "POST",
          headers: {
            "Content-Type": "application/json; charset=utf-8",
            Authorization: `Bearer ${this.apiKey}`,
          },
          body: JSON.stringify({ card: this.cardToken, type: "token", client: this.getClientData() }),
        });
      }
      else {
        accountResponse = await fetch(this.merchant.iss + "/account", {
          method: "POST",
          headers: {
            "Content-Type": "application/json; charset=utf-8",
            Authorization: `Bearer ${this.apiKey}`,
          },
          body: JSON.stringify(accountPayFunc),
        });
      }
      if (accountResponse === null || accountResponse === void 0 ? void 0 : accountResponse.ok) {
        let account = await accountResponse.json();
        if (index$4.Account.Method.is(account) && this.account) {
          (_e = this.account) === null || _e === void 0 ? void 0 : _e.method.push(account);
          account = this.account;
        }
        if ((account.status && account.status >= 400) || index$3.dist.Error.is(account)) {
          message = this.getErrorMessage(account);
          result = account;
        }
        else if (!index$4.Account.is(account)) {
          message = "Unexpected problem occurred; account couldn't be verified.";
          result = index$3.dist.client.invalidContent("Unexpected problem occurred", "account couldn't be verified");
        }
        else {
          if (!this.createAccount.emit(account).defaultPrevented)
            this.paymentMethods = account;
          result = account;
        }
      }
      else if (index$3.dist.Error.is(accountResponse)) {
        if (accountResponse.headers.get("content-type") == "application/json; charset=utf-8") {
          const errorResponse = await accountResponse.json();
          if ((index$3.dist.Error.is(errorResponse) &&
            errorResponse.status == 400 &&
            errorResponse.type == "missing property" &&
            errorResponse.content &&
            errorResponse.content.property == "pares" &&
            errorResponse.content.url) ||
            model.isCardVerificationError(errorResponse)) {
            result = await this.submitHelper(errorResponse);
          }
          else {
            message = this.getErrorMessage(errorResponse);
            result = errorResponse;
          }
        }
        else {
          const errorResponse = await accountResponse.text();
          message = "Unexpected problem occurred; account couldn't be verified.";
          result = index$3.dist.server.backendFailure(errorResponse);
        }
      }
      else {
        message = "Unexpected problem occurred; unknown response problem occurred.";
        result = index$3.dist.client.invalidContent("Unexpected problem occurred", "unknown response problem occurred");
      }
    }
    if (index$3.dist.Error.is(result) && message)
      this.notice.emit(index$2.Notice.failed(message));
    return result;
  }
  getClientData() {
    return {
      browser: {
        colorDepth: screen.colorDepth,
        resolution: [screen.width, screen.height],
        java: navigator.javaEnabled(),
        javascript: true,
        locale: index$5.dist.Locale.is(navigator.language) ? navigator.language : "en-GB",
        timezone: new Date().getTimezoneOffset(),
        parent: window.location.origin,
      },
    };
  }
  legacyOutput() {
    var _a;
    return ((_a = this.merchant) === null || _a === void 0 ? void 0 : _a.sub) ? ["BUeG1Dl0", "exZ-5a4T", "6lD8WwPl"].some(id => { var _a; return id == ((_a = this.merchant) === null || _a === void 0 ? void 0 : _a.sub); }) : false;
  }
  componentDidRender() {
    if (this.paymentMethods && this.submitElement) {
      ;
      this.submitElement.submit();
      this.processing = false;
    }
  }
  render() {
    const t = this.t;
    return [
      index$1.h("main", { color: "primary" }, index$1.h("header", null, index$1.h("smoothly-icon", { fill: "solid", name: "checkmark-circle" }), index$1.h("span", null, t("Card"))), index$1.h("payfunc-card-input", { apiKey: this.apiKey, ref: (element) => (this.element = element) })),
      index$1.h("smoothly-submit", { processing: this.processing, disabled: index$4.Account.is(this.paymentMethods), color: "success", prevent: true, expand: "block", onSubmit: (event) => {
          this.submit(event);
          return false;
        }, ref: (element) => (this.submitElement = element) }, t("Submit")),
      this.paymentMethods ? (index$1.h("input", { type: "hidden", name: this.legacyOutput() ? "payment-methods" : "account", value: JSON.stringify(this.paymentMethods) })) : ([]),
    ];
  }
  get hostElement() { return index$1.getElement(this); }
  static get watchers() { return {
    "processing": ["onUpdatedNotice"]
  }; }
};
OnboardForm.style = styleCss;

exports.payfunc_onboard_form = OnboardForm;
