import { isDemo, useParentState } from "@saasquatch/component-boilerplate";
import { withHooks } from "@saasquatch/stencil-hooks";
import { useCallback, useEffect, useState } from "@saasquatch/universal-hooks";
import { Component, h, Host, Prop } from "@stencil/core";
import debugFn from "debug";
import { VERIFICATION_PARENT_NAMESPACE } from "./keys";
const debug = debugFn("sq:widget-verification");
function useTemplateChildren({ parent, callback }) {
  const parentObserver = new MutationObserver(listenForTemplateChanges);
  const childTemplateObserver = new MutationObserver(callback);
  parentObserver.observe(parent, {
    childList: true,
    // We only care about immediate children templates
    subtree: false,
  });
  listenForTemplateChanges({ addedNodes: parent.querySelectorAll("template") });
  function listenForTemplateChanges(mutationList) {
    var _a;
    // Be smart, only look at the mutation list
    (_a = mutationList.addedNodes) === null || _a === void 0 ? void 0 : _a.forEach((t) => {
      childTemplateObserver.observe(t.content, {
        childList: true,
        attributes: true,
        // Look deep into the templates for re-rendering
        subtree: true,
      });
    });
  }
  return () => {
    parentObserver.disconnect();
    childTemplateObserver.disconnect();
  };
}
/**
 * @uiName Widget Verification Controller
 * @slots [{"name":"not-verified","title":"Not Verified template"},{"name":"verified","title":"Verified template"}]
 * @exampleGroup Tax and Cash
 * @example Widget Cash Payout Form - <sqm-widget-verification-controller><template slot="not-verified"><sqm-widget-verification></sqm-widget-verification></template><template slot="verified"><sqm-tax-and-cash></sqm-tax-and-cash></template></sqm-widget-verification-controller>
 * @canvasRenderer always-replace
 */
export class WidgetVerificationController {
  constructor() {
    /**
     * @undocumented
     * @componentState { "title": "Verify email", "slot": "not-verified", "props": { "isAuth": false }, "disabled": "true" }
     * @componentState { "title": "Tax and cash", "slot": "verified", "props": { "isAuth": true }, "disabled": "true" }
     */
    this.stateController = "{}";
    withHooks(this);
  }
  disconnectedCallback() { }
  render() {
    var _a;
    const [context, setContext] = useParentState({
      namespace: VERIFICATION_PARENT_NAMESPACE,
      initialValue: false,
    });
    const props = JSON.parse(this.stateController);
    const demoIsAuth = isDemo() && ((_a = props["sqm-widget-verification-controller"]) === null || _a === void 0 ? void 0 : _a.isAuth);
    const [container, setContainer] = useState(undefined);
    const [slot, setSlot] = useState(undefined);
    const updateTemplates = useCallback(() => {
      const isAuth = demoIsAuth || context;
      const templates = slot.querySelectorAll(`template`);
      const template = Array.from(templates).find((t) => t.slot === (isAuth ? "verified" : "not-verified"));
      if (template) {
        // use outerHTML if template's innerHTML is unset (only happens in Stencilbook)
        const newContent = template.innerHTML || template.firstElementChild.outerHTML;
        // if template contents are an exact match
        if (newContent === container.innerHTML) {
          debug("don't rerender");
        }
        else if (template) {
          container.innerHTML = newContent;
        }
      }
      const plopTargets = Array.from(slot.children).filter((el) => el.tagName === "RAISINS-PLOP-TARGET");
      // if editing in raisins
      if (plopTargets.length) {
        const loggedInPlopTargets = plopTargets.filter((el) => el.slot === "verified");
        const loggedOutPlopTargets = plopTargets.filter((el) => el.slot === "not-verified");
        loggedOutPlopTargets.forEach((target, i) => {
          if (isAuth) {
            target.style.display = "none";
            return;
          }
          // Place last plop target at the bottom of the parent
          if (i === loggedOutPlopTargets.length - 1) {
            target.style.bottom = "0px";
            target.style.left = "0px";
            target.style.right = "0px";
            target.style.position = "absolute";
          }
          target.style.height = "25px";
        });
        loggedInPlopTargets.forEach((target, i) => {
          if (!isAuth) {
            target.style.display = "none";
            return;
          }
          // Place last plop target at the bottom of the parent
          if (i === loggedInPlopTargets.length - 1) {
            target.style.bottom = "0px";
            target.style.left = "0px";
            target.style.right = "0px";
            target.style.position = "absolute";
          }
          target.style.height = "25px";
        });
      }
    }, [container, slot, context, demoIsAuth]);
    useEffect(() => {
      if (!container || !slot) {
        debug("DOM not ready:");
        return;
      }
      // Run on first render
      updateTemplates();
      return useTemplateChildren({ parent: slot, callback: updateTemplates });
    }, [slot, container, context, demoIsAuth]);
    return (h(Host, null,
      h("div", { ref: setSlot, style: { display: "contents" } },
        h("slot", { name: "not-verified" }),
        h("slot", { name: "verified" })),
      h("div", { ref: setContainer },
        h("slot", { name: "shown" }))));
  }
  static get is() { return "sqm-widget-verification-controller"; }
  static get properties() { return {
    "stateController": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "text": undefined,
            "name": "undocumented"
          }, {
            "text": "{ \"title\": \"Verify email\", \"slot\": \"not-verified\", \"props\": { \"isAuth\": false }, \"disabled\": \"true\" }",
            "name": "componentState"
          }, {
            "text": "{ \"title\": \"Tax and cash\", \"slot\": \"verified\", \"props\": { \"isAuth\": true }, \"disabled\": \"true\" }",
            "name": "componentState"
          }],
        "text": ""
      },
      "attribute": "state-controller",
      "reflect": false,
      "defaultValue": "\"{}\""
    }
  }; }
}
