import { r as registerInstance, a as createEvent, E as Env, h, d as getElement } from './index-BNpVu1WU.js';
import { Q as getFormByKeyName } from './utils-DK_Yhmpx.js';
import { r as renderSurvey } from './surveyHelpers-D-00eWjv.js';
import { c as createScriptStyleLoader } from './scriptStyleLoader-DXBxSLgN.js';

const ai12zFormCss = () => `.ai12z-form-wrapper{width:100%}.ai12z-form-status,.ai12z-form-error{font-size:14px;margin-bottom:8px}.ai12z-form-error{color:#b91c1c}.ai12z-form-container{width:100%}.ai12z-form-honeypot{position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden}@keyframes ai12z-form-spin{to{transform:rotate(360deg)}}@keyframes ai12z-form-bounce{0%,80%,100%{opacity:0.35;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}`;

const Ai12zForm = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.formSubmitted = createEvent(this, "formSubmitted", 7);
        this.errored = createEvent(this, "errored", 7);
        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" })));
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "keyName": [{
                "watchLoadProps": 0
            }]
    }; }
};
Ai12zForm.style = ai12zFormCss();

export { Ai12zForm as ai12z_form };
