import { NumberValue, Schema } from "@coveo/bueno";
import { buildGeneratedAnswer, buildInteractiveCitation, buildSearchStatus } from "@coveo/headless/insight";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { GeneratedAnswerController } from "../../common/generated-answer/generated-answer-controller.js";
import { renderAnswerContent } from "../../common/generated-answer/render-answer-content.js";
import { renderCardHeader } from "../../common/generated-answer/render-card-header.js";
import { renderCitations } from "../../common/generated-answer/render-citations.js";
import { renderCustomNoAnswerMessage } from "../../common/generated-answer/render-custom-no-answer-message.js";
import { renderDisclaimer } from "../../common/generated-answer/render-disclaimer.js";
import { renderFeedbackAndCopyButtons } from "../../common/generated-answer/render-feedback-and-copy-buttons.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { createLegacyArrayStringConverter } from "../../../converters/legacy-array-string-converter.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { AriaLiveRegionController } from "../../../utils/accessibility-utils.js";
import { debounce } from "../../../utils/debounce-utils.js";
import { getNamedSlotContent } from "../../../utils/slot-utils.js";
import atomic_insight_generated_answer_tw_css from "./atomic-insight-generated-answer.tw.css.js";
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 LitElement {
    initialize() {
        this.controller = new GeneratedAnswerController(this, {
            withToggle: this.withToggle,
            getGeneratedAnswer: ()=>this.generatedAnswer,
            getGeneratedAnswerState: ()=>this.generatedAnswerState,
            getSearchStatusState: ()=>this.searchStatusState,
            getBindings: ()=>this.bindings
        });
        this.generatedAnswer = 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 = buildSearchStatus(this.bindings.engine);
        this.controller.insertFeedbackModal();
        if (window.ResizeObserver && this.collapsible) {
            const debouncedAdaptAnswerHeight = 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 html`
          <div>
            <aside
              class=${contentClasses}
              part="container"
              aria-label=${this.bindings.i18n.t('generated-answer-title')}
            >
              <div part="generated-content">
                ${this.renderCardHeaderWrapper()}
                ${when(this.isAnswerVisible, ()=>html`<article>${renderCustomNoAnswerMessage()}</article>`)}
              </div>
            </aside>
          </div>
        `;
            return nothing;
        }
        return html`
      <div>
        <aside
          class=${contentClasses}
          part="container"
          aria-label=${this.bindings.i18n.t('generated-answer-title')}
        >
          <div part="generated-content">
            ${this.renderCardHeaderWrapper()}
            ${when(this.isAnswerVisible, ()=>html` <div part="generated-content-container" class="px-6 pb-6">
                  <article>${this.renderContent()}</article>
                  ${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 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 renderCitations({
            props: {
                citations,
                i18n: this.bindings.i18n,
                buildInteractiveCitation: (citation)=>buildInteractiveCitation(this.bindings.engine, {
                        options: {
                            citation
                        }
                    }),
                logCitationHover: (citationId, citationHoverTimeMs)=>{
                    this.generatedAnswer?.logCitationHover(citationId, citationHoverTimeMs);
                },
                disableCitationAnchoring: this.disableCitationAnchoring
            }
        });
    }
    renderFeedbackAndCopyButtonsWrapper() {
        return 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 renderAnswerContent({
            props: {
                i18n: this.bindings.i18n,
                generatedAnswer: generatedAnswer,
                collapsible: this.collapsible && (this.fullAnswerHeight ?? 0) > this.validateMaxCollapsedHeight(),
                renderFeedbackAndCopyButtonsSlot: ()=>this.renderFeedbackAndCopyButtonsWrapper(),
                renderCitationsSlot: ()=>html`${this.renderCitationsList()}`,
                onRetry: ()=>this.generatedAnswer?.retry(),
                onClickShowButton: ()=>this.clickOnShowButton()
            }
        });
    }
    renderCardHeaderWrapper() {
        return 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 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 ValidatePropsController(this, ()=>({
                maxCollapsedHeight: this.maxCollapsedHeight
            }), AtomicInsightGeneratedAnswer.propsSchema, false);
    }
}
AtomicInsightGeneratedAnswer.styles = [
    atomic_insight_generated_answer_tw_css
];
AtomicInsightGeneratedAnswer.propsSchema = new Schema({
    maxCollapsedHeight: new NumberValue({
        min: 9,
        max: 32,
        required: false
    })
});
AtomicInsightGeneratedAnswer.fieldsToIncludeInCitationsConverter = 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([
    property({
        type: Boolean,
        attribute: 'with-toggle',
        converter: booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "withToggle", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "collapsible", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'max-collapsed-height'
    })
], AtomicInsightGeneratedAnswer.prototype, "maxCollapsedHeight", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'answer-configuration-id'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightGeneratedAnswer.prototype, "answerConfigurationId", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'fields-to-include-in-citations',
        converter: AtomicInsightGeneratedAnswer.fieldsToIncludeInCitationsConverter
    }),
    _ts_metadata("design:type", String)
], AtomicInsightGeneratedAnswer.prototype, "fieldsToIncludeInCitations", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-citation-anchoring',
        converter: booleanConverter
    })
], AtomicInsightGeneratedAnswer.prototype, "disableCitationAnchoring", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightGeneratedAnswer.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightGeneratedAnswer.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('generatedAnswer', {
        onUpdateCallbackMethod: 'onGeneratedAnswerStateUpdate'
    }),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightGeneratedAnswerState ? Object : InsightGeneratedAnswerState)
], AtomicInsightGeneratedAnswer.prototype, "generatedAnswerState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightSearchStatusState ? Object : InsightSearchStatusState)
], AtomicInsightGeneratedAnswer.prototype, "searchStatusState", void 0);
_ts_decorate([
    state()
], AtomicInsightGeneratedAnswer.prototype, "copied", void 0);
_ts_decorate([
    state()
], AtomicInsightGeneratedAnswer.prototype, "copyError", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightGeneratedAnswer.prototype, "render", null);
AtomicInsightGeneratedAnswer = _ts_decorate([
    customElement('atomic-insight-generated-answer'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightGeneratedAnswer);
export { AtomicInsightGeneratedAnswer };
