import { r as registerInstance, e as createEvent, B as Build, h, H as Host } from './index-e0adbd54.js';
import { l as logic } from './getHandlebarsHelpers-c1e27d99.js';
import { r as renderHandlebars } from './renderHandlebars-ea5bbb3a.js';
import { s as state } from './store-75674961.js';
import './_commonjsHelpers-44457d8d.js';
import './index-e6b3332e.js';
import './index-51c24363.js';
import './index-96e8c812.js';
import './localforage-394b59fa.js';

const flowRiderCss = "";

const FlowRider = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.fireenjinFetch = createEvent(this, "fireenjinFetch", 7);
    this.formData = undefined;
    this.successIcon = "checkmark-circle";
    this.flowId = undefined;
    this.renderId = undefined;
    this.materialId = undefined;
    this.fetch = undefined;
    this.stepInput = {};
    this.endpoint = undefined;
    this.isLoading = true;
    this.templates = [];
    this.beforeSubmit = undefined;
    this.successTemplate = undefined;
    this.successMessage = undefined;
    this.errorTemplate = undefined;
    this.showProgress = true;
    this.currentPath = "default";
    this.currentStep = undefined;
    this.flow = {};
    this.renderedSuccessTemplate = undefined;
    this.errors = [];
    this.pathSteps = [];
    this.steps = [];
    this.currentSlideIndex = 0;
    this.paths = {};
  }
  /**
   * Check the path's logic and return the matching path based on form data
   * @returns path String
   */
  async checkPath() {
    var _a, _b;
    const result = logic.apply((_a = this.flow) === null || _a === void 0 ? void 0 : _a.pathLogic, (_b = this.flowEl) === null || _b === void 0 ? void 0 : _b.formData);
    return typeof result === "string" ? result : null;
  }
  /**
   * Set the current path of the flow
   * @param path The path to switch to
   * @returns steps any[] A list of steps
   */
  async setPath(path) {
    var _a, _b, _c, _d;
    this.currentPath = path || this.currentPath;
    this.currentStep =
      ((_c = (_b = (_a = this.paths) === null || _a === void 0 ? void 0 : _a[this.currentPath]) === null || _b === void 0 ? void 0 : _b[this.currentSlideIndex]) === null || _c === void 0 ? void 0 : _c.name) || null;
    this.pathSteps = ((_d = this.paths) === null || _d === void 0 ? void 0 : _d[this.currentPath]) || [];
    return this.pathSteps;
  }
  async renderPaths() {
    var _a, _b, _c, _d, _e, _f, _g;
    const paths = {};
    for (const [pathName, pathSteps] of Object.entries(((_a = this.flow) === null || _a === void 0 ? void 0 : _a.paths) || {})) {
      const sortedSteps = Object.entries(pathSteps).sort(([aStep], [bStep]) => aStep.localeCompare(bStep));
      const steps = [];
      for (const [_stepOrder, pathStep] of sortedSteps) {
        const step = this.steps.find((step) => { var _a; return ((_a = pathStep === null || pathStep === void 0 ? void 0 : pathStep.step) === null || _a === void 0 ? void 0 : _a.id) === (step === null || step === void 0 ? void 0 : step.id); });
        const stepInput = {
          ...((pathStep === null || pathStep === void 0 ? void 0 : pathStep.input) || {}),
          ...(((_b = this.stepInput) === null || _b === void 0 ? void 0 : _b[step === null || step === void 0 ? void 0 : step.name]) || {}),
          ...(((_c = this.flowEl) === null || _c === void 0 ? void 0 : _c.formData) || {}),
        };
        if (!step || JSON.stringify(step) === "undefined")
          continue;
        const renderedStep = renderHandlebars(JSON.stringify(step), stepInput);
        steps.push({
          ...JSON.parse(renderedStep),
          innerHTML: (((_d = step === null || step === void 0 ? void 0 : step.template) === null || _d === void 0 ? void 0 : _d.id) &&
            renderHandlebars((_g = (_f = (_e = this.templates) === null || _e === void 0 ? void 0 : _e.find) === null || _f === void 0 ? void 0 : _f.call(_e, (t) => { var _a; return (t === null || t === void 0 ? void 0 : t.id) === ((_a = step.template) === null || _a === void 0 ? void 0 : _a.id); })) === null || _g === void 0 ? void 0 : _g.html, stepInput)) ||
            null,
        });
      }
      paths[pathName] = steps;
    }
    this.paths = paths;
    this.setPath(await this.checkPath());
  }
  async onChange() {
    const path = await this.checkPath();
    setTimeout(() => {
      var _a;
      this.formData = ((_a = this.flowEl) === null || _a === void 0 ? void 0 : _a.formData) || {};
    }, 500);
    if (path && this.currentPath && path !== this.currentPath)
      this.setPath(path);
  }
  onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === "listSteps") {
      this.steps = ((_c = (_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.steps) || [];
      if (!this.renderId)
        this.fetchFlow();
    }
    if (((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.endpoint) === this.endpoint) {
      this.showProgress = false;
    }
    if (((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.endpoint) === "findFlow") {
      this.flow = ((_g = (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.flow) || {};
      if ((_h = this.flow) === null || _h === void 0 ? void 0 : _h.defaultPath)
        this.currentPath = this.flow.defaultPath;
      if (this.renderId) {
        this.steps = ((_j = this.flow) === null || _j === void 0 ? void 0 : _j.steps) || [];
        this.templates = (_k = this.flow) === null || _k === void 0 ? void 0 : _k.templates;
      }
      this.renderPaths();
      if (!this.endpoint)
        this.endpoint = (_l = this.flow) === null || _l === void 0 ? void 0 : _l.endpoint;
      this.showProgress = ((_m = this.flow) === null || _m === void 0 ? void 0 : _m.showProgress) || false;
      this.successTemplate =
        (this.renderId && ((_p = (_o = this.flow) === null || _o === void 0 ? void 0 : _o.successTemplate) === null || _p === void 0 ? void 0 : _p.html)) ||
          ((_q = (this.templates || []).find((template) => { var _a, _b; return (template === null || template === void 0 ? void 0 : template.id) === ((_b = (_a = this.flow) === null || _a === void 0 ? void 0 : _a.successTemplate) === null || _b === void 0 ? void 0 : _b.id); })) === null || _q === void 0 ? void 0 : _q.html) ||
          null;
      this.errorTemplate =
        (this.renderId && ((_s = (_r = this.flow) === null || _r === void 0 ? void 0 : _r.errorTemplate) === null || _s === void 0 ? void 0 : _s.html)) ||
          ((_t = (this.templates || []).find((template) => { var _a, _b; return (template === null || template === void 0 ? void 0 : template.id) === ((_b = (_a = this.flow) === null || _a === void 0 ? void 0 : _a.errorTemplate) === null || _b === void 0 ? void 0 : _b.id); })) === null || _t === void 0 ? void 0 : _t.html) ||
          null;
      setTimeout(() => {
        this.flowEl.updateAutoHeight();
        this.isLoading = false;
      }, 1500);
    }
  }
  onError(event) {
    let errors = [];
    if (event.detail.endpoint === this.endpoint ||
      event.detail.name === "payCard") {
      this.isLoading = false;
      setTimeout(() => {
        var _a, _b, _c, _d, _e;
        errors = (_e = (_d = (_c = (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.response) === null || _c === void 0 ? void 0 : _c.errors) === null || _d === void 0 ? void 0 : _d.map) === null || _e === void 0 ? void 0 : _e.call(_d, (err) => err === null || err === void 0 ? void 0 : err.message);
        this.errors = errors;
      }, 100);
    }
  }
  onSlideWillChange() {
    var _a;
    if (!((_a = this.flow) === null || _a === void 0 ? void 0 : _a.paths))
      return;
    try {
      this.renderPaths();
    }
    catch (e) {
      console.log(e);
    }
  }
  async onSlideChange(event) {
    this.errors = null;
    this.currentSlideIndex = await event.target.getActiveIndex();
    await this.setPath();
  }
  async onBeforeSubmit(data) {
    var _a, _b;
    const input = (typeof this.beforeSubmit === "function" &&
      (await this.beforeSubmit(data))) ||
      data;
    this.renderedSuccessTemplate = this.successTemplate
      ? renderHandlebars(this.successTemplate, input)
      : `<floodteam-success-message animate="true" icon="${this.successIcon}" label="${this.successMessage || `${((_a = this.flow) === null || _a === void 0 ? void 0 : _a.name) || ""} Flow Completed!`}" ${((_b = this.flow) === null || _b === void 0 ? void 0 : _b.successConfetti) ? `auto-throw-confetti="true"` : ""} size="lg"  />`;
    return input;
  }
  async fetchFlow() {
    this.fireenjinFetch.emit({
      endpoint: "findFlow",
      params: {
        id: this.flowId,
        renderId: this.renderId,
      },
    });
  }
  async fetchSteps() {
    this.fireenjinFetch.emit({
      endpoint: "listSteps",
    });
  }
  componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    !this.renderId ? this.fetchSteps() : this.fetchFlow();
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g;
    const unit = 1 / ((_a = this.pathSteps) === null || _a === void 0 ? void 0 : _a.length);
    const progress = unit * this.currentSlideIndex;
    return (h(Host, { style: {
        opacity: this.isLoading ? "0" : "1",
        transition: "all ease 0.3s",
      } }, ((_b = this.flow) === null || _b === void 0 ? void 0 : _b.showProgress) &&
      !(this.currentSlideIndex >= ((_c = this.pathSteps) === null || _c === void 0 ? void 0 : _c.length)) && (h("ion-progress-bar", { style: {
        width: "80%",
        margin: this.showProgress ? "30px auto" : "0 auto",
        transition: "opacity ease 500ms",
        opacity: this.showProgress ? "1" : "0",
      }, value: progress })), (_e = (_d = this.errors) === null || _d === void 0 ? void 0 : _d.map) === null || _e === void 0 ? void 0 :
      _e.call(_d, (message) => (h("floodteam-error", null, this.errorTemplate ? this.errorTemplate : message))), h("fireenjin-flow", { ref: (el) => (this.flowEl = el), steps: this.pathSteps, endpoint: this.endpoint, fetch: this.fetch, formData: this.formData, googleMapsKey: (_g = (_f = state === null || state === void 0 ? void 0 : state.config) === null || _f === void 0 ? void 0 : _f.firebase) === null || _g === void 0 ? void 0 : _g.apiKey, beforeSubmit: this.onBeforeSubmit.bind(this) }, this.renderedSuccessTemplate && (h("div", { innerHTML: this.renderedSuccessTemplate || "" })))));
  }
};
FlowRider.style = flowRiderCss;

export { FlowRider as floodteam_flow_rider };
