import { r as registerInstance, c as createEvent, h, g as getElement } from './index-08b73e9e.js';
import './Item-f4cbd6f4.js';
import { I as Item, d as Schedule, a as Payment, O as Order } from './index-945f930d.js';
import './Credentials-b84c0c5f.js';
import { I as Identifier } from './Token-ba2c5d5c.js';
import { d as dist } from './index-a0a71287.js';
import { b as backendFailure, E as Error } from './unknown-97022c22.js';
import { d as dist$2 } from './index-3cf720d3.js';
import { d as dist$1 } from './index-8ba22472.js';
import './App-364e27cc.js';
import { C as ClientIdentifier } from './ClientIdentifier-4a71c283.js';
import { N as Notice } from './Notice-668f9bc7.js';
import { P as PayfuncPortal, O as OrderHandler } from './index-fd4c17e7.js';
import './_commonjsHelpers-9943807e.js';
import './index-1f953d81.js';
import './TextDecoder-357ac2ce.js';
import './index-ff7475d6.js';

const sv$4 = {
  Qty: "Antal",
  Unit: "Enhet",
  Name: "Namn",
  Price: "Pris",
  VAT: "Moms",
  "Clear/remove item": "Töm/ta bort artikel",
};

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

const styleCss$4 = ".sc-ig-item-input-h{display:block}[hidden].sc-ig-item-input-h{display:none}*.sc-ig-item-input{z-index:0}.sc-ig-item-input-h>form.sc-ig-item-input{display:-ms-flexbox;display:flex;-ms-flex-wrap:nowrap;flex-wrap:nowrap}.sc-ig-item-input-h>form.sc-ig-item-input>smoothly-input.sc-ig-item-input{border:1px solid rgb(var(--smoothly-medium-color));margin-left:-1px;-ms-flex-positive:1;flex-grow:1}.sc-ig-item-input-h>form.sc-ig-item-input>smoothly-input.sc-ig-item-input>#itemName.sc-ig-item-input{-ms-flex-positive:2;flex-grow:2}.sc-ig-item-input-h>form.sc-ig-item-input>smoothly-trigger.sc-ig-item-input{float:right;padding-top:0.3em}";

const IntergiroItemInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.itemChanged = createEvent(this, "itemChanged", 7);
    this.itemCleared = createEvent(this, "itemCleared", 7);
    this.item = {};
  }
  componentWillLoad() {
    this.t = create$4(this.element);
  }
  clearInputs(e) {
    if (e.detail.name == "clear") {
      e.stopPropagation();
      e.preventDefault();
      const quantity = document.getElementById("itemQuantity");
      const unit = document.getElementById("itemUnit");
      const name = document.getElementById("itemName");
      const price = document.getElementById("itemPrice");
      const vat = document.getElementById("itemVat");
      const inputs = [quantity, unit, name, price, vat];
      for (const input of inputs)
        if (hasStringValue(input) || hasNumberValue(input))
          input.value = "";
      this.updateItem();
      this.itemCleared.emit();
    }
  }
  updateItem() {
    const quantity = document.getElementById("itemQuantity");
    const unit = document.getElementById("itemUnit");
    const name = document.getElementById("itemName");
    const price = document.getElementById("itemPrice");
    const vat = document.getElementById("itemVat");
    const item = Item.fromVatInclusivePrice(hasNumberValue(price) ? price.value : 0, hasNumberValue(vat) ? vat.value : undefined, undefined, hasStringValue(name) ? name.value : undefined, hasStringValue(quantity) && Number(quantity.value) > 0 ? Number(quantity.value) : undefined, hasStringValue(unit) ? unit.value : undefined, undefined);
    this.itemChanged.emit(item);
  }
  render() {
    const t = this.t;
    return [
      h("form", { name: "item" }, h("smoothly-input", { class: "left small", onKeyDown: this.updateItem.bind(this), id: "itemQuantity", value: this.item.quantity, type: "text", name: "quantity" }, t("Qty")), h("smoothly-input", { class: "small", onKeyDown: this.updateItem.bind(this), id: "itemUnit", value: this.item.unit, type: "text", name: "unit" }, t("Unit")), h("smoothly-input", { class: "big", onKeyDown: this.updateItem.bind(this), id: "itemName", value: this.item.name, type: "text", name: "name" }, t("Name")), h("smoothly-input", { class: "medium", onKeyDown: this.updateItem.bind(this), id: "itemPrice", value: this.inclusivePrice, type: "price", name: "price" }, t("Price")), h("smoothly-input", { class: "medium", onKeyDown: this.updateItem.bind(this), id: "itemVat", value: this.vatPercentage, type: "percent", name: "vat" }, t("VAT")), h("smoothly-trigger", { fill: "clear", name: "clear" }, h("smoothly-icon", { toolTip: t("Clear/remove item"), size: "small", name: "trash" }))),
    ];
  }
  get element() { return getElement(this); }
};
function hasStringValue(element) {
  return typeof element.value === "string";
}
function hasNumberValue(element) {
  return typeof element.value === "number";
}
IntergiroItemInput.style = styleCss$4;

const sv$3 = {};

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

const styleCss$3 = ".sc-ig-item-list-h{display:block}[hidden].sc-ig-item-list-h{display:none}";

const IntergiroItemList = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
  }
  componentWillLoad() {
    this.t = create$3(this.element);
  }
  render() {
    return [
      h("section", null, this.items
        ? this.items.map((item, index) => (h("ig-display-item", { item: item, currency: this.currency, index: index })))
        : ""),
    ];
  }
  get element() { return getElement(this); }
};
IntergiroItemList.style = styleCss$3;

const sv$2 = {
  Date: "Datum",
  Month: "Månad",
  Weekday: "Dag",
  Monday: "Måndag",
  Tuesday: "Tisdag",
  Wednesday: "Onsdag",
  Thursday: "Torsdag",
  Friday: "Fredag",
  Saturday: "Lördag",
  Sunday: "Söndag",
  January: "Januari",
  February: "Februari",
  March: "Mars",
  May: "Maj",
  June: "Juni",
  July: "Juli",
  August: "Augusti",
  October: "Oktober",
  First: "Första",
  Second: "Andra",
  Third: "Tredje",
};

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

const styleCss$2 = ".sc-ig-select-offset-h{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between}[frequency=daily].sc-ig-select-offset-h{display:none}smoothly-select.sc-ig-select-offset{display:grid;-ms-flex-positive:2;flex-grow:2}smoothly-select.sc-ig-select-offset:nth-of-type(2){border-left:1px solid rgb(var(--smoothly-medium-color))}";

const IntergiroSelectOffset = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.offsetChanged = createEvent(this, "offsetChanged", 7);
    this.days = [];
  }
  componentWillLoad() {
    this.t = create$2(this.element);
    this.weekdays = ["Weekday", ...Schedule.weekdays];
    this.quarterly = ["Month", ...Schedule.quarterly];
    this.months = ["Month", ...Schedule.months];
    const days = ["Date", ...Schedule.daysOfMonth.map(day => (day >= 0 ? (day + 1).toString() : day.toString()))];
    this.days = days;
    this.setValues();
  }
  onSelectionChanged(e) {
    const value = Number(e.detail.value);
    e.detail.value = value != undefined && value >= 0 ? (value - 1).toString() : e.detail.value;
    if (e.detail.identifier == "offset") {
      this.value = e.detail.value;
      this.offsetChanged.emit(this.value2 ? [this.value, this.value2] : this.value);
    }
    else if (e.detail.identifier == "offset2") {
      this.value2 = e.detail.value;
      this.offsetChanged.emit([this.value, this.value2]);
    }
  }
  setValues() {
    switch (this.frequency) {
      case "weekly":
        this.values = this.weekdays;
        this.value = "Weekday";
        this.value2 = undefined;
        break;
      case "monthly":
        this.values = this.days;
        this.value = "Date";
        this.value2 = undefined;
        break;
      case "quarterly":
        this.values = this.quarterly;
        this.value = "Month";
        this.values2 = this.days;
        this.value2 = "Date";
        break;
      case "yearly":
        this.values = this.months;
        this.value = "Month";
        this.values2 = this.days;
        this.value2 = "Date";
        break;
    }
  }
  render() {
    return [
      this.values && this.value ? (h("smoothly-select", { identifier: "offset", background: "transparent" }, this.values.map(option => this.value == option ? (h("option", { value: option, selected: true }, this.t(option))) : (h("option", { value: option }, this.t(option)))))) : ([]),
      this.values2 && this.value2 && this.value != "Month" ? (h("smoothly-select", { identifier: "offset2", background: "transparent" }, this.values2.map(option => this.value2 == option ? (h("option", { value: option, selected: true }, this.t(option))) : (h("option", { value: option }, this.t(option)))))) : ([]),
    ];
  }
  get element() { return getElement(this); }
  static get watchers() { return {
    "frequency": ["setValues"]
  }; }
};
IntergiroSelectOffset.style = styleCss$2;

const sv$1 = {
  Amount: "Summa",
  "Add item": "Lägg till artikel",
};

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

const styleCss$1 = ".sc-ig-total-amount-h{display:-ms-flexbox;display:flex}[hidden].sc-ig-total-amount-h{display:none}.sc-ig-total-amount-h>*.sc-ig-total-amount:first-child{-ms-flex-positive:1;flex-grow:1}smoothly-select.sc-ig-total-amount{margin-top:0.25em}";

const IntergiroTotalAmount = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.addItem = createEvent(this, "addItem", 7);
    this.currencies = [
      "SEK",
      "EUR",
      "USD",
      "DKK",
      "GBP",
      "ISK",
      "NOK",
      "AUD",
      "CAD",
      "JPY",
      "NZD",
      "CHF",
      "TRY",
      "PLN",
      "RUB",
    ];
    this.currency = "SEK";
    this.itemsvisible = false;
  }
  componentWillLoad() {
    this.t = create$1(this.element);
  }
  add(e) {
    this.addItem.emit(e);
  }
  render() {
    return [
      h("smoothly-input", { disabled: this.itemsvisible, type: "price", value: this.price, name: "price" }, this.t("Amount")),
      h("smoothly-select", { identifier: "currency", background: "transparent" }, this.currencies.map(option => this.currency == option ? (h("option", { value: option, selected: true }, option)) : (h("option", { value: option }, option)))),
      h("button", { type: "button", tabindex: "-1", onClick: e => this.add(e) }, h("smoothly-icon", { toolTip: this.t("Add item"), name: "add-circle-outline", fill: "clear", size: "medium", color: "medium" })),
    ];
  }
  get element() { return getElement(this); }
};
IntergiroTotalAmount.style = styleCss$1;

const sv = {
  "Creating order...": "Skapar order...",
  "Creating orders...": "Skapar ordrar...",
  "Failed to create order.": "Order kunde inte skapas.",
  "Failed to create $0 of $1 orders.": "Kunde inte skapa $0 av $1 ordrar.",
  "Order was created.": "Order skapades.",
  "$0 of $1 orders were created.": "$0 av $1 ordrar skapades.",
  "Order number": "Ordernummer",
  "Payment was declined.": "Betalningen misslyckades.",
  "$0 of $1 payments were declined.": "$0 av $1 betalningar misslyckades.",
  Amount: "Summa",
  Phone: "Telefon",
  Message: "Meddelande",
  "Create order": "Skapa order",
  "Add item": "Lägg till artikel",
};

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

const styleCss = ".sc-portal-create-order-h{display:block}[hidden].sc-portal-create-order-h{display:none}.sc-portal-create-order-h{margin-top:.5em}.sc-portal-create-order-h>form.sc-portal-create-order{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.sc-portal-create-order-h>form.sc-portal-create-order>*.sc-portal-create-order{-ms-flex-align:center;align-items:center;margin-bottom:.5em;margin-left:-1px}.sc-portal-create-order-h>form.sc-portal-create-order>section.sc-portal-create-order{display:-ms-flexbox;display:flex;-ms-flex-positive:1;flex-grow:1}.sc-portal-create-order-h>form.sc-portal-create-order>section.sc-portal-create-order:not(#receiver),.sc-portal-create-order-h>form.sc-portal-create-order>section#receiver.sc-portal-create-order>smoothly-input.sc-portal-create-order{border:1px solid rgb(var(--smoothly-medium-color));border-collapse:collapse}.sc-portal-create-order-h>form.sc-portal-create-order>section.sc-portal-create-order>*.sc-portal-create-order:first-child{-ms-flex-positive:1;flex-grow:1}.sc-portal-create-order-h>form.sc-portal-create-order>#languageBox.sc-portal-create-order{-ms-flex-positive:0;flex-grow:0}.sc-portal-create-order-h>form.sc-portal-create-order>#message.sc-portal-create-order{-ms-flex-positive:2;flex-grow:2;min-width:calc(100% - 80px)}.sc-portal-create-order-h>form.sc-portal-create-order>ig-item-list.sc-portal-create-order,.sc-portal-create-order-h>form.sc-portal-create-order>ig-item-input.sc-portal-create-order{width:100%;margin-bottom:0}";

const PortalCreateOrder = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.items = [];
    this.itemsVisible = false;
    this.editCounter = 0;
    this.type = "defer";
    this.selected = {};
    this.currency = "SEK";
    this.languages = ["sv", "en"];
    this.language = "sv";
  }
  componentWillLoad() {
    this.orderNumber = Identifier.generate(12);
    this.t = create(this.element);
  }
  async submitCustomerOrder(e) {
    if (this.selected)
      this.submitOrder(Object.values(this.selected)
        .filter((a) => !!a)
        .map(a => ({
        type: "customer",
        customer: a.id,
      })), e.detail.orderNumber, e.detail.price);
  }
  submitDefer(e) {
    const creatablePayment = {
      type: "defer",
      method: this.emailOption ? "email" : "sms",
      contact: this.emailOption ? e.detail.email : e.detail.phone,
      message: e.detail.message,
    };
    this.submitOrder([creatablePayment], e.detail.orderNumber, e.detail.price);
  }
  async submitOrder(payments, orderNumber, price) {
    const styleLinks = document.querySelectorAll("link[rel=stylesheet]");
    let theme = "light";
    styleLinks.forEach(element => {
      if (element.href.startsWith("https://theme.payfunc.com/")) {
        theme = element.href.substring(26);
        theme = theme.substring(0, theme.indexOf("/"));
      }
    });
    const creatableOrder = {
      client: ClientIdentifier.value,
      items: this.items && this.items.length > 0 ? this.items : dist$1.parse(price, "price", this.currency),
      currency: this.currency,
      theme,
      language: this.language,
    };
    this.notice.emit(Notice.execute(payments.length > 1 ? this.t("Creating orders...") : this.t("Creating order..."), async () => {
      let result;
      const response = await Promise.all(payments.map(payment => {
        var _a;
        return creatableOrder.items
          ? (_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.order.create(Object.assign(Object.assign({}, creatableOrder), { items: creatableOrder.items, number: orderNumber !== null && orderNumber !== void 0 ? orderNumber : Identifier.generate(12), payment, customer: Payment.Customer.Creatable.is(payment) ? payment.customer : undefined }))
          : backendFailure();
      }));
      const [succeeded, failed, pended] = response.reduce(([s, f, p], e) => {
        var _a;
        return Error.is(e)
          ? [s, ++f, p]
          : Order.is(e) && (Array.isArray(e.status) ? e.status.includes("pending") : (_a = e === null || e === void 0 ? void 0 : e.status) === null || _a === void 0 ? void 0 : _a.pending)
            ? [s, f, ++p]
            : [++s, f, p];
      }, [0, 0, 0]);
      if (failed > 0) {
        result = [
          false,
          payments.length > 1
            ? this.t("Failed to create $0 of $1 orders.", failed, payments.length)
            : this.t("Failed to create order."),
        ];
      }
      else if (pended > 0)
        result = [
          false,
          payments.length > 1
            ? this.t("$0 of $1 payments were declined.", pended, payments.length)
            : this.t("Payment was declined."),
        ];
      else {
        await OrderHandler.download();
        result = [
          true,
          payments.length > 1
            ? this.t("$0 of $1 orders were created.", succeeded, payments.length)
            : this.t("Order was created."),
        ];
        const form = document.getElementsByName("defer");
        if (form.length > 0) {
          const smoothlyInputs = form[0].getElementsByTagName("smoothly-input");
          for (let i = 0; i < smoothlyInputs.length; i++) {
            const element = smoothlyInputs.item(i);
            if (hasValue(element))
              element.value = "";
          }
        }
        this.reset();
        this.orderNumber = Identifier.generate(12);
      }
      return result;
    }));
  }
  handleItemCleared(e) {
    e.stopPropagation();
    e.preventDefault();
    this.price = Item.amount(this.items).toFixed(2);
    if (this.items.length < 2)
      this.reset();
  }
  reset() {
    this.items = [];
    this.itemsVisible = false;
    this.price = "";
  }
  changeItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items[this.items.length - 1] = e.detail;
    this.price = Item.amount(this.items).toFixed(2);
  }
  deleteItem(e) {
    const items = [];
    this.price = (Number(this.price) - Item.amount(this.items[e.detail.index])).toFixed(2);
    for (let i = 0; i < this.items.length; i++)
      if (i != e.detail.index) {
        items.push(this.items[i]);
      }
    this.items = items;
  }
  addItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items = [...this.items, {}];
    this.itemsVisible = true;
    this.price = Item.amount(this.items).toFixed(2);
    this.editCounter++;
  }
  onSelectionChanged(e) {
    if (e.detail.identifier == "currency" && dist$2.Currency.is(e.detail.value))
      this.currency = e.detail.value;
    else if (e.detail.identifier == "language" && dist$2.Language.is(e.detail.value))
      this.language = e.detail.value;
  }
  render() {
    const t = this.t;
    return [
      h("form", { name: "defer" }, this.type == "defer" || (this.selected && Object.keys(this.selected).length == 1) ? (h("section", null, h("smoothly-input", { class: "left slim", type: "text", name: "orderNumber", value: this.orderNumber }, t("Order number")))) : (""), h("section", { id: "languageBox" }, h("smoothly-select", { identifier: "language", background: "transparent" }, this.languages.map(option => this.language == option ? (h("option", { value: option, selected: true }, option)) : (h("option", { value: option }, option))))), h("section", null, h("ig-total-amount", { price: this.price, itemsvisible: this.itemsVisible, onAddItem: (e) => this.addItem(e) })), this.type == "defer" ? (h("section", { id: "receiver" }, this.emailOption ? (h("smoothly-input", { type: "text", name: "email" }, t("Email"))) : (h("smoothly-input", { type: "phone", name: "phone" }, t("Phone"))))) : (""), h("smoothly-submit", { color: "primary", fill: "clear", prevent: true, onSubmit: (e) => (this.type == "defer" ? this.submitDefer(e) : this.submitCustomerOrder(e)) }, h("smoothly-icon", { toolTip: t("Create order"), name: "send", fill: "clear", size: "medium", color: "success" })), this.emailOption || this.type == "customer" ? (h("section", { id: "message" }, h("smoothly-input", { type: "text", name: "message" }, t("Message")))) : ([]), h("ig-item-list", { items: this.items.slice(0, this.items.length - 1), currency: this.currency }), this.itemsVisible ? h("ig-item-input", { key: this.editCounter, item: {} }) : ""),
    ];
  }
  get element() { return getElement(this); }
};
function hasValue(element) {
  return typeof element === "object" && typeof element.value === "string";
}
PortalCreateOrder.style = styleCss;

export { IntergiroItemInput as ig_item_input, IntergiroItemList as ig_item_list, IntergiroSelectOffset as ig_select_offset, IntergiroTotalAmount as ig_total_amount, PortalCreateOrder as portal_create_order };
