import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-08b73e9e.js';
import { E as Error } from './unknown-97022c22.js';
import { I as Identifier } from './Token-ba2c5d5c.js';
import { K as Key, R as Remover, c as Customer } from './index-3299c1c0.js';
import { A as App } from './App-364e27cc.js';
import { a as Connection } from './Item-f4cbd6f4.js';
import './Credentials-b84c0c5f.js';
import { d as dist } from './index-a0a71287.js';
import { H as Handler } from './Handler-bd5ad0e8.js';
import './_commonjsHelpers-9943807e.js';
import './index-1f953d81.js';
import './TextDecoder-357ac2ce.js';
import './index-26d778c4.js';

function isDefined(value) {
  return value != undefined;
}

const sv = {
  "Your link is invalid or expired. Please check your email for a new link.": "Din länk är ogiltig eller har upphört att gälla. En ny länk har skickats till din mail.",
  subscription: "prenumeration",
  methods: "metoder",
  address: "adress",
  balance: "saldo",
  "Customer ID": "Kund ID",
};

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

const styleCss = "h1.errorMessage.sc-intergiro-customer{padding-left:1.4em;padding-top:3em}[component=\"app\"].sc-intergiro-customer-h{min-width:60em;min-height:calc(40em);width:auto;height:auto;display:inline-block}[component].sc-intergiro-customer-h header.sc-intergiro-customer{position:relative}[component].sc-intergiro-customer-h content.sc-intergiro-customer{top:0cm}[component].sc-intergiro-customer-h header.sc-intergiro-customer>*.sc-intergiro-customer:nth-child(2){display:none}[component].sc-intergiro-customer-h header.sc-intergiro-customer nav.sc-intergiro-customer ul.sc-intergiro-customer li.sc-intergiro-customer:last-child{display:none}.sc-intergiro-customer-h{font-family:var(--smoothly-font-family)}";

const IntergiroCustomer = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.login = false;
    this.paths = [""];
    this.unpackedKeys = [];
  }
  async componentWillLoad() {
    await Handler.open("", "");
    Handler.client.me.onUnauthorized = () => {
      this.customer = undefined;
      return Promise.reject();
    };
    if (location.search && location.search.split("&").length > 2) {
      const queryParameters = location.search.substring(1).split("&");
      const customerId = decodeURIComponent(queryParameters[0].split("=")[1]);
      const linkId = decodeURIComponent(queryParameters[1].split("=")[1]);
      if (Identifier.is(customerId, 16) && Identifier.is(linkId, 16)) {
        Connection.key = "a.b.c";
        Connection.url = decodeURIComponent(queryParameters[2].split("=")[1]);
        await Handler.client.customer.openLink(customerId, linkId);
      }
    }
    this.authenticate();
    this.t = create(this.element);
  }
  async authenticate() {
    var _a;
    this.apiKey && this.apiKey != "" && (Connection.key = this.apiKey);
    const unpackedKey = await Key.getVerifier().verify(Connection.key, "customer");
    if (unpackedKey && unpackedKey.customer && Connection.key) {
      this.login = false;
      Handler.client.me.addCustomerKey((_a = Connection.key) !== null && _a !== void 0 ? _a : "", unpackedKey.customer);
      Connection.url = unpackedKey.iss;
      const response = await Handler.client.customer.get("me");
      this.unpackedKeys = await Handler.client.me.customerKeys.reduce(async (accumulator, currentKey) => {
        const unpacked = await Key.getVerifier()
          .add(Remover.create(["exp"]))
          .verify(currentKey, "customer");
        if (unpacked)
          (await accumulator).push(unpacked);
        return accumulator;
      }, Promise.resolve([]));
      this.customer = !Error.is(response) && typeof response != "string" ? response : undefined;
      this.unpackedKey = unpackedKey;
      const orders = await Handler.client.order.list();
      this.customerRefresh = window.setTimeout(async () => {
        await this.getCustomer();
      }, 30000);
      if (!Error.is(orders) && typeof orders != "string")
        this.orders = orders;
    }
    else {
      window.clearTimeout(this.customerRefresh);
      this.customerRefresh = undefined;
      if (!this.unpackedKey)
        this.login = true;
    }
    this.features();
  }
  async onSelectionChanged(e) {
    if (e.detail.identifier == "customer") {
      this.apiKey = e.detail.value;
      this.authenticate();
    }
  }
  async updateMethod(event) {
    if (Customer.is(this.customer)) {
      await Handler.client.customer.setMethods(this.customer.method, "me");
      await Handler.client.customer.retryPayment();
      await this.getCustomer();
    }
  }
  async getCustomer() {
    const response = await Handler.client.customer.get("me");
    if (!Error.is(response))
      this.customer = response;
    return response;
  }
  logIn(e) {
    this.apiKey = e.detail[0];
    this.unpackedKey = e.detail[1];
    this.login = false;
    this.authenticate();
  }
  features() {
    var _a;
    this.paths =
      ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.features) == undefined
        ? this.paths
        : [
          "",
          this.checkAccess(this.unpackedKey.features, "customer.order", true),
          this.checkAccess(this.unpackedKey.features, "customer.subscription", false),
          this.checkAccess(this.unpackedKey.features, "customer.balance", false),
          this.checkAccess(this.unpackedKey.features, "customer.address", true),
          this.checkAccess(this.unpackedKey.features, "customer.method", true),
        ].filter(isDefined);
  }
  checkAccess(features, flag, showByDefault) {
    return flag.match(/\w+\.\w+/)
      ? this.checkAccess(features[flag.split(".")[0]], flag.split(".")[1], showByDefault)
      : (features != undefined && typeof features[flag] == "boolean" ? features[flag] : showByDefault)
        ? flag
        : undefined;
  }
  handleTrigger(event) {
    if (event.detail.name == "logout") {
      this.login = true;
      this.apiKey = undefined;
      this.customer = undefined;
      Connection.key = undefined;
    }
  }
  getCustomCssVariables() {
    var _a, _b, _c, _d, _e;
    const result = {};
    if (this.cosmetic && (typeof this.cosmetic == "object" || ((_a = this.cosmetic) === null || _a === void 0 ? void 0 : _a.length) > 0)) {
      const cosmetic = typeof this.cosmetic == "string" && this.cosmetic.length > 0 ? JSON.parse(this.cosmetic) : this.cosmetic;
      Object.entries({
        "--smoothly-font-family": (_b = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.fontFamily) !== null && _b !== void 0 ? _b : cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.font_family,
        "--smoothly-primary-color": (_c = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _c === void 0 ? void 0 : _c.background,
        "--smoothly-success-color": (_d = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _d === void 0 ? void 0 : _d.background,
        "--smoothly-success-contrast": (_e = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _e === void 0 ? void 0 : _e.color,
      }).forEach(([key, value]) => {
        value && (result[key] = value);
      });
    }
    return result;
  }
  render() {
    const t = this.t;
    return (h(Host, { style: this.getCustomCssVariables() }, !this.component || this.component == "app" ? (h("customer-login", { open: this.login, onSelected: e => this.logIn(e) }, h(App, { label: "Intergiro Customer" }, Customer.is(this.customer)
      ? [
        h("smoothly-room", { path: "", to: "" }),
        this.unpackedKeys.length > 1 ? (h("smoothly-select", { slot: "header", identifier: "customer", background: "transparent" }, this.unpackedKeys.map(a => {
          var _a;
          return (h("option", { value: a.token, selected: ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.customer) == a.customer }, `${a.name} - ${t("Customer ID")}: ${a.customer}`));
        }))) : (h("span", { slot: "header" }, this.unpackedKey ? this.unpackedKey.name : "")),
        this.paths.includes("order") && (h("smoothly-room", { label: t("order"), path: "order" }, h("customer-orders", { orders: this.orders, cosmetic: this.cosmetic, receipt: this.whitelistReceipt(), component: this.component }))),
        this.paths.includes("subscription") && (h("smoothly-room", { label: t("subscription"), path: "subscription" }, h("customer-subscriptions", { customer: this.customer, cosmetic: this.cosmetic, orders: this.orders, receipt: this.whitelistReceipt(), component: this.component }))),
        this.paths.includes("balance") && (h("smoothly-room", { label: t("balance"), path: "balance" }, h("customer-balance", { customer: this.customer, orders: this.orders, component: this.component }))),
        this.paths.includes("method") && (h("smoothly-room", { label: t("methods"), path: "method" }, h("customer-methods", { "api-key": Connection.key, cosmetic: this.cosmetic, customer: this.customer, methods: this.customer.method, onUpdate: (e) => this.updateMethod(e), component: this.component }))),
        this.paths.includes("address") && (h("smoothly-room", { label: t("address"), path: "address" }, h("customer-address", { customer: this.customer, component: this.component }))),
      ]
      : [
        this.paths.map(path => (h("smoothly-room", { path: path }, h("customer-error", { component: this.component, unpackedKey: this.unpackedKey })))),
      ], h("smoothly-trigger", { slot: "nav-end", type: "link", fill: "clear", name: "logout" }, h("smoothly-icon", { toolTip: "Log out", name: "log-out", size: "medium", fill: "clear", color: "light" }))))) : !Customer.is(this.customer) ? (h("customer-error", { component: this.component, unpackedKey: this.unpackedKey })) : this.component == "order" && this.paths.includes("order") ? (h("customer-orders", { orders: this.orders, cosmetic: this.cosmetic, receipt: this.whitelistReceipt(), component: this.component })) : this.component == "subscription" && this.paths.includes("subscription") ? (h("customer-subscriptions", { customer: this.customer, cosmetic: this.cosmetic, orders: this.orders, receipt: this.whitelistReceipt(), component: this.component })) : this.component == "balance" && this.paths.includes("balance") ? (h("customer-balance", { customer: this.customer, orders: this.orders, component: this.component })) : this.component == "method" && this.paths.includes("method") ? (h("customer-methods", { cosmetic: this.cosmetic, customer: this.customer, methods: this.customer.method, onUpdate: (e) => this.updateMethod(e), component: this.component })) : this.component == "address" && this.paths.includes("address") ? (h("customer-address", { customer: this.customer, component: this.component })) : (h("customer-error", { component: this.component, unpackedKey: this.unpackedKey }))));
  }
  whitelistReceipt() {
    var _a, _b;
    return ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.sub) != undefined && ["testtest", "test0123"].includes((_b = this.unpackedKey) === null || _b === void 0 ? void 0 : _b.sub);
  }
  get element() { return getElement(this); }
};
IntergiroCustomer.style = styleCss;

export { IntergiroCustomer as intergiro_customer };
