'use strict';

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

const index$1 = require('./index-140bcbcd.js');
const index$3 = require('./index-76391849.js');
const index = require('./index-d3079b93.js');
const Token = require('./Token-8c5ba5d9.js');
require('./App-0b3e3f31.js');
const Notice = require('./Notice-e970b490.js');
const model = require('./model-7ac3bb05.js');
const index$2 = require('./index-8b1b8e63.js');
const Item = require('./Item-00ce8c24.js');
const unknown = require('./unknown-38d3748c.js');
require('./Credentials-8e4749ab.js');
require('./TextDecoder-753156f3.js');
require('./_commonjsHelpers-537d719a.js');
require('./index-09251373.js');
require('./index-bddf9814.js');
require('./index-188cc15d.js');

const sv$1 = {
  Buy: "Köp",
  Send: "Skicka",
  Verifying: "Bekräftar",
  "By clicking the Buy button I accept the ": "Genom att klicka på Köp-knappen godkänner jag ",
  "terms and conditions.": "villkoren.",
  "No response from payment server within time limit, please try again later.": "Inget respons från betalservrarna inom satt tidsbegränsning, var god försök igen senare.",
  "Order could not be created.": "Order kunde inte skapas.",
};

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

const styleCss$2 = ".sc-ig-checkout-payment-h{display:block}[hidden].sc-ig-checkout-payment-h{display:none}smoothly-submit.sc-ig-checkout-payment{border-radius:4px;width:60%;margin:auto}header.sc-ig-checkout-payment{padding:0;height:56px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.sc-ig-checkout-payment-h>smoothly-notifier.sc-ig-checkout-payment>p.sc-ig-checkout-payment{font-size:smaller;text-align:center}ig-items-display.sc-ig-checkout-payment,ig-payment-options.sc-ig-checkout-payment{font-family:var(--smoothly-font-family);color:rgb(var(--smoothly-default-contrast))}smoothly-submit.sc-ig-checkout-payment,merchant-terms.sc-ig-checkout-payment{font-family:var(--smoothly-font-family)}merchant-terms.sc-ig-checkout-payment{color:var(--smoothly-default-contrast)}";

const IntergiroCheckoutPayment = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.notice = index$1.createEvent(this, "notice", 7);
    this.processing = false;
    this.buttonDisabled = false;
  }
  async componentWillLoad() {
    var _a;
    this.t = create$1(this.element);
    this.errorMessage = index$2.ErrorMessage.create("payment", (_a = index.dist.getLanguage(this.element)) !== null && _a !== void 0 ? _a : "en");
  }
  async handleSubmit(event) {
    event.preventDefault();
    let result = false;
    const t = this.t;
    if (this.paymentOptionsElement && this.merchant) {
      this.processing = true;
      if (!this.order.number)
        this.order.number = Token.Identifier.generate(12);
      const order = await this.paymentOptionsElement.submit(this.order, this.apiKey, this.merchant);
      result = !!order;
      if (!result) {
        this.notice.emit(Notice.Notice.failed(t("Order could not be created.")));
        this.processing = false;
      }
      else
        this.signedOrder = order;
    }
    console.log("handleSubmit result", result);
    return result;
  }
  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.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;
        }
      }, 180000);
    }
  }
  async onPaymentFailed(event) {
    var _a, _b;
    if ((((_a = event.detail.content) === null || _a === void 0 ? void 0 : _a.property) == "pares" && ((_b = event.detail.content) === null || _b === void 0 ? void 0 : _b.url)) || model.isVerificationError(event.detail)) {
      if (this.responseTimer) {
        window.clearTimeout(this.responseTimer);
        this.responseTimer = undefined;
      }
    }
    else {
      this.processing = false;
      const message = this.errorMessage.generate(event);
      if (message && message != "noMessage")
        this.notice.emit(Notice.Notice.failed(message));
    }
  }
  componentDidRender() {
    if (this.signedOrder && this.submitElement)
      this.submitElement.submit();
  }
  render() {
    var _a, _b;
    const t = this.t;
    return [
      index$1.h("ig-payment-options", { client: this.client, options: this.options, cosmetic: this.cosmetic, flags: this.flags, ref: e => (this.paymentOptionsElement = e) }),
      index$1.h("ig-items-display", { items: !this.order.items ? [] : this.order.items, currency: this.order.currency, style: { border: "1x black" } }),
      index$1.h("smoothly-submit", { color: "success", prevent: true, expand: "block", processing: this.processing, onSubmit: (event) => this.handleSubmit(event), ref: (element) => (this.submitElement = element) }, this.processing ? t("Verifying") : index$3.dist.get((_a = this.flags) !== null && _a !== void 0 ? _a : {}, "transfer") ? t("Send") : t("Buy")),
      index$1.h("merchant-terms", { merchant: this.merchant, buttonName: index$3.dist.get((_b = this.flags) !== null && _b !== void 0 ? _b : {}, "transfer") ? t("Send") : t("Buy") }),
      index$1.h("card-logotypes", null),
      this.signedOrder ? index$1.h("input", { type: "hidden", name: "order", value: this.signedOrder }) : [],
    ];
  }
  get element() { return index$1.getElement(this); }
  static get watchers() { return {
    "processing": ["onUpdatedNotice"]
  }; }
};
IntergiroCheckoutPayment.style = styleCss$2;

const sv = {
  Address: "Adress",
  Continue: "Fortsätt",
  Email: "E-post",
  "Identity Number": "Personnummer",
  Phone: "Telefon",
  "Zip Code": "Postnummer",
};

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

const styleCss$1 = ".sc-ig-contact-h{display:block}[hidden].sc-ig-contact-h{display:none}*.sc-ig-contact{font-family:var(--smoothly-font-family);color:rgb(var(--smoothly-default-contrast))}p.sc-ig-contact{-webkit-margin-before:0;margin-block-start:0;-webkit-margin-after:0;margin-block-end:0;padding:0.4em 0.4em}p.sc-ig-contact,ig-display-address.sc-ig-contact,smoothly-input.sc-ig-contact{border:1px solid rgb(var(--smoothly-dark-color));border-bottom:none;color:rgb(var(--smoothly-default-contrast))}p.sc-ig-contact,smoothly-input.sc-ig-contact:first-of-type{border-top-left-radius:4px;border-top-right-radius:4px;margin-top:0.4em}ig-display-address.sc-ig-contact,smoothly-input.sc-ig-contact:last-of-type{border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom:1px solid rgb(var(--smoothly-dark-color));margin-bottom:0.6em}smoothly-input.sc-ig-contact:focus-within{border-color:rgb(var(--smoothly-primary-color));border-bottom:1px solid rgb(var(--smoothly-primary-color))}smoothly-input.sc-ig-contact:focus-within+smoothly-input.sc-ig-contact{border-top:none}";

const IntergiroContact = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.contactChanged = index$1.createEvent(this, "contactChanged", 7);
    this.processing = false;
  }
  async componentWillLoad() {
    this.merchant = await model.MerchantKeyUnpack(this.apiKey, "public");
    this.t = create(this.element);
  }
  componentDidLoad() {
    var _a;
    const form = document.getElementsByName("contact");
    const smoothlyInputs = form[0].getElementsByTagName("smoothly-input");
    if (this.contact) {
      for (let i = 0; i < smoothlyInputs.length; i++) {
        const element = smoothlyInputs.item(i);
        if (element)
          switch (element.name) {
            case "email":
              element.value = this.contact.email;
              break;
            case "phone":
              element.value = this.contact.phone;
              break;
            case "identityNumber":
              element.value = this.contact.identityNumber;
              break;
            case "zipCode":
              if (this.contact.address && Item.Addresses.is(this.contact.address))
                element.value = (_a = Object.values(this.contact.address)[0]) === null || _a === void 0 ? void 0 : _a.zipCode;
              else if (this.contact.address && Item.Address.is(this.contact.address))
                element.value = this.contact.address.zipCode;
              break;
          }
      }
    }
  }
  onContactChanged() {
    this.contactChanged.emit(this.contact);
  }
  async lookupUser(event) {
    this.processing = true;
    if (this.merchant) {
      const response = await fetch(this.merchant.iss +
        "/contact?countryCode=SE&identityNumber=" +
        event.detail.identityNumber +
        "&zipCode=" +
        event.detail.zipCode, {
        method: "GET",
        headers: {
          authorization: "Bearer " + this.apiKey,
          accept: "application/json",
          "content-type": "application/json",
        },
      });
      if (response.ok) {
        const personData = await response.json();
        if (Item.Contact.is(personData)) {
          personData.email = event.detail.email;
          personData.phone = event.detail.phone;
          this.contact = personData;
        }
      }
    }
    this.processing = false;
  }
  render() {
    const t = this.t;
    return (index$1.h("form", { name: "contact" }, index$1.h("header", null, index$1.h("h3", null, t("Address"))), Item.Contact.is(this.contact) && (Item.Address.is(this.contact.address) || Item.Name.is(this.contact.name))
      ? [
        index$1.h("main", null, index$1.h("p", null, this.contact.name)),
        index$1.h("ig-display-address", { data: this.contact.address }),
      ]
      : [
        index$1.h("smoothly-input", { type: "email", name: "email" }, t("Email")),
        index$1.h("smoothly-input", { type: "phone", name: "phone" }, t("Phone")),
        index$1.h("smoothly-input", { type: "identity-number", name: "identityNumber" }, t("Identity Number")),
        index$1.h("smoothly-input", { type: "postal-code", name: "zipCode" }, t("Zip Code")),
        index$1.h("smoothly-submit", { color: "success", expand: "block", prevent: true, processing: this.processing, onSubmit: (e) => this.lookupUser(e) }, t("Continue")),
      ]));
  }
  get element() { return index$1.getElement(this); }
  static get watchers() { return {
    "contact": ["onContactChanged"]
  }; }
};
IntergiroContact.style = styleCss$1;

const styleCss = ".sc-payfunc-checkout-h{display:block}[hidden].sc-payfunc-checkout-h{display:none}smoothly-submit.sc-payfunc-checkout{border-radius:4px}header.sc-payfunc-checkout{padding:0;height:56px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.sc-payfunc-checkout-h>smoothly-notifier.sc-payfunc-checkout>p.sc-payfunc-checkout{font-size:smaller;text-align:center}";

var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, privateMap) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to get private field on non-instance");
  }
  return privateMap.get(receiver);
};
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, privateMap, value) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to set private field on non-instance");
  }
  privateMap.set(receiver, value);
  return value;
};
var _flags;
const PayfuncCheckout = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.notice = index$1.createEvent(this, "notice", 7);
    this.contactChanged = index$1.createEvent(this, "contactChanged", 7);
    this.processing = false;
    _flags.set(this, void 0);
    this.buttonDisabled = false;
  }
  get flags() {
    var _a;
    if (!__classPrivateFieldGet(this, _flags) && this.features)
      __classPrivateFieldSet(this, _flags, index$3.dist.parse(this.features));
    return (_a = __classPrivateFieldGet(this, _flags)) !== null && _a !== void 0 ? _a : {};
  }
  async componentWillLoad() {
    var _a, _b;
    this.merchant = await model.MerchantKeyUnpack(this.apiKey, "public");
    this.checkoutClient = await model.openClient((_b = (_a = this.merchant) === null || _a === void 0 ? void 0 : _a.iss) !== null && _b !== void 0 ? _b : "", this.apiKey, "order", "contact");
    if (!index$3.dist.get(this.flags, "contact"))
      this.contactChanged.emit(this.parsedOrder.customer);
  }
  get parsedOrder() {
    var _a;
    if (!this.orderValue) {
      let order = { id: index$3.Order.generateId() };
      if (this.order)
        order = typeof this.order == "string" ? JSON.parse(this.order) : this.order;
      if (this.items)
        order = Object.assign(Object.assign({}, order), { items: typeof this.items == "string" ? JSON.parse(this.items) : this.items });
      if (this.currency)
        order = Object.assign(Object.assign({}, order), { currency: this.currency });
      if (this.number)
        order = Object.assign(Object.assign({}, order), { number: this.number });
      if (this.customer)
        order = Object.assign(Object.assign({}, order), { customer: typeof order.customer == "string"
            ? order.customer
            : Object.assign(Object.assign({}, order.customer), (typeof this.customer == "string" ? JSON.parse(this.customer) : this.customer)) });
      if (this.client)
        order = Object.assign(Object.assign({}, order), { client: this.client });
      order = Object.assign(Object.assign({}, order), { category: (_a = this.category) !== null && _a !== void 0 ? _a : "purchase" });
      this.orderValue = order;
    }
    return this.orderValue;
  }
  async onContactChanged(event) {
    var _a, _b;
    this.parsedOrder.customer = event.detail || undefined;
    if (this.merchant) {
      const paymentOptions = await this.checkoutClient.contact.getPaymentOptions(this.parsedOrder.currency, index$3.Item.amount(this.parsedOrder.items), (_b = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : "default");
      if (!unknown.Error.is(paymentOptions)) {
        event.preventDefault();
        this.paymentOptions = paymentOptions.map(option => { var _a; return option.type == "card" && ((_a = this.merchant) === null || _a === void 0 ? void 0 : _a.card) ? Object.assign(Object.assign({}, option), { apiKey: this.apiKey }) : option; });
      }
    }
  }
  getCustomCssVariables() {
    var _a, _b, _c, _d, _e, _f;
    const result = {};
    const cosmetic = typeof this.cosmetic == "string" ? JSON.parse(this.cosmetic) : this.cosmetic;
    const temp = {
      "--smoothly-tertiary-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-font-family": cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.fontFamily,
      "--smoothly-default-contrast": (_c = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.text) === null || _c === void 0 ? void 0 : _c.color,
      "--smoothly-color-contrast": (_d = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.text) === null || _d === void 0 ? void 0 : _d.color,
      "--smoothly-success-color": (_e = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.submit) === null || _e === void 0 ? void 0 : _e.background,
      "--smoothly-success-contrast": (_f = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.submit) === null || _f === void 0 ? void 0 : _f.color,
      "--smoothly-danger-color": cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.dangerColor,
    };
    Object.entries(temp).forEach(([key, value]) => {
      value && (result[key] = value);
    });
    return result;
  }
  render() {
    return (index$1.h("smoothly-notifier", null, index$3.dist.get(this.flags, "contact") ? (index$1.h("ig-contact", { style: this.getCustomCssVariables(), "api-key": this.apiKey, contact: typeof this.parsedOrder.customer != "string" ? this.parsedOrder.customer : undefined })) : ([]), this.paymentOptions ? (index$1.h("ig-checkout-payment", { client: this.checkoutClient, options: this.paymentOptions, order: this.parsedOrder, merchant: this.merchant, "api-key": this.apiKey, style: this.getCustomCssVariables(), flags: this.flags, cosmetic: !this.cosmetic
        ? undefined
        : typeof this.cosmetic == "string"
          ? this.cosmetic
          : JSON.stringify(this.cosmetic) })) : ([])));
  }
};
_flags = new WeakMap();
PayfuncCheckout.style = styleCss;

exports.ig_checkout_payment = IntergiroCheckoutPayment;
exports.ig_contact = IntergiroContact;
exports.payfunc_checkout = PayfuncCheckout;
