import { buildSmartSnippet } from "@coveo/headless/insight";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { getAttributesFromLinkSlotContent } from "../../common/item-link/attributes-slot.js";
import { renderSnippetFooter } from "../../common/smart-snippets/atomic-smart-snippet/snippet-footer.js";
import { renderSnippetQuestion } from "../../common/smart-snippets/atomic-smart-snippet/snippet-question.js";
import { renderSnippetWrapper } from "../../common/smart-snippets/atomic-smart-snippet/snippet-wrapper.js";
import { renderSmartSnippetFeedbackBanner } from "../../common/smart-snippets/smart-snippet-feedback-banner.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 { randomID } from "../../../utils/utils.js";
import "../../common/atomic-smart-snippet-collapse-wrapper/atomic-smart-snippet-collapse-wrapper.js";
import "../../common/atomic-smart-snippet-expandable-answer/atomic-smart-snippet-expandable-answer.js";
import "../../common/atomic-smart-snippet-source/atomic-smart-snippet-source.js";
import { when } from "lit/directives/when.js";
import "../atomic-insight-smart-snippet-feedback-modal/atomic-insight-smart-snippet-feedback-modal.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import atomic_insight_smart_snippet_tw_css from "./atomic-insight-smart-snippet.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 AtomicInsightSmartSnippet extends LitElement {
    initialize() {
        this.smartSnippetId ||= randomID();
        this.smartSnippet = buildSmartSnippet(this.bindings.engine);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this.modalRef) this.modalRef.removeEventListener('feedbackSent', this.feedbackSentHandler);
    }
    willUpdate() {
        if (!this.smartSnippetState) return;
        if (!(this.smartSnippetState.liked || this.smartSnippetState.disliked)) this.feedbackSent = false;
    }
    loadModal() {
        if (this.modalRef) return;
        const modalRef = document.createElement('atomic-insight-smart-snippet-feedback-modal');
        modalRef.addEventListener('feedbackSent', this.feedbackSentHandler);
        this.modalRef = modalRef;
        this.renderRoot.parentElement?.insertAdjacentElement('beforebegin', modalRef);
    }
    renderSource() {
        const source = this.smartSnippetState.source;
        if (!source) return nothing;
        return html`<atomic-smart-snippet-source
      .anchorAttributes=${getAttributesFromLinkSlotContent(this, 'source-anchor-attributes')}
      .onBeginDelayedSelectSource=${this.smartSnippet.beginDelayedSelectSource}
      .onCancelPendingSelectSource=${this.smartSnippet.cancelPendingSelectSource}
      .onSelectSource=${this.smartSnippet.selectSource}
      .source=${source}
    ></atomic-smart-snippet-source>`;
    }
    renderFeedbackBanner() {
        const explainWhyRef = (button)=>{
            if (this.modalRef && button) this.modalRef.source = button;
        };
        return renderSmartSnippetFeedbackBanner({
            props: {
                disliked: this.smartSnippetState.disliked,
                explainWhyRef,
                feedbackSent: this.feedbackSent,
                id: this.smartSnippetId,
                i18n: this.bindings.i18n,
                liked: this.smartSnippetState.liked,
                onDislike: ()=>{
                    this.loadModal();
                    this.smartSnippet.dislike();
                },
                onLike: ()=>this.smartSnippet.like(),
                onPressExplainWhy: ()=>{
                    if (this.modalRef) this.modalRef.isOpen = true;
                }
            }
        });
    }
    render() {
        const shouldDisplay = this.smartSnippetState?.answerFound ?? false;
        this.classList.toggle('atomic-hidden', !shouldDisplay);
        return html` ${when(shouldDisplay, ()=>renderSnippetWrapper({
                props: {
                    headingLevel: this.headingLevel,
                    i18n: this.bindings.i18n
                }
            })(html`
        <atomic-smart-snippet-collapse-wrapper>
          ${renderSnippetQuestion({
                props: {
                    headingLevel: this.headingLevel,
                    question: this.smartSnippetState.question
                }
            })}
          <atomic-smart-snippet-expandable-answer
            .collapsedHeight=${this.collapsedHeight}
            .expanded=${this.smartSnippetState.expanded}
            exportparts="answer,show-more-button,show-less-button,truncated-answer"
            .htmlContent=${this.smartSnippetState.answer}
            .maximumHeight=${this.maximumHeight}
            @collapse=${()=>this.smartSnippet.collapse()}
            @expand=${()=>this.smartSnippet.expand()}
            part="body"
            .snippetStyle=${this.snippetStyle}
          ></atomic-smart-snippet-expandable-answer>
          ${renderSnippetFooter({
                props: {
                    i18n: this.bindings.i18n
                }
            })(html` ${this.renderSource()} ${this.renderFeedbackBanner()} `)}
        </atomic-smart-snippet-collapse-wrapper>
      `))}`;
    }
    constructor(...args){
        super(...args), this.feedbackSent = false, this.feedbackSentHandler = ()=>{
            this.feedbackSent = true;
        }, this.headingLevel = 0, this.maximumHeight = 250, this.collapsedHeight = 180;
    }
}
AtomicInsightSmartSnippet.styles = atomic_insight_smart_snippet_tw_css;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightSmartSnippet.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightSmartSnippet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('smartSnippet'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightSmartSnippetState ? Object : InsightSmartSnippetState)
], AtomicInsightSmartSnippet.prototype, "smartSnippetState", void 0);
_ts_decorate([
    state()
], AtomicInsightSmartSnippet.prototype, "feedbackSent", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'heading-level'
    })
], AtomicInsightSmartSnippet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'maximum-height'
    })
], AtomicInsightSmartSnippet.prototype, "maximumHeight", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'collapsed-height'
    })
], AtomicInsightSmartSnippet.prototype, "collapsedHeight", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'snippet-style'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightSmartSnippet.prototype, "snippetStyle", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightSmartSnippet.prototype, "render", null);
AtomicInsightSmartSnippet = _ts_decorate([
    customElement('atomic-insight-smart-snippet'),
    bindings(),
    withTailwindStyles
], AtomicInsightSmartSnippet);
export { AtomicInsightSmartSnippet };
