import { g as getAllLanguagesInSurvey, a as getBroswerLang, s as submitForm } from './utils-DK_Yhmpx.js';

class SurveyRenderer {
    constructor(config) {
        this.honeypotFieldName = "ai12z_control";
        this.config = config;
    }
    /**
     * Initialize Survey.js library and add custom properties
     */
    initializeSurveyLibrary() {
        if (!window["Survey"]) {
            throw new Error("Survey.js library not loaded");
        }
        // Add custom property
        window["Survey"].Serializer.addProperty("survey", {
            name: "keyName:string",
            visible: false,
            category: "general",
            default: "",
        });
    }
    /**
     * Prepare and validate form model
     */
    prepareFormModel(chat) {
        var _a, _b, _c, _d, _e, _f;
        // console.log("Preparing form model for chat:", chat)
        let formModel = (_c = (_b = (_a = chat.controlData) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.source) !== null && _c !== void 0 ? _c : (chat.controlData ? (_d = chat.controlData) === null || _d === void 0 ? void 0 : _d.form_model : null);
        if (typeof formModel === "string") {
            try {
                formModel = JSON.parse(formModel);
            }
            catch (error) {
                throw new Error("Invalid JSON in form model");
            }
        }
        if (typeof formModel === "object" && formModel !== null) {
            formModel.keyName = (_e = chat.keyName) !== null && _e !== void 0 ? _e : (_f = chat.controlData) === null || _f === void 0 ? void 0 : _f.key_name;
            this.injectHoneypotField(formModel);
            return formModel;
        }
        throw new Error("Invalid form model format");
    }
    injectHoneypotField(formModel) {
        if (!formModel.pages || !Array.isArray(formModel.pages)) {
            return;
        }
        if (this.hasField(formModel.pages, this.honeypotFieldName)) {
            return;
        }
        const firstPage = formModel.pages[0];
        if (!firstPage) {
            return;
        }
        if (!Array.isArray(firstPage.elements)) {
            firstPage.elements = [];
        }
        firstPage.elements.push({
            type: "text",
            name: this.honeypotFieldName,
            title: "Leave this field empty",
            visible: true,
            isRequired: false,
        });
    }
    hasField(pages, fieldName) {
        return pages.some(page => {
            const elements = page === null || page === void 0 ? void 0 : page.elements;
            if (!Array.isArray(elements)) {
                return false;
            }
            return elements.some(element => (element === null || element === void 0 ? void 0 : element.name) === fieldName);
        });
    }
    /**
     * Determine the best locale for the survey
     */
    determineLocale(formModel) {
        var _a;
        const supportedLocales = getAllLanguagesInSurvey(formModel);
        // Priority: dataAttributes.lang > browser language > default
        if (((_a = this.config.dataAttributes) === null || _a === void 0 ? void 0 : _a.lang) && supportedLocales.has(this.config.dataAttributes.lang)) {
            return this.config.dataAttributes.lang;
        }
        const browserLang = getBroswerLang();
        if (supportedLocales.has(browserLang)) {
            return browserLang;
        }
        return "default";
    }
    /**
     * Configure survey instance
     */
    configureSurvey(survey, formModel, chat) {
        var _a, _b, _c, _d;
        survey.showCompletedPage = false;
        survey.completeText = (_a = formModel === null || formModel === void 0 ? void 0 : formModel.completeText) !== null && _a !== void 0 ? _a : "";
        survey.completedHTML = (_b = formModel === null || formModel === void 0 ? void 0 : formModel.completedHtml) !== null && _b !== void 0 ? _b : "Thank You!";
        // Apply theme if available - check both locations
        const themeData = (_c = chat.theme) !== null && _c !== void 0 ? _c : (_d = chat.controlData) === null || _d === void 0 ? void 0 : _d.theme;
        if (themeData) {
            try {
                const themeObj = typeof themeData === "string" ? JSON.parse(themeData) : themeData;
                survey.applyTheme(themeObj);
                // console.log("Survey theme applied successfully")
            }
            catch (error) {
                console.warn("Failed to apply survey theme:", error);
            }
        }
        else {
            console.warn("No theme data found in chat object");
        }
        // Hide complete button for iframe elements
        this.hideCompleteButtonForIframes(formModel, survey);
        // Add event handlers
        survey.onAfterRenderQuestionInput.add((_, options) => {
            options.htmlElement.name = options.question.name;
        });
        survey.onAfterRenderQuestion.add((_, options) => {
            if (options.question.name === "ai12z_control") {
                options.htmlElement.classList.add("ai12z-form-honeypot");
            }
        });
        survey.onUpdateQuestionCssClasses.add((_, options) => {
            if (options.question.name === "ai12z_control") {
                // This adds the class to the root element of the question
                options.cssClasses.mainRoot += " ai12z-form-honeypot";
            }
        });
        // ✅ Fix: Properly set up the survey completion handler
        survey.onComplete.add(async (sender) => {
            try {
                // Handle survey results and get processed data
                const processedResults = await this.handleSurveyResults(sender);
                // Call the render callback with the processed results
                if (this.config.formSubmitRenderCallback) {
                    this.config.formSubmitRenderCallback(processedResults);
                }
            }
            catch (error) {
                if (this.config.onSubmitError) {
                    this.config.onSubmitError((error === null || error === void 0 ? void 0 : error.message) || "Failed to submit form", { sender });
                }
                console.error("Error in survey completion handler:", error);
            }
        });
    }
    /**
     * Hide complete button if form contains iframe elements
     */
    hideCompleteButtonForIframes(formModel, survey) {
        if (formModel === null || formModel === void 0 ? void 0 : formModel.pages) {
            formModel.pages.forEach((page) => {
                if (page.elements) {
                    page.elements.forEach((element) => {
                        var _a, _b;
                        if (element.type === "html") {
                            if (typeof element.html === "string") {
                                if ((_a = element.html) === null || _a === void 0 ? void 0 : _a.includes("<iframe")) {
                                    survey.showCompleteButton = false;
                                }
                            }
                            else if (typeof element.html === "object") {
                                if ((_b = element.html[getBroswerLang()]) === null || _b === void 0 ? void 0 : _b.includes("<iframe")) {
                                    survey.showCompleteButton = false;
                                }
                            }
                        }
                    });
                }
            });
        }
    }
    /**
     * Handle survey results submission
     */
    async handleSurveyResults(sender) {
        var _a, _b, _c, _d, _e;
        try {
            // Emit form submission event
            //   this.formSubmitted.emit(sender.data)
            // Prepare results
            const results = this.prepareResults(sender);
            const honeypotValue = this.getHoneypotValue(sender);
            if (honeypotValue.length > 0) {
                throw new Error("Form submission blocked by validation");
            }
            delete results[this.honeypotFieldName];
            // Submit form data
            const response = await submitForm(this.config.dataKey, this.config.dataMode, sender.keyName, results);
            // console.log("Form submission response:", response)
            const processedHTML = sender.processText((_a = sender.jsonObj) === null || _a === void 0 ? void 0 : _a.completedHtml);
            // ✅ Return processed results with all necessary data
            const processedResults = {
                sender,
                results,
                response,
                completedHtml: this.resolveLocalized(processedHTML, "Thank You!"),
                completeText: this.resolveLocalized((_b = sender.jsonObj) === null || _b === void 0 ? void 0 : _b.completeText, "Submit"),
                domId: (_e = (_d = (_c = sender.implementor) === null || _c === void 0 ? void 0 : _c.renderedElement) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : sender.domId,
                keyName: sender.keyName,
                jsonData: `This JSON is from a form submission [${sender.keyName}]: ${JSON.stringify(results, null, 2)}. There is no need to show the form [${sender.keyName}] again.`,
            };
            return processedResults;
        }
        catch (error) {
            console.error("Form submission error:", error);
            throw error;
        }
    }
    getHoneypotValue(sender) {
        var _a, _b, _c;
        const rawValue = (_c = (_b = (_a = sender === null || sender === void 0 ? void 0 : sender.data) === null || _a === void 0 ? void 0 : _a[this.honeypotFieldName]) !== null && _b !== void 0 ? _b : sender === null || sender === void 0 ? void 0 : sender[this.honeypotFieldName]) !== null && _c !== void 0 ? _c : "";
        if (typeof rawValue === "string") {
            return rawValue.trim();
        }
        if (rawValue === null || rawValue === undefined) {
            return "";
        }
        return String(rawValue).trim();
    }
    /**
     * Prepare survey results
     */
    prepareResults(sender) {
        const results = JSON.parse(JSON.stringify(sender.data));
        results.description = this.resolveLocalized(sender.jsonObj.description, "");
        return results;
    }
    /**
     * Resolve localized values
     */
    resolveLocalized(value, fallback = "") {
        var _a;
        if (!value)
            return fallback;
        if (typeof value === "string") {
            return value;
        }
        if (typeof value === "object") {
            const defaultLang = (_a = this.config.dataAttributes) === null || _a === void 0 ? void 0 : _a.lang;
            return value[defaultLang] || value[getBroswerLang()] || value.default || fallback;
        }
        return fallback;
    }
    /**
     * Main render method
     */
    async renderSurvey(options) {
        try {
            // Initialize Survey.js
            this.initializeSurveyLibrary();
            // Prepare form model
            const formModel = this.prepareFormModel(options.chat);
            // Set locale
            const locale = this.determineLocale(formModel);
            window["Survey"].surveyLocalization.currentLocale = locale;
            // Create survey instance
            const survey = new window["Survey"].Model(formModel);
            // Find DOM element
            const domElement = options.shadowRoot.querySelector(`#${options.surveyDomId}`);
            if (!domElement) {
                throw new Error(`Survey element with ID ${options.surveyDomId} not found`);
            }
            // Configure survey
            survey.domId = options.surveyDomId;
            this.configureSurvey(survey, formModel, options.chat);
            // Render survey
            survey.render(domElement);
            return survey;
        }
        catch (error) {
            console.error("Error rendering survey:", error);
            this.handleSurveyError(options.shadowRoot, options.surveyDomId, error.message);
            throw error;
        }
    }
    /**
     * Handle survey rendering errors
     */
    handleSurveyError(shadowRoot, surveyDomId, errorMessage) {
        const domElement = shadowRoot.querySelector(`#${surveyDomId}`);
        if (domElement) {
            domElement.innerHTML = `
        <div class="survey-error">
          <p class="error-message">Failed to load survey: ${errorMessage}</p>
          <button onclick="location.reload()" class="retry-button">Retry</button>
        </div>
      `;
        }
    }
}
// ✅ Utility function for simple usage
async function renderSurvey(options) {
    const renderer = new SurveyRenderer(options.config);
    return await renderer.renderSurvey(options);
}

export { renderSurvey as r };
