import { Schema, StringValue } from "@coveo/bueno";
import { buildQuickview } from "@coveo/headless";
import { LitElement } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { createRef } from "lit/directives/ref.js";
import { when } from "lit/directives/when.js";
import { renderIconButton } from "../../common/icon-button.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import "../../search/atomic-quickview-modal/atomic-quickview-modal.js";
import { createResultContextController } from "../../search/result-template-component-utils/context/result-context-controller.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindings } from "../../../decorators/bindings.js";
import { LightDomMixin } from "../../../mixins/light-dom.js";
import { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import preview from "../../../images/preview.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 AtomicInsightResultQuickviewAction extends LightDomMixin(LitElement) {
    initialize() {
        const item = this.resultContext?.item;
        if (!item) return;
        this.result = 'result' in item ? item.result : item;
        this.buttonFocusTarget = new FocusTargetController(this, this.bindings);
        this.quickview = buildQuickview(this.bindings.engine, {
            options: {
                result: this.result
            }
        });
    }
    connectedCallback() {
        super.connectedCallback();
        document.body.addEventListener('atomic/quickview/next', this.nextQuickviewHandler);
        document.body.addEventListener('atomic/quickview/previous', this.previousQuickviewHandler);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        document.body.removeEventListener('atomic/quickview/next', this.nextQuickviewHandler);
        document.body.removeEventListener('atomic/quickview/previous', this.previousQuickviewHandler);
    }
    addQuickviewModalIfNeeded() {
        if (this.quickviewModalRef || !this.bindings?.interfaceElement) return;
        const quickviewModal = this.bindings.interfaceElement.querySelector('atomic-quickview-modal');
        if (quickviewModal) {
            this.quickviewModalRef = quickviewModal;
            return;
        }
        this.quickviewModalRef = document.createElement('atomic-quickview-modal');
        this.quickviewModalRef.setAttribute('sandbox', this.sandbox);
        this.bindings.interfaceElement.appendChild(this.quickviewModalRef);
    }
    updateModalContent() {
        if (this.quickviewModalRef && this.quickview.state.content) {
            this.quickviewModalRef.content = this.quickview.state.content;
            this.quickviewModalRef.result = this.result;
            this.quickviewModalRef.total = this.quickviewState.totalResults;
            this.quickviewModalRef.current = this.quickviewState.currentResult;
            this.quickviewModalRef.modalCloseCallback = ()=>this.buttonFocusTarget.focus();
            this.ariaLiveRegion.message = this.quickviewState.isLoading ? this.bindings.i18n.t('quickview-loading') : this.bindings.i18n.t('quickview-loaded', {
                first: this.quickviewState.currentResult,
                last: this.quickviewState.totalResults,
                title: this.result.title
            });
        }
    }
    onClick(event) {
        event?.stopPropagation();
        this.quickview.fetchResultContent();
    }
    get shouldRenderQuickview() {
        return this.quickviewState?.resultHasPreview;
    }
    updated() {
        this.addQuickviewModalIfNeeded();
        if (this.quickviewState) this.updateModalContent();
        if (this.buttonRef.value && this.buttonFocusTarget) this.buttonFocusTarget.setTarget(this.buttonRef.value);
    }
    render() {
        return when(this.shouldRenderQuickview, ()=>renderIconButton({
                props: {
                    partPrefix: 'result-action',
                    style: 'outline-neutral',
                    buttonRef: this.buttonRef,
                    icon: preview,
                    title: this.bindings.i18n.t('quickview'),
                    onClick: (event)=>this.onClick(event)
                }
            }));
    }
    constructor(){
        super(), this.sandbox = 'allow-popups allow-top-navigation allow-same-origin', this.resultContext = createResultContextController(this), this.ariaLiveRegion = new AriaLiveRegionController(this, 'quickview'), this.buttonRef = createRef(), this.nextQuickviewHandler = (evt)=>{
            evt.stopImmediatePropagation();
            this.quickview.next();
        }, this.previousQuickviewHandler = (evt)=>{
            evt.stopImmediatePropagation();
            this.quickview.previous();
        };
        new ValidatePropsController(this, ()=>({
                sandbox: this.sandbox
            }), AtomicInsightResultQuickviewAction.propsSchema);
    }
}
AtomicInsightResultQuickviewAction.propsSchema = new Schema({
    sandbox: new StringValue({
        required: true,
        regex: /allow-same-origin/
    })
});
_ts_decorate([
    property({
        type: String
    })
], AtomicInsightResultQuickviewAction.prototype, "sandbox", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicInsightResultQuickviewAction.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightResultQuickviewAction.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Result ? Object : Result)
], AtomicInsightResultQuickviewAction.prototype, "result", void 0);
_ts_decorate([
    bindStateToController('quickview'),
    state(),
    _ts_metadata("design:type", "u" < typeof QuickviewState ? Object : QuickviewState)
], AtomicInsightResultQuickviewAction.prototype, "quickviewState", void 0);
AtomicInsightResultQuickviewAction = _ts_decorate([
    customElement('atomic-insight-result-quickview-action'),
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightResultQuickviewAction);
export { AtomicInsightResultQuickviewAction };
