import { r as registerInstance, j as createEvent, h, k as Host, g as getElement } from './index-07845439.js';
import { E as Error, u as unauthorized, i as invalidContent } from './index-38089f62.js';
import { d as dist$1 } from './index-046ba252.js';
import { I as Identifier } from './index-265fba1f.js';
import './index-cd3eb450.js';
import { f as ErrorMessage, a as Customer } from './index-e20749b7.js';
import { V as VerificationError } from './VerificationError-f78215c9.js';
import { d as dist } from './index-63517df5.js';
import { N as Notice, T as Trigger } from './index-f068b00b.js';
import './_commonjsHelpers-8fe71198.js';
import './App-15d9fce3.js';
import './index-b6cf748e.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 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) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.createCustomer = createEvent(this, "createCustomer", 7);
    this.processing = false;
  }
  async componentWillLoad() {
    this.t = create(this.hostElement);
    this.errorMessage = ErrorMessage.create("customer", this.hostElement);
    this.id = 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(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 (Trigger.is(event.detail) && (event.detail.name == "cardTokenFailed" || event.detail.name == "fail")) {
      if (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(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 (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 = 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 (Customer.Method.is(body) && this.customer) {
        this.customer.method.push(body);
        body = this.customer;
      }
      if (VerificationError.is(body))
        result = await this.submitHelper(body);
      else if (Error.is(body)) {
        message = this.errorMessage.generate(body);
        result = body;
      }
      else if (!Customer.is(body)) {
        message = "Unexpected problem occurred; customer couldn't be verified.";
        result = invalidContent("Unexpected problem occurred", "customer couldn't be verified");
      }
      else {
        if (!this.createCustomer.emit(body).defaultPrevented)
          this.paymentMethods = body;
        result = body;
      }
    }
    if (Error.is(result) && message)
      this.notice.emit(Notice.failed(message));
    return result;
  }
  getClientData() {
    return {
      browser: {
        colorDepth: screen.colorDepth,
        resolution: [screen.width, screen.height],
        java: navigator.javaEnabled(),
        javascript: true,
        locale: dist$1.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 (h(Host, { style: this.getCustomCssVariables() }, h("main", null, h("header", null, h("smoothly-icon", { fill: "solid", name: "checkmark-circle" }), h("span", null, t("Card"))), h("intergiro-card-input", { cosmetic: this.cosmetic, apiKey: this.apiKey, ref: (element) => (this.element = element) })), h("smoothly-submit", { processing: this.processing, disabled: 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 ? (h("input", { type: "hidden", name: this.legacyOutput() ? "payment-methods" : "customer", value: JSON.stringify(this.paymentMethods) })) : ([])));
  }
  get hostElement() { return getElement(this); }
  static get watchers() { return {
    "processing": ["onUpdatedNotice"]
  }; }
};
OnboardForm.style = styleCss;

export { OnboardForm as ig_onboard_form };
