import { h, Env } from "@stencil/core";
import { getFormByKeyName } from "../../utils/utils";
import { renderSurvey } from "../../utils/surveyHelpers";
import { createScriptStyleLoader } from "../../utils/scriptStyleLoader";
export class Ai12zForm {
    constructor() {
        this.loadTimer = null;
        this.loadVersion = 0;
        this.surveyCDNPath = "https://cdn.ai12z.net/pkg/surveyjs";
        this.dataKey = Env.DATA_KEY || "";
        this.dataMode = Env.DATA_MODE || "prod";
        this.keyName = "";
        this.isLoading = false;
        this.error = "";
        this.isReady = false;
        this.honeypotValue = "";
        this.styles = [`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, `https://cdn.ai12z.net/pkg/surveyjs/survey-core@2.3.4/survey-core.min.css`];
        this.surveyDomId = `ai12z-form-survey-${Math.random().toString(36).slice(2, 10)}`;
    }
    async componentDidLoad() {
        await this.initializeAssetLoader();
        this.isReady = true;
        await this.loadDynamicForm();
    }
    async initializeAssetLoader() {
        try {
            this.assetLoader = createScriptStyleLoader({
                shadowRoot: this.el.shadowRoot,
                surveyCDNPath: this.surveyCDNPath,
                customStyles: this.styles,
            });
            // Load all bot assets
            await this.assetLoader.loadBotAssets();
            await this.assetLoader.loadSurveyDependencies();
            // console.log("✅ Asset loader initialized successfully")
        }
        catch (error) {
            console.error("❌ Failed to initialize asset loader:", error);
        }
    }
    disconnectedCallback() {
        // Invalidate any in-flight load by bumping the version
        this.loadVersion++;
        if (this.loadTimer)
            clearTimeout(this.loadTimer);
    }
    async watchLoadProps() {
        if (!this.isReady) {
            return;
        }
        if (this.loadTimer)
            clearTimeout(this.loadTimer);
        this.loadTimer = setTimeout(() => {
            this.loadDynamicForm();
        }, 150);
    }
    async loadDynamicForm(keyName) {
        var _a;
        const nextKeyName = (_a = (keyName !== null && keyName !== void 0 ? keyName : this.keyName)) === null || _a === void 0 ? void 0 : _a.trim();
        const version = ++this.loadVersion;
        if (!this.dataKey) {
            this.setError('Public Key is required. Please provide using attribute "data-key".');
            return;
        }
        this.error = "";
        this.isLoading = true;
        try {
            const response = await this.fetchResponse(nextKeyName);
            if (version !== this.loadVersion)
                return;
            if (!response.success) {
                const controlHint = nextKeyName ? ` for keyName "${nextKeyName}"` : "";
                throw new Error(`No form control found${controlHint}.`);
            }
            await renderSurvey({
                chat: {
                    keyName: response.form.keyName,
                    controlData: { form_model: response.form.model },
                    theme: response.form.theme,
                },
                surveyDomId: this.surveyDomId,
                shadowRoot: this.el.shadowRoot,
                config: {
                    dataKey: this.dataKey,
                    dataMode: this.dataMode,
                    onSubmitError: errorMessage => {
                        if (errorMessage === "Form submission blocked by validation") {
                            this.setError("Submission blocked due to suspicious activity.");
                            return;
                        }
                        this.setError(errorMessage || "Failed to submit form");
                    },
                    formSubmitRenderCallback: processedResults => {
                        var _a, _b, _c;
                        this.error = "";
                        const targetDomId = (processedResults === null || processedResults === void 0 ? void 0 : processedResults.domId) || this.surveyDomId;
                        const container = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector(`#${targetDomId}`);
                        if (container) {
                            container.innerHTML = processedResults.completedHtml;
                        }
                        this.formSubmitted.emit((_c = (_b = processedResults.sender) === null || _b === void 0 ? void 0 : _b.data) !== null && _c !== void 0 ? _c : processedResults.results);
                    },
                },
            });
        }
        catch (error) {
            const msg = (error === null || error === void 0 ? void 0 : error.message) || "Failed to load form";
            this.setError(msg);
        }
        finally {
            this.isLoading = false;
        }
    }
    async fetchResponse(keyName) {
        const response = await getFormByKeyName(this.dataKey, this.dataMode, keyName !== null && keyName !== void 0 ? keyName : this.keyName);
        return response;
    }
    setError(message) {
        this.error = message;
        this.errored.emit(message);
    }
    render() {
        return (h("div", { key: 'b31dc3055b20ff63de53571749e4394acfce4441', class: "ai12z-form-wrapper" }, this.error && !this.isLoading && h("div", { key: '0a09604f199fa41a6a8a18755782489cc4fa8f6b', class: "ai12z-form-error" }, this.error), h("div", { key: '970ee7d88aa2a7971c9841a8d51392a1c703d2ce', id: this.surveyDomId, class: "ai12z-form-container" })));
    }
    static get is() { return "ai12z-form"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["./ai12z-form.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ai12z-form.css"]
        };
    }
    static get properties() {
        return {
            "dataKey": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-key",
                "defaultValue": "Env.DATA_KEY || \"\""
            },
            "dataMode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-mode",
                "defaultValue": "Env.DATA_MODE || \"prod\""
            },
            "keyName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "key-name",
                "defaultValue": "\"\""
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "error": {},
            "isReady": {},
            "honeypotValue": {}
        };
    }
    static get events() {
        return [{
                "method": "formSubmitted",
                "name": "formSubmitted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "errored",
                "name": "errored",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "loadDynamicForm": {
                "complexType": {
                    "signature": "(keyName?: string) => Promise<void>",
                    "parameters": [{
                            "name": "keyName",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "keyName",
                "methodName": "watchLoadProps"
            }];
    }
}
