import "../../common/atomic-modal/atomic-modal.js";
import { buildInteractiveResult } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { ATOMIC_MODAL_EXPORT_PARTS } from "../../common/atomic-modal/export-parts.js";
import { renderButton } from "../../common/button.js";
import { renderIconButton } from "../../common/icon-button.js";
import { renderLinkWithItemAnalytics } from "../../common/item-link/item-link.js";
import { renderQuickviewSidebar } from "../result-template-components/atomic-quickview-sidebar/atomic-quickview-sidebar.js";
import { renderQuickviewIframe } from "../result-template-components/quickview-iframe/quickview-iframe.js";
import { buildQuickviewPreviewBar } from "../result-template-components/quickview-preview-bar/quickview-preview-bar.js";
import { HIGHLIGHT_PREFIX, getWordsHighlights } from "../result-template-components/quickview-word-highlight/quickview-word-highlight.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 { buildCustomEvent } from "../../../utils/event-utils.js";
import images_close from "../../../images/close.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 AtomicQuickviewModal extends LitElement {
    initialize() {
        this.minimizeSidebar = this.bindings.store.isMobile();
    }
    async reset() {
        this.highlightKeywords = {
            highlightNone: false,
            keywords: {}
        };
        this.minimizeSidebar = false;
        this.iframeRef = void 0;
        this.content = void 0;
        this.result = void 0;
        this.interactiveResult = void 0;
        this.highlightStyleSheets.clear();
    }
    willUpdate(changedProperties) {
        if (changedProperties.has('highlightKeywords')) this.handleHighlightsScripts();
    }
    renderHeader() {
        if (!this.result) return html`<div slot="header"></div>`;
        this.interactiveResult = buildInteractiveResult(this.bindings.engine, {
            options: {
                result: this.result
            }
        });
        return html`
      <div slot="header" class="flex w-full items-center justify-between">
        ${renderLinkWithItemAnalytics({
            props: {
                href: this.result.clickUri,
                onSelect: ()=>this.interactiveResult?.select(),
                onBeginDelayedSelect: ()=>this.interactiveResult?.beginDelayedSelect(),
                onCancelPendingSelect: ()=>this.interactiveResult?.cancelPendingSelect(),
                className: 'truncate',
                part: 'quickview-modal-header-title'
            }
        })(html`${this.result.title}`)}
        ${renderIconButton({
            props: {
                partPrefix: 'quickview-modal-header',
                icon: images_close,
                onClick: ()=>this.onClose(),
                ariaLabel: this.bindings.i18n.t('close'),
                style: 'text-transparent',
                title: this.bindings.i18n.t('close')
            }
        })}
      </div>
    `;
    }
    renderBody() {
        return html`
      <div slot="body" class="grid h-full grid-cols-[min-content_auto]">
        <div
          class="h-full overflow-y-auto"
          style="background-color: var(--atomic-neutral-light)"
        >
          ${renderQuickviewSidebar({
            props: {
                words: this.words,
                i18n: this.bindings.i18n,
                highlightKeywords: this.highlightKeywords,
                onHighlightKeywords: (highlight)=>{
                    this.highlightKeywords = highlight;
                },
                minimized: this.minimizeSidebar,
                onMinimize: (minimize)=>{
                    this.minimizeSidebar = minimize;
                }
            }
        })}
        </div>
        <div class="relative overflow-auto">
          ${renderQuickviewIframe({
            props: {
                title: this.result?.title ?? this.bindings.i18n.t('preview-modal-title'),
                logger: this.logger,
                src: this.quickviewSrc,
                sandbox: this.sandbox,
                uniqueIdentifier: this.quickviewUniqueIdentifier,
                content: this.content,
                onSetIframeRef: async (ref)=>{
                    this.iframeRef = ref;
                    this.words = getWordsHighlights(this.termsToHighlight, this.iframeRef);
                    this.handleHighlightsScripts();
                }
            }
        })}
          ${buildQuickviewPreviewBar(this.words, this.highlightKeywords, this.iframeRef)}
        </div>
      </div>
    `;
    }
    renderFooter() {
        return html`
      <div slot="footer" class="flex items-center gap-2">
        ${renderButton({
            props: {
                class: 'p-2',
                style: 'square-neutral',
                onClick: ()=>{
                    this.dispatchEvent(buildCustomEvent('atomic/quickview/previous'));
                },
                disabled: 1 === this.current,
                text: this.bindings.i18n.t('quickview-previous')
            }
        })(nothing)}
        <p class="text-center text-on-background">
          ${this.bindings.i18n.t('showing-results-of', {
            first: this.current,
            total: this.total
        })}
        </p>
        ${renderButton({
            props: {
                class: 'p-2',
                style: 'square-neutral',
                onClick: ()=>{
                    this.dispatchEvent(buildCustomEvent('atomic/quickview/next'));
                },
                disabled: this.current === this.total,
                text: this.bindings.i18n.t('quickview-next')
            }
        })(nothing)}
      </div>
    `;
    }
    onClose() {
        this.content = void 0;
        this.result = void 0;
        this.modalCloseCallback?.();
    }
    get isOpen() {
        return !!this.content && !!this.result;
    }
    get logger() {
        return this.bindings.engine.logger;
    }
    get quickviewSrc() {
        return this.bindings.engine.state.resultPreview?.contentURL;
    }
    enableHighlights() {
        this.removeDisableHighlightStyleSheet();
    }
    enableHighlightsSpecificKeyword(identifier) {
        this.removeDisableHighlightStyleSheet(identifier);
    }
    disableHighlights() {
        this.createDisableHighlightStyleSheet();
    }
    disableHighlightsSpecificKeyword(identifier) {
        this.createDisableHighlightStyleSheet(identifier);
    }
    removeDisableHighlightStyleSheet(identifier) {
        const doc = this.iframeRef?.contentWindow?.document;
        if (!doc) return;
        const key = identifier ?? '';
        const sheet = this.highlightStyleSheets.get(key);
        if (!sheet) return;
        doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter((s)=>s !== sheet);
        this.highlightStyleSheets.delete(key);
    }
    createDisableHighlightStyleSheet(identifier) {
        const doc = this.iframeRef?.contentWindow?.document;
        if (!doc) return;
        const key = identifier ?? '';
        if (this.highlightStyleSheets.has(key)) return;
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(`[id^="${HIGHLIGHT_PREFIX}${identifier ? `:${identifier}` : ''}"] {
        background-color: inherit !important;
        color: inherit !important;
      }`);
        this.highlightStyleSheets.set(key, sheet);
        doc.adoptedStyleSheets = [
            ...doc.adoptedStyleSheets,
            sheet
        ];
    }
    get termsToHighlight() {
        const flatPhrasesToHighlight = {};
        const phrasesToHighlight = this.bindings.engine.state.search.response.phrasesToHighlight;
        Object.entries(phrasesToHighlight).forEach(([phrase, keywords])=>{
            flatPhrasesToHighlight[phrase] = Object.entries(keywords).flatMap(([keywordEntry, keywordStemming])=>[
                    keywordEntry,
                    ...keywordStemming
                ]);
        });
        return {
            ...this.bindings.engine.state.search.response.termsToHighlight,
            ...flatPhrasesToHighlight
        };
    }
    get requestId() {
        return this.bindings.engine.state.search.requestId;
    }
    get quickviewUniqueIdentifier() {
        if (!this.result?.uniqueId) return this.requestId;
        return this.result.uniqueId + this.requestId;
    }
    handleHighlightsScripts() {
        if (this.highlightKeywords.highlightNone) this.disableHighlights();
        else this.enableHighlights();
        Object.values(this.highlightKeywords.keywords).forEach((word)=>{
            if (word.enabled) this.enableHighlightsSpecificKeyword(word.indexIdentifier);
            else this.disableHighlightsSpecificKeyword(word.indexIdentifier);
        });
    }
    render() {
        return html`
      <atomic-modal
        .fullscreen=${this.bindings.store.isMobile()}
        class="atomic-quickview-modal"
        .isOpen=${this.isOpen}
        .close=${()=>this.onClose()}
        exportparts=${ATOMIC_MODAL_EXPORT_PARTS}
      >
        ${this.renderHeader()} ${this.renderBody()} ${this.renderFooter()}
      </atomic-modal>
    `;
    }
    constructor(...args){
        super(...args), this.highlightKeywords = {
            highlightNone: false,
            keywords: {}
        }, this.minimizeSidebar = false, this.words = {}, this.highlightStyleSheets = new Map();
    }
}
AtomicQuickviewModal.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */.atomic-quickview-modal::part(backdrop){grid-template-columns:1fr max(80vw,30rem) 1fr}.atomic-quickview-modal::part(body),.atomic-quickview-modal::part(footer),.atomic-quickview-modal::part(header){max-width:100%}.atomic-quickview-modal::part(footer){display:flex;justify-content:center}.atomic-quickview-modal::part(body-wrapper){height:100%;overflow:hidden;padding:calc(var(--spacing,.25rem)*0)}.atomic-quickview-modal::part(body){height:100%}.atomic-quickview-modal::part(backdrop){grid-template-rows:1fr 100% 3fr}.atomic-quickview-modal::part(header-wrapper){background-color:var(--atomic-neutral-light)}.atomic-quickview-modal a{color:var(--atomic-on-background)}.atomic-quickview-modal a:focus-visible,.atomic-quickview-modal a:hover{color:var(--atomic-primary);text-decoration:underline}.atomic-quickview-modal a:focus{outline:none}.atomic-quickview-modal a:visited{color:var(--atomic-visited)}`;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicQuickviewModal.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicQuickviewModal.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof HighlightKeywords ? Object : HighlightKeywords)
], AtomicQuickviewModal.prototype, "highlightKeywords", void 0);
_ts_decorate([
    state()
], AtomicQuickviewModal.prototype, "minimizeSidebar", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicQuickviewModal.prototype, "words", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: false
    }),
    _ts_metadata("design:type", String)
], AtomicQuickviewModal.prototype, "content", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof Result ? Object : Result)
], AtomicQuickviewModal.prototype, "result", void 0);
_ts_decorate([
    property({
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicQuickviewModal.prototype, "current", void 0);
_ts_decorate([
    property({
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicQuickviewModal.prototype, "total", void 0);
_ts_decorate([
    property({
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicQuickviewModal.prototype, "sandbox", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", Function)
], AtomicQuickviewModal.prototype, "modalCloseCallback", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicQuickviewModal.prototype, "render", null);
AtomicQuickviewModal = _ts_decorate([
    customElement('atomic-quickview-modal'),
    bindings(),
    withTailwindStyles
], AtomicQuickviewModal);
export { AtomicQuickviewModal };
