import { Component, Host, h, Prop, Event, Element, State, Listen } from '@stencil/core';
export class HubspotForm {
  constructor() {
    this.portalId = '3776657';
    this.ajax = false;
    this.submitArrow = false;
    this.error = null;
    this.handleScriptLoad = () => {
      requestAnimationFrame(() => {
        window.hbspt.forms.create({
          portalId: '3776657',
          formId: this.formId,
          target: `#${this.getFormElementId()}`,
          goToWebinarWebinarKey: this.goToWebinarKey || '',
          css: '',
          onFormReady: this.handleFormReady,
        });
      });
    };
    this.handleFormReady = (_e, _c) => {
      var _a, _b;
      // Don't override the form if not using the ajax method
      if (!this.ajax) {
        return;
      }
      const formEl = (_a = this.el) === null || _a === void 0 ? void 0 : _a.querySelector(`#${this.getFormElementId()} form`);
      if (!formEl) {
        return;
      }
      formEl.addEventListener('submit', (e) => {
        e.preventDefault();
        e.stopPropagation();
        return false;
      });
      (_b = formEl.querySelector('input[type="submit"]')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', (e) => {
        this.submitForm(formEl);
        e.preventDefault();
      });
    };
    this.getFormElementId = () => `hbspt-form-${this.formId}`;
    this.submitForm = async (form) => {
      const data = new FormData(form);
      try {
        const ret = await fetch(form.getAttribute('action'), {
          method: 'POST',
          body: data,
        });
        if (ret.status !== 200) {
          this.error = 'Error submitting form';
        }
        else {
          // The response from hubspot is a script tag. I know, it's truly magnificent
          const frame = document.createElement('iframe');
          frame.srcdoc = await ret.text();
          document.body.appendChild(frame);
        }
      }
      catch (e) {
        this.error = 'Unable to submit form';
      }
    };
  }
  disconnectCallback() {
    var _a, _b;
    (_b = (_a = this.scriptEl) === null || _a === void 0 ? void 0 : _a.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(this.scriptEl);
  }
  componentDidLoad() {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.charset = 'utf-8';
    script.src = '//js.hsforms.net/forms/v2.js';
    script.addEventListener('load', this.handleScriptLoad);
    this.scriptEl = script;
    document.body.appendChild(script);
  }
  handleWindowMessage(e) {
    var _a;
    if (e.data && e.data.formGuid && this.ajax) {
      // Don't let hubspot do anything
      e.preventDefault();
      e.stopImmediatePropagation();
      if (e.data.accepted === true) {
        (_a = this.formSubmitted) === null || _a === void 0 ? void 0 : _a.emit();
      }
      else if (e.data.accepted === false) {
        this.error = 'Unable to submit. Please check your information and try again.';
      }
      else {
        this.error = '';
      }
    }
  }
  render() {
    return (h(Host, null,
      h("div", { class: `
            hubspot-override
            ${this.submitArrow ? 'submit-arrow' : ''}
            ${this.buttonPosition ? `button-position--${this.buttonPosition}` : ''}
          ` },
        h("div", { id: this.getFormElementId() })),
      this.error ? h("div", { class: "hs-error-msgs" }, this.error) : null));
  }
  static get is() { return "hubspot-form"; }
  static get originalStyleUrls() { return {
    "$": ["hubspot-form.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["hubspot-form.css"]
  }; }
  static get properties() { return {
    "formId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "form-id",
      "reflect": false
    },
    "portalId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "portal-id",
      "reflect": false,
      "defaultValue": "'3776657'"
    },
    "goToWebinarKey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "go-to-webinar-key",
      "reflect": false
    },
    "ajax": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "ajax",
      "reflect": false,
      "defaultValue": "false"
    },
    "submitArrow": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "submit-arrow",
      "reflect": false,
      "defaultValue": "false"
    },
    "buttonPosition": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'start' | 'center' | 'end'",
        "resolved": "\"center\" | \"end\" | \"start\"",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "button-position",
      "reflect": false
    }
  }; }
  static get states() { return {
    "error": {}
  }; }
  static get events() { return [{
      "method": "formSubmitted",
      "name": "formSubmitted",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "message",
      "method": "handleWindowMessage",
      "target": "window",
      "capture": false,
      "passive": false
    }]; }
}
