import { r as registerInstance, c as createEvent, h, g as getElement } from './index-08b73e9e.js';
import { g as dist$1, O as Order, I as Item } from './index-945f930d.js';
import { d as dist } from './index-a0a71287.js';
import { I as Identifier } from './Token-ba2c5d5c.js';
import './App-364e27cc.js';
import { N as Notice } from './Notice-668f9bc7.js';
import { i as isVerificationError, M as MerchantKeyUnpack, o as openClient } from './model-ebf2a54b.js';
import { E as ErrorMessage } from './index-ec1bd2b3.js';
import { A as Addresses, b as Address, C as Contact, N as Name } from './Item-f4cbd6f4.js';
import { E as Error } from './unknown-97022c22.js';
import './Credentials-b84c0c5f.js';
import './TextDecoder-357ac2ce.js';
import './_commonjsHelpers-9943807e.js';
import './index-1f953d81.js';
import './index-3cf720d3.js';
import './index-ff7475d6.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 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) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.processing = false;
    this.buttonDisabled = false;
  }
  async componentWillLoad() {
    var _a;
    this.t = create$1(this.element);
    this.errorMessage = ErrorMessage.create("payment", (_a = 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 = Identifier.generate(12);
      const order = await this.paymentOptionsElement.submit(this.order, this.apiKey, this.merchant);
      result = !!order;
      if (!result) {
        this.notice.emit(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.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)) || 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.failed(message));
    }
  }
  componentDidRender() {
    if (this.signedOrder && this.submitElement)
      this.submitElement.submit();
  }
  render() {
    var _a, _b;
    const t = this.t;
    return [
      h("ig-payment-options", { client: this.client, options: this.options, cosmetic: this.cosmetic, flags: this.flags, ref: e => (this.paymentOptionsElement = e) }),
      h("ig-items-display", { items: !this.order.items ? [] : this.order.items, currency: this.order.currency, style: { border: "1x black" } }),
      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") : dist$1.get((_a = this.flags) !== null && _a !== void 0 ? _a : {}, "transfer") ? t("Send") : t("Buy")),
      h("merchant-terms", { merchant: this.merchant, buttonName: dist$1.get((_b = this.flags) !== null && _b !== void 0 ? _b : {}, "transfer") ? t("Send") : t("Buy") }),
      h("card-logotypes", null),
      this.signedOrder ? h("input", { type: "hidden", name: "order", value: this.signedOrder }) : [],
    ];
  }
  get element() { return 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 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) {
    registerInstance(this, hostRef);
    this.contactChanged = createEvent(this, "contactChanged", 7);
    this.processing = false;
  }
  async componentWillLoad() {
    this.merchant = await 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 && 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 && 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 (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 (h("form", { name: "contact" }, h("header", null, h("h3", null, t("Address"))), Contact.is(this.contact) && (Address.is(this.contact.address) || Name.is(this.contact.name))
      ? [
        h("main", null, h("p", null, this.contact.name)),
        h("ig-display-address", { data: this.contact.address }),
      ]
      : [
        h("smoothly-input", { type: "email", name: "email" }, t("Email")),
        h("smoothly-input", { type: "phone", name: "phone" }, t("Phone")),
        h("smoothly-input", { type: "identity-number", name: "identityNumber" }, t("Identity Number")),
        h("smoothly-input", { type: "postal-code", name: "zipCode" }, t("Zip Code")),
        h("smoothly-submit", { color: "success", expand: "block", prevent: true, processing: this.processing, onSubmit: (e) => this.lookupUser(e) }, t("Continue")),
      ]));
  }
  get element() { return 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) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.contactChanged = 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, dist$1.parse(this.features));
    return (_a = __classPrivateFieldGet(this, _flags)) !== null && _a !== void 0 ? _a : {};
  }
  async componentWillLoad() {
    var _a, _b;
    this.merchant = await MerchantKeyUnpack(this.apiKey, "public");
    this.checkoutClient = await openClient((_b = (_a = this.merchant) === null || _a === void 0 ? void 0 : _a.iss) !== null && _b !== void 0 ? _b : "", this.apiKey, "order", "contact");
    if (!dist$1.get(this.flags, "contact"))
      this.contactChanged.emit(this.parsedOrder.customer);
  }
  get parsedOrder() {
    var _a;
    if (!this.orderValue) {
      let order = { id: 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, Item.amount(this.parsedOrder.items), (_b = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : "default");
      if (!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 (h("smoothly-notifier", null, dist$1.get(this.flags, "contact") ? (h("ig-contact", { style: this.getCustomCssVariables(), "api-key": this.apiKey, contact: typeof this.parsedOrder.customer != "string" ? this.parsedOrder.customer : undefined })) : ([]), this.paymentOptions ? (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;

export { IntergiroCheckoutPayment as ig_checkout_payment, IntergiroContact as ig_contact, PayfuncCheckout as payfunc_checkout };
