'use strict';

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

const index$1 = require('./index-df541290.js');
const index$5 = require('./index-0a8af373.js');
const index$6 = require('./index-b8688617.js');
const index$3 = require('./index-fe328b96.js');
require('./index-5e992066.js');
const index$2 = require('./index-c12b8888.js');
const VerificationError = require('./VerificationError-51df0603.js');
const index = require('./index-b7493032.js');
const index$4 = require('./index-3e5f1089.js');
require('./_commonjsHelpers-10109b76.js');
require('./App-1e388484.js');
require('./index-0b6f1dd9.js');

const sv = {
  "Card Number": "Kortnummer",
  Expires: "Giltigt till",
  Save: "Spara",
  Submit: "Skicka",
  Card: "Kort",
  "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-ig-onboard-form-h{display:block}[hidden].sc-ig-onboard-form-h{display:none}.sc-ig-onboard-form-h>main.sc-ig-onboard-form{border:solid 2px rgb(var(--smoothly-primary-color))}.sc-ig-onboard-form-h>main.sc-ig-onboard-form>header.sc-ig-onboard-form{font-size:1.2em;padding:0.4em;display:-ms-flexbox;display:flex;background-color:rgb(var(--smoothly-primary-color));color:rgb(var(--smoothly-primary-contrast));font-family:var(--smoothly-font-family)}.sc-ig-onboard-form-h>main.sc-ig-onboard-form>header.sc-ig-onboard-form>smoothly-icon.sc-ig-onboard-form{width:1.1em;height:auto;margin-right:0.4em;fill:rgb(var(--smoothly-primary-contrast))}.sc-ig-onboard-form-h>smoothly-submit.sc-ig-onboard-form{margin-top:2rem;background-color:rgb(var(--smoothly-success-color));color:rgb(var(--smoothly-success-contrast));font-family:var(--smoothly-font-family)}";

const OnboardForm = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.notice = index$1.createEvent(this, "notice", 7);
    this.createCustomer = index$1.createEvent(this, "createCustomer", 7);
    this.processing = false;
  }
  async componentWillLoad() {
    this.t = create(this.hostElement);
    this.errorMessage = index$2.ErrorMessage.create("customer", this.hostElement);
    this.id = index$3.Identifier.generate(16);
  }
  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$4.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) {
    if (index$4.Trigger.is(event.detail) && (event.detail.name == "cardTokenFailed" || event.detail.name == "fail")) {
      if (VerificationError.VerificationError.is(event.detail.value)) {
        if (this.responseTimer) {
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
        }
      }
      else {
        const message = this.errorMessage.generate(event);
        if (message && message != this.errorMessage.unknown)
          this.notice.emit(index$4.Notice.failed(message));
      }
    }
  }
  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;
    let result;
    const card = await this.element.submit(this.card, error);
    let message;
    if (index$5.Error.is(card)) {
      message = this.errorMessage.generate(card);
      result = card;
    }
    else if (!card)
      result = undefined;
    else if (!this.merchant) {
      message = "Unauthorized merchant, contact your merchant.";
      result = index$5.unauthorized();
    }
    else {
      this.card = card;
      const creatable = {
        id: this.id,
        number: this.number,
        method: [{ card: this.card, type: "token", client: this.getClientData() }],
        contact: {
          name: this.name,
          email: this.email,
          phone: this.phone,
        },
      };
      const response = await fetch(this.merchant.iss +
        "/customer" +
        (((_a = this.customer) === null || _a === void 0 ? void 0 : _a.id) ? "/" + (((_b = this.merchant) === null || _b === void 0 ? void 0 : _b.aud) == "customer" ? "me" : (_c = this.customer) === null || _c === void 0 ? void 0 : _c.id) + "/method" : ""), {
        method: "POST",
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          Authorization: `Bearer ${this.apiKey}`,
        },
        body: JSON.stringify(((_d = this.customer) === null || _d === void 0 ? void 0 : _d.id) ? { card: this.card, type: "token", client: this.getClientData() } : creatable),
      });
      let body = await response.json();
      if (index$2.Customer.Method.is(body) && this.customer) {
        this.customer.method.push(body);
        body = this.customer;
      }
      if (VerificationError.VerificationError.is(body))
        result = await this.submitHelper(body);
      else if (index$5.Error.is(body)) {
        message = this.errorMessage.generate(body);
        result = body;
      }
      else if (!index$2.Customer.is(body)) {
        message = "Unexpected problem occurred; customer couldn't be verified.";
        result = index$5.invalidContent("Unexpected problem occurred", "customer couldn't be verified");
      }
      else {
        if (!this.createCustomer.emit(body).defaultPrevented)
          this.paymentMethods = body;
        result = body;
      }
    }
    if (index$5.Error.is(result) && message)
      this.notice.emit(index$4.Notice.failed(message));
    return result;
  }
  getClientData() {
    return {
      browser: {
        colorDepth: screen.colorDepth,
        resolution: [screen.width, screen.height],
        java: navigator.javaEnabled(),
        javascript: true,
        locale: index$6.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;
    }
  }
  getCustomCssVariables() {
    var _a, _b, _c, _d;
    const cosmetic = typeof this.cosmetic == "string" ? JSON.parse(this.cosmetic) : this.cosmetic;
    const temp = {
      "--smoothly-primary-color": (_a = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.header) === null || _a === void 0 ? void 0 : _a.background,
      "--smoothly-primary-contrast": (_b = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.header) === null || _b === void 0 ? void 0 : _b.color,
      "--smoothly-success-color": (_c = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.submit) === null || _c === void 0 ? void 0 : _c.background,
      "--smoothly-success-contrast": (_d = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.submit) === null || _d === void 0 ? void 0 : _d.color,
      "--smoothly-font-family": cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.fontFamily,
      "--smoothly-danger-color": cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.dangerColor,
    };
    const result = {};
    Object.entries(temp).forEach(([key, value]) => {
      value && (result[key] = value);
    });
    return result;
  }
  render() {
    const t = this.t;
    return (index$1.h(index$1.Host, { style: this.getCustomCssVariables() }, index$1.h("main", null, 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("intergiro-card-input", { cosmetic: this.cosmetic, apiKey: this.apiKey, ref: (element) => (this.element = element) })), index$1.h("smoothly-submit", { processing: this.processing, disabled: index$2.Customer.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" : "customer", value: JSON.stringify(this.paymentMethods) })) : ([])));
  }
  get hostElement() { return index$1.getElement(this); }
  static get watchers() { return {
    "processing": ["onUpdatedNotice"]
  }; }
};
OnboardForm.style = styleCss;

exports.ig_onboard_form = OnboardForm;
