import { buildSmartSnippet, buildTabManager } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import "../../common/atomic-icon/atomic-icon.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 { 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 { renderSnippetTruncatedAnswer } from "../../common/smart-snippets/atomic-smart-snippet/snippet-truncated-answer.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 { arrayConverter } from "../../../converters/array-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 { shouldDisplayOnCurrentTab } from "../../../utils/tab-utils.js";
import { randomID } from "../../../utils/utils.js";
import atomic_smart_snippet_tw_css from "./atomic-smart-snippet.tw.css.js";
import "../../common/atomic-smart-snippet-source/atomic-smart-snippet-source.js";
import "../atomic-smart-snippet-feedback-modal/atomic-smart-snippet-feedback-modal.js";
function _check_private_redeclaration(obj, privateCollection) {
    if (privateCollection.has(obj)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}
function _class_apply_descriptor_get(receiver, descriptor) {
    if (descriptor.get) return descriptor.get.call(receiver);
    return descriptor.value;
}
function _class_apply_descriptor_set(receiver, descriptor, value) {
    if (descriptor.set) descriptor.set.call(receiver, value);
    else {
        if (!descriptor.writable) throw new TypeError("attempted to set read only private field");
        descriptor.value = value;
    }
}
function _class_extract_field_descriptor(receiver, privateMap, action) {
    if (!privateMap.has(receiver)) throw new TypeError("attempted to " + action + " private field on non-instance");
    return privateMap.get(receiver);
}
function _class_private_field_get(receiver, privateMap) {
    var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
    return _class_apply_descriptor_get(receiver, descriptor);
}
function _class_private_field_init(obj, privateMap, value) {
    _check_private_redeclaration(obj, privateMap);
    privateMap.set(obj, value);
}
function _class_private_field_set(receiver, privateMap, value) {
    var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
    _class_apply_descriptor_set(receiver, descriptor, value);
    return value;
}
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);
}
var _id = /*#__PURE__*/ new WeakMap();
class AtomicSmartSnippet extends LitElement {
    connectedCallback() {
        super.connectedCallback();
        _class_private_field_set(this, _id, _class_private_field_get(this, _id) || randomID());
        this.addEventListener('selectInlineLink', this.onSelectInlineLink);
        this.addEventListener('beginDelayedSelectInlineLink', this.onBeginDelayedSelectInlineLink);
        this.addEventListener('cancelPendingSelectInlineLink', this.onCancelPendingSelectInlineLink);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('selectInlineLink', this.onSelectInlineLink);
        this.removeEventListener('beginDelayedSelectInlineLink', this.onBeginDelayedSelectInlineLink);
        this.removeEventListener('cancelPendingSelectInlineLink', this.onCancelPendingSelectInlineLink);
    }
    initialize() {
        this.smartSnippet = buildSmartSnippet(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
    }
    willUpdate() {
        if (this.smartSnippetState && !(this.smartSnippetState.liked || this.smartSnippetState.disliked)) this.setFeedbackSent(false);
    }
    onSelectInlineLink(event) {
        this.smartSnippet.selectInlineLink(event.detail);
    }
    onBeginDelayedSelectInlineLink(event) {
        this.smartSnippet.beginDelayedSelectInlineLink(event.detail);
    }
    onCancelPendingSelectInlineLink(event) {
        this.smartSnippet.cancelPendingSelectInlineLink(event.detail);
    }
    setModalRef(ref) {
        this.modalRef = ref;
    }
    setFeedbackSent(isSent) {
        this.feedbackSent = isSent;
    }
    get computedStyle() {
        const styleTag = this.querySelector('template')?.content.querySelector('style');
        if (!styleTag) return this.snippetStyle;
        return styleTag.innerHTML;
    }
    loadModal() {
        if (this.modalRef) return;
        const modalRef = document.createElement('atomic-smart-snippet-feedback-modal');
        modalRef.addEventListener('feedbackSent', ()=>{
            this.setFeedbackSent(true);
        });
        this.setModalRef(modalRef);
        this.insertAdjacentElement('beforebegin', modalRef);
    }
    render() {
        const shouldDisplay = shouldDisplayOnCurrentTab(this.tabsIncluded, this.tabsExcluded, this.tabManagerState?.activeTab) && this.smartSnippetState.answerFound;
        this.classList.toggle('atomic-hidden', !shouldDisplay);
        return html`${when(shouldDisplay, ()=>this.renderContent())}`;
    }
    renderContent() {
        const source = this.smartSnippetState.source;
        return renderSnippetWrapper({
            props: {
                headingLevel: this.headingLevel,
                i18n: this.bindings.i18n
            }
        })(html`
      <atomic-smart-snippet-collapse-wrapper
        .collapsedHeight=${this.snippetCollapsedHeight}
        .maximumHeight=${this.snippetMaximumHeight}
      >
        ${renderSnippetQuestion({
            props: {
                headingLevel: this.headingLevel,
                question: this.smartSnippetState.question
            }
        })}
        ${when(void 0 !== this.snippetMaximumHeight, ()=>renderSnippetTruncatedAnswer({
                props: {
                    answer: this.smartSnippetState.answer,
                    style: this.computedStyle
                }
            }), ()=>html`
            <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.computedStyle}
            ></atomic-smart-snippet-expandable-answer>
          `)}
        ${renderSnippetFooter({
            props: {
                i18n: this.bindings.i18n
            }
        })(html`
          ${when(source, ()=>html`
              <atomic-smart-snippet-source
                .source=${source}
                .anchorAttributes=${getAttributesFromLinkSlotContent(this, 'source-anchor-attributes')}
                @selectSource=${this.smartSnippet.selectSource}
                @beginDelayedSelectSource=${this.smartSnippet.beginDelayedSelectSource}
                @cancelPendingSelectSource=${this.smartSnippet.cancelPendingSelectSource}
              ></atomic-smart-snippet-source>
            `)}
          ${renderSmartSnippetFeedbackBanner({
            props: {
                disliked: this.smartSnippetState.disliked,
                explainWhyRef: (button)=>{
                    if (this.modalRef && button) this.modalRef.source = button;
                },
                feedbackSent: this.feedbackSent,
                id: _class_private_field_get(this, _id),
                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;
                }
            }
        })}
        `)}
      </atomic-smart-snippet-collapse-wrapper>
    `);
    }
    constructor(...args){
        super(...args), _class_private_field_init(this, _id, {
            writable: true,
            value: void 0
        }), this.feedbackSent = false, this.headingLevel = 0, this.maximumHeight = 250, this.collapsedHeight = 180, this.tabsIncluded = [], this.tabsExcluded = [];
    }
}
AtomicSmartSnippet.styles = atomic_smart_snippet_tw_css;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSmartSnippet.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSmartSnippet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('smartSnippet'),
    state(),
    _ts_metadata("design:type", "u" < typeof SmartSnippetState ? Object : SmartSnippetState)
], AtomicSmartSnippet.prototype, "smartSnippetState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicSmartSnippet.prototype, "tabManagerState", void 0);
_ts_decorate([
    state()
], AtomicSmartSnippet.prototype, "feedbackSent", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'heading-level'
    })
], AtomicSmartSnippet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'maximum-height'
    })
], AtomicSmartSnippet.prototype, "maximumHeight", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'collapsed-height'
    })
], AtomicSmartSnippet.prototype, "collapsedHeight", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'snippet-style'
    }),
    _ts_metadata("design:type", String)
], AtomicSmartSnippet.prototype, "snippetStyle", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-included',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicSmartSnippet.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-excluded',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicSmartSnippet.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'snippet-maximum-height'
    }),
    _ts_metadata("design:type", Number)
], AtomicSmartSnippet.prototype, "snippetMaximumHeight", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'snippet-collapsed-height'
    }),
    _ts_metadata("design:type", Number)
], AtomicSmartSnippet.prototype, "snippetCollapsedHeight", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSmartSnippet.prototype, "render", null);
AtomicSmartSnippet = _ts_decorate([
    customElement('atomic-smart-snippet'),
    bindings(),
    withTailwindStyles
], AtomicSmartSnippet);
export { AtomicSmartSnippet };
