"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    AtomicInsightGeneratedAnswer: ()=>AtomicInsightGeneratedAnswer
});
const bueno_namespaceObject = require("@coveo/bueno");
const insight_namespaceObject = require("@coveo/headless/insight");
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const when_js_namespaceObject = require("lit/directives/when.js");
const generated_answer_controller_cjs_namespaceObject = require("../../common/generated-answer/generated-answer-controller.cjs");
const render_answer_content_cjs_namespaceObject = require("../../common/generated-answer/render-answer-content.cjs");
const render_card_header_cjs_namespaceObject = require("../../common/generated-answer/render-card-header.cjs");
const render_citations_cjs_namespaceObject = require("../../common/generated-answer/render-citations.cjs");
const render_custom_no_answer_message_cjs_namespaceObject = require("../../common/generated-answer/render-custom-no-answer-message.cjs");
const render_disclaimer_cjs_namespaceObject = require("../../common/generated-answer/render-disclaimer.cjs");
const render_feedback_and_copy_buttons_cjs_namespaceObject = require("../../common/generated-answer/render-feedback-and-copy-buttons.cjs");
const validate_props_controller_cjs_namespaceObject = require("../../common/validate-props-controller/validate-props-controller.cjs");
const boolean_converter_cjs_namespaceObject = require("../../../converters/boolean-converter.cjs");
const legacy_array_string_converter_cjs_namespaceObject = require("../../../converters/legacy-array-string-converter.cjs");
const bind_state_cjs_namespaceObject = require("../../../decorators/bind-state.cjs");
const binding_guard_cjs_namespaceObject = require("../../../decorators/binding-guard.cjs");
const bindings_cjs_namespaceObject = require("../../../decorators/bindings.cjs");
const error_guard_cjs_namespaceObject = require("../../../decorators/error-guard.cjs");
const with_tailwind_styles_cjs_namespaceObject = require("../../../decorators/with-tailwind-styles.cjs");
const accessibility_utils_cjs_namespaceObject = require("../../../utils/accessibility-utils.cjs");
const debounce_utils_cjs_namespaceObject = require("../../../utils/debounce-utils.cjs");
const slot_utils_cjs_namespaceObject = require("../../../utils/slot-utils.cjs");
const external_atomic_insight_generated_answer_tw_css_cjs_namespaceObject = require("./atomic-insight-generated-answer.tw.css.cjs");
var external_atomic_insight_generated_answer_tw_css_cjs_default = /*#__PURE__*/ __webpack_require__.n(external_atomic_insight_generated_answer_tw_css_cjs_namespaceObject);
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicInsightGeneratedAnswer extends external_lit_namespaceObject.LitElement {
    initialize() {
        this.controller = new generated_answer_controller_cjs_namespaceObject.GeneratedAnswerController(this, {
            withToggle: this.withToggle,
            getGeneratedAnswer: ()=>this.generatedAnswer,
            getGeneratedAnswerState: ()=>this.generatedAnswerState,
            getSearchStatusState: ()=>this.searchStatusState,
            getBindings: ()=>this.bindings
        });
        this.generatedAnswer = (0, insight_namespaceObject.buildGeneratedAnswer)(this.bindings.engine, {
            initialState: {
                isVisible: this.controller.data.isVisible,
                responseFormat: {
                    contentFormat: [
                        'text/markdown',
                        'text/plain'
                    ]
                }
            },
            ...this.answerConfigurationId && {
                answerConfigurationId: this.answerConfigurationId
            },
            fieldsToIncludeInCitations: this.getCitationFields()
        });
        this.searchStatus = (0, insight_namespaceObject.buildSearchStatus)(this.bindings.engine);
        this.controller.insertFeedbackModal();
        if (window.ResizeObserver && this.collapsible) {
            const debouncedAdaptAnswerHeight = (0, debounce_utils_cjs_namespaceObject.debounce)(()=>this.adaptAnswerHeight(), 100);
            this.resizeObserver = new ResizeObserver(debouncedAdaptAnswerHeight);
            this.resizeObserver.observe(this);
        }
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.resizeObserver?.disconnect();
    }
    willUpdate(changedProperties) {
        if (changedProperties.has('generatedAnswerState')) {
            const oldState = changedProperties.get('generatedAnswerState');
            if (oldState && this.generatedAnswerState?.expanded !== oldState?.expanded) {
                const container = this.getAnswerContainer();
                if (container) this.toggleClass(container, 'answer-collapsed', !this.generatedAnswerState.expanded);
            }
        }
    }
    render() {
        const contentClasses = 'mx-auto mt-0 mb-4 border border-neutral shadow-lg bg-background rounded-lg text-on-background';
        if (this.hasNoAnswerGenerated) {
            if (this.generatedAnswerState?.cannotAnswer && this.hasCustomNoAnswerMessage) return (0, external_lit_namespaceObject.html)`
          <div>
            <aside
              class=${contentClasses}
              part="container"
              aria-label=${this.bindings.i18n.t('generated-answer-title')}
            >
              <div part="generated-content">
                ${this.renderCardHeaderWrapper()}
                ${(0, when_js_namespaceObject.when)(this.isAnswerVisible, ()=>(0, external_lit_namespaceObject.html)`<article>${(0, render_custom_no_answer_message_cjs_namespaceObject.renderCustomNoAnswerMessage)()}</article>`)}
              </div>
            </aside>
          </div>
        `;
            return external_lit_namespaceObject.nothing;
        }
        return (0, external_lit_namespaceObject.html)`
      <div>
        <aside
          class=${contentClasses}
          part="container"
          aria-label=${this.bindings.i18n.t('generated-answer-title')}
        >
          <div part="generated-content">
            ${this.renderCardHeaderWrapper()}
            ${(0, when_js_namespaceObject.when)(this.isAnswerVisible, ()=>(0, external_lit_namespaceObject.html)` <div part="generated-content-container" class="px-6 pb-6">
                  <article>${this.renderContent()}</article>
                  ${(0, render_disclaimer_cjs_namespaceObject.renderDisclaimer)({
                props: {
                    i18n: this.bindings.i18n
                }
            })}
                </div>`)}
          </div>
        </aside>
      </div>
    `;
    }
    get hasNoAnswerGenerated() {
        return this.controller.hasNoAnswerGenerated;
    }
    get isAnswerVisible() {
        return this.controller.isAnswerVisible;
    }
    get toggleTooltip() {
        return this.controller.getToggleTooltip();
    }
    get copyToClipboardTooltip() {
        return this.controller.getCopyToClipboardTooltip(this.copied, this.copyError);
    }
    get hasCustomNoAnswerMessage() {
        return (0, slot_utils_cjs_namespaceObject.getNamedSlotContent)(this, 'no-answer-message').length > 0;
    }
    async copyToClipboard(answer) {
        await this.controller.copyToClipboard(answer, ()=>{
            this.copied = true;
            setTimeout(()=>{
                this.copied = false;
            }, 2000);
        }, ()=>{
            this.copyError = true;
            setTimeout(()=>{
                this.copyError = false;
            }, 2000);
        });
    }
    clickOnShowButton() {
        this.controller.clickOnShowButton();
    }
    getCitationFields() {
        let fields = [];
        if (Array.isArray(this.fieldsToIncludeInCitations)) fields = this.fieldsToIncludeInCitations;
        else if ('string' == typeof this.fieldsToIncludeInCitations) fields = this.fieldsToIncludeInCitations.split(',').map((f)=>f.trim()).filter((f)=>f.length > 0);
        return fields.concat(this.REQUIRED_FIELDS_TO_INCLUDE_IN_CITATIONS);
    }
    validateMaxCollapsedHeight() {
        const isValid = this.maxCollapsedHeight >= this.MIN_COLLAPSED_HEIGHT && this.maxCollapsedHeight <= this.MAX_COLLAPSED_HEIGHT;
        if (!isValid) console.warn(`max-collapsed-height (${this.maxCollapsedHeight}rem) is out of the valid range (${this.MIN_COLLAPSED_HEIGHT}rem - ${this.MAX_COLLAPSED_HEIGHT}rem). Falling back to default value (${this.DEFAULT_COLLAPSED_HEIGHT}rem).`);
        return isValid ? this.maxCollapsedHeight : this.DEFAULT_COLLAPSED_HEIGHT;
    }
    toggleClass(element, className, condition) {
        element.classList.toggle(className, condition);
    }
    adaptAnswerHeight() {
        const answerHeight = this.shadowRoot?.querySelector('[part="generated-text"]')?.getBoundingClientRect().height;
        if (answerHeight) {
            const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
            const nextFullAnswerHeight = answerHeight / rootFontSize;
            if (this.fullAnswerHeight !== nextFullAnswerHeight) {
                this.fullAnswerHeight = nextFullAnswerHeight;
                this.requestUpdate();
            }
            this.updateAnswerHeight();
        }
    }
    getAnswerContainer() {
        return this.shadowRoot?.querySelector('[part="generated-container"]');
    }
    getAnswerFooter() {
        return this.shadowRoot?.querySelector('[part="generated-answer-footer"]');
    }
    setCSSVariable(variableName, value) {
        const container = this.getAnswerContainer();
        if (container) container.style.setProperty(variableName, value);
    }
    updateAnswerHeight() {
        const container = this.getAnswerContainer();
        const footer = this.getAnswerFooter();
        const maxHeight = this.validateMaxCollapsedHeight();
        if (!container || !footer) return;
        if (this.fullAnswerHeight > maxHeight) {
            this.setCSSVariable('--atomic-crga-collapsed-height', `${maxHeight}rem`);
            this.toggleClass(container, 'answer-collapsed', !this.generatedAnswerState.expanded);
            this.toggleClass(footer, 'is-collapsible', true);
            this.toggleClass(footer, 'generating-label-visible', this.generatedAnswerState.isStreaming);
        } else {
            this.toggleClass(container, 'answer-collapsed', false);
            this.toggleClass(footer, 'is-collapsible', false);
            this.toggleClass(footer, 'generating-label-visible', false);
        }
    }
    clickDislike() {
        this.controller.clickDislike();
    }
    clickLike() {
        this.controller.clickLike();
    }
    renderCitationsList() {
        const { citations } = this.generatedAnswerState ?? {};
        return (0, render_citations_cjs_namespaceObject.renderCitations)({
            props: {
                citations,
                i18n: this.bindings.i18n,
                buildInteractiveCitation: (citation)=>(0, insight_namespaceObject.buildInteractiveCitation)(this.bindings.engine, {
                        options: {
                            citation
                        }
                    }),
                logCitationHover: (citationId, citationHoverTimeMs)=>{
                    this.generatedAnswer?.logCitationHover(citationId, citationHoverTimeMs);
                },
                disableCitationAnchoring: this.disableCitationAnchoring
            }
        });
    }
    renderFeedbackAndCopyButtonsWrapper() {
        return (0, render_feedback_and_copy_buttons_cjs_namespaceObject.renderFeedbackAndCopyButtons)({
            props: {
                i18n: this.bindings.i18n,
                generatedAnswerActionsState: {
                    liked: this.generatedAnswerState.liked,
                    disliked: this.generatedAnswerState.disliked,
                    isStreaming: this.generatedAnswerState.isStreaming,
                    isLoading: this.generatedAnswerState.isLoading,
                    answer: this.generatedAnswerState.answer
                },
                copied: this.copied,
                copyError: this.copyError,
                getCopyToClipboardTooltip: ()=>this.copyToClipboardTooltip,
                onClickLike: ()=>this.clickLike(),
                onClickDislike: ()=>this.clickDislike(),
                onCopyToClipboard: (answer)=>this.copyToClipboard(answer)
            }
        });
    }
    renderContent() {
        const generatedAnswer = {
            ...this.generatedAnswerState
        };
        return (0, render_answer_content_cjs_namespaceObject.renderAnswerContent)({
            props: {
                i18n: this.bindings.i18n,
                generatedAnswer: generatedAnswer,
                collapsible: this.collapsible && (this.fullAnswerHeight ?? 0) > this.validateMaxCollapsedHeight(),
                renderFeedbackAndCopyButtonsSlot: ()=>this.renderFeedbackAndCopyButtonsWrapper(),
                renderCitationsSlot: ()=>(0, external_lit_namespaceObject.html)`${this.renderCitationsList()}`,
                onRetry: ()=>this.generatedAnswer?.retry(),
                onClickShowButton: ()=>this.clickOnShowButton()
            }
        });
    }
    renderCardHeaderWrapper() {
        return (0, render_card_header_cjs_namespaceObject.renderCardHeader)({
            props: {
                i18n: this.bindings.i18n,
                isAnswerVisible: this.isAnswerVisible,
                toggleTooltip: this.toggleTooltip,
                withToggle: this.withToggle,
                onToggle: (checked)=>{
                    checked ? this.generatedAnswer?.show() : this.generatedAnswer?.hide();
                }
            }
        });
    }
    constructor(){
        super(), this.DEFAULT_COLLAPSED_HEIGHT = 16, this.MAX_COLLAPSED_HEIGHT = 32, this.MIN_COLLAPSED_HEIGHT = 9, this.REQUIRED_FIELDS_TO_INCLUDE_IN_CITATIONS = [
            'filetype'
        ], this.withToggle = false, this.collapsible = false, this.maxCollapsedHeight = this.DEFAULT_COLLAPSED_HEIGHT, this.disableCitationAnchoring = false, this.copied = false, this.copyError = false, this.ariaMessage = new accessibility_utils_cjs_namespaceObject.AriaLiveRegionController(this, 'generated-answer'), this.onGeneratedAnswerStateUpdate = ()=>{
            if (this.generatedAnswerState.isVisible !== this.controller.data.isVisible) {
                this.controller.data = {
                    ...this.controller.data,
                    isVisible: this.generatedAnswerState.isVisible
                };
                this.controller.writeStoredData(this.controller.data);
            }
            this.ariaMessage.message = this.controller.getGeneratedAnswerStatus();
        };
        new validate_props_controller_cjs_namespaceObject.ValidatePropsController(this, ()=>({
                maxCollapsedHeight: this.maxCollapsedHeight
            }), AtomicInsightGeneratedAnswer.propsSchema, false);
    }
}
AtomicInsightGeneratedAnswer.styles = [
    external_atomic_insight_generated_answer_tw_css_cjs_default()
];
AtomicInsightGeneratedAnswer.propsSchema = new bueno_namespaceObject.Schema({
    maxCollapsedHeight: new bueno_namespaceObject.NumberValue({
        min: 9,
        max: 32,
        required: false
    })
});
AtomicInsightGeneratedAnswer.fieldsToIncludeInCitationsConverter = (0, legacy_array_string_converter_cjs_namespaceObject.createLegacyArrayStringConverter)((value)=>{
    console.warn(`Starting from Atomic v4, the "fields-to-include-in-citations" property will only accept an array of strings. Using a comma-separated string value ("${value}") is now deprecated. Please update the value to be a JSON array. For example: fields-to-include-in-citations='["fieldA","fieldB"]'`);
});
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'with-toggle',
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "withToggle", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "collapsible", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        attribute: 'max-collapsed-height'
    })
], AtomicInsightGeneratedAnswer.prototype, "maxCollapsedHeight", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'answer-configuration-id'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightGeneratedAnswer.prototype, "answerConfigurationId", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'fields-to-include-in-citations',
        converter: AtomicInsightGeneratedAnswer.fieldsToIncludeInCitationsConverter
    }),
    _ts_metadata("design:type", String)
], AtomicInsightGeneratedAnswer.prototype, "fieldsToIncludeInCitations", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'disable-citation-anchoring',
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "disableCitationAnchoring", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightGeneratedAnswer.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightGeneratedAnswer.prototype, "error", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('generatedAnswer', {
        onUpdateCallbackMethod: 'onGeneratedAnswerStateUpdate'
    }),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof InsightGeneratedAnswerState ? Object : InsightGeneratedAnswerState)
], AtomicInsightGeneratedAnswer.prototype, "generatedAnswerState", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('searchStatus'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof InsightSearchStatusState ? Object : InsightSearchStatusState)
], AtomicInsightGeneratedAnswer.prototype, "searchStatusState", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicInsightGeneratedAnswer.prototype, "copied", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicInsightGeneratedAnswer.prototype, "copyError", void 0);
_ts_decorate([
    (0, binding_guard_cjs_namespaceObject.bindingGuard)(),
    (0, error_guard_cjs_namespaceObject.errorGuard)(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightGeneratedAnswer.prototype, "render", null);
AtomicInsightGeneratedAnswer = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-insight-generated-answer'),
    (0, bindings_cjs_namespaceObject.bindings)(),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightGeneratedAnswer);
exports.AtomicInsightGeneratedAnswer = __webpack_exports__.AtomicInsightGeneratedAnswer;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicInsightGeneratedAnswer"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
