import { h } from "@stencil/core";
import { getBroswerLang, getAllLanguagesInSurvey, insertStyles } from "../../../utils/utils";
export class DynamicForm {
    constructor() {
        this.surveyCDNPath = "https://cdn.ai12z.net/pkg/surveyjs";
    }
    componentWillLoad() {
        var _a;
        insertStyles(`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, this.el);
        this.loadScriptsSequentially();
        // console.log("form", this.form)
        let supportedLocales;
        if (this.form) {
            supportedLocales = getAllLanguagesInSurvey(JSON.parse(this.form));
        }
        // console.log("supportedLocales", supportedLocales)
        if (supportedLocales.has(getBroswerLang())) {
            window["Survey"].surveyLocalization.currentLocale = getBroswerLang();
        }
        else {
            window["Survey"].surveyLocalization.currentLocale = "default";
        }
        // window["Survey"].surveyLocalization.currentLocale = supportedLocales.includes(getBroswerLang()) ? getBroswerLang() : "default"
        // Initialize the SurveyJS model
        this.surveyModel = new window["Survey"].Model(this.form);
        // window["Survey"].StylesManager.applyTheme(JSON.parse(this.theme))
        // const theme = window["SurveyTheme"]?.PlainLightPanelless
        // const theme = this.theme ? window["Survey"].StylesManager.applyTheme(JSON.parse(this.theme)) : window["SurveyTheme"]?.PlainLightPanelless
        if (this.theme && typeof JSON.parse(this.theme) === "object") {
            this.surveyModel.applyTheme(JSON.parse(this.theme));
        }
        else {
            const theme = (_a = window["SurveyTheme"]) === null || _a === void 0 ? void 0 : _a.PlainLightPanelless;
            if (theme) {
                this.surveyModel.applyTheme(theme);
            }
            console.warn("Invalid theme object:", this.theme);
        }
        if (!this.formSettings) {
            this.formSettings = JSON.parse(this.formsettings);
        }
        // Handle survey completion
        this.surveyModel.onComplete.add(sender => {
            // console.log("Survey completed:", sender.data)
            this.formSubmitted.emit(sender);
        });
        this.surveyModel.onAfterRenderQuestionInput.add(function (_, options) {
            options.htmlElement.name = options.question.name;
        });
    }
    async loadScriptsSequentially() {
        try {
            // 2. Load Survey Core
            await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/survey.core.min.js`);
            // 3. Load Survey i18n
            await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/survey.i18n.min.js`);
            // 4. Load Survey themes
            await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/themes/index.min.js`);
            // 6. Load Survey UI
            await this.loadScript(`${this.surveyCDNPath}/survey-js-ui@2.3.4/survey-js-ui.min.js`);
            // console.log("All Survey.js scripts loaded successfully")
        }
        catch (error) {
            console.error("Failed to load Survey.js scripts:", error);
        }
    }
    loadScript(src) {
        return new Promise((resolve, reject) => {
            if (document.querySelector(`script[src="${src}"]`)) {
                resolve();
                return;
            }
            const script = document.createElement("script");
            script.src = src;
            script.async = false;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
            // Load in document head for global access
            // document.head.appendChild(script)
            this.el.shadowRoot.appendChild(script);
        });
    }
    componentDidLoad() {
        var _a;
        // Render the SurveyJS survey
        const surveyContainer = this.el.querySelector("#surveyContainer");
        if (surveyContainer) {
            this.applySettings();
            (_a = this.surveyModel) === null || _a === void 0 ? void 0 : _a.render(surveyContainer);
        }
    }
    disconnectedCallback() {
        // Dispose of the Form model to free resources
        if (this.surveyModel) {
            this.surveyModel.dispose();
        }
    }
    applySettings() {
        var _a, _b, _c, _d, _e, _f, _g;
        if ((_a = this.formSettings) === null || _a === void 0 ? void 0 : _a.showProgressBar) {
            this.surveyModel.showProgressBar = this.formSettings.showProgressBar;
        }
        if ((_b = this.formSettings) === null || _b === void 0 ? void 0 : _b.showQuestionNumbers) {
            this.surveyModel.showQuestionNumbers = this.formSettings.showQuestionNumbers;
        }
        if ((_c = this.formSettings) === null || _c === void 0 ? void 0 : _c.completeText) {
            this.surveyModel.completeText = this.resolveLocalized(this.formSettings.completeText, "Submit");
        }
        if ((_d = this.formSettings) === null || _d === void 0 ? void 0 : _d.startSurveyText) {
            this.surveyModel.startSurveyText = this.formSettings.startSurveyText;
        }
        if ((_e = this.formSettings) === null || _e === void 0 ? void 0 : _e.pagePrevText) {
            this.surveyModel.pagePrevText = this.formSettings.pagePrevText;
        }
        if ((_f = this.formSettings) === null || _f === void 0 ? void 0 : _f.completedHTML) {
            this.surveyModel.completedHtml = this.resolveLocalized((_g = this.formSettings) === null || _g === void 0 ? void 0 : _g.completedHtml, "Thank You!");
        }
    }
    resolveLocalized(value, fallback = "") {
        if (!value)
            return fallback;
        if (typeof value === "string") {
            return value;
        }
        if (typeof value === "object") {
            return value[getBroswerLang()] || value.default || fallback;
        }
        return fallback;
    }
    render() {
        return h("div", { key: '3c14f096fdaa5f7aa2618cc364b98bad84b70895', id: "surveyContainer" });
    }
    static get is() { return "dynamic-form"; }
    static get originalStyleUrls() {
        return {
            "$": ["DynamicForm.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["DynamicForm.css"]
        };
    }
    static get properties() {
        return {
            "form": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "form"
            },
            "formSettings": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "form-settings"
            },
            "formsettings": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "formsettings"
            },
            "theme": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "theme"
            }
        };
    }
    static get events() {
        return [{
                "method": "formSubmitted",
                "name": "formComplete",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
