import dompurify from "dompurify";
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import { createRef, ref } from "lit/directives/ref.js";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { when } from "lit/directives/when.js";
import { bindAnalyticsToLink } from "../item-link/bind-analytics-to-link.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { sanitizeStyle } from "../../../utils/utils.js";
import atomic_smart_snippet_answer_tw_css from "./atomic-smart-snippet-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 AtomicSmartSnippetAnswer extends LitElement {
    disconnectedCallback() {
        super.disconnectedCallback();
        this.resizeObserver?.disconnect();
        this.cleanupAnalyticsFunctions.forEach((cleanup)=>cleanup());
        this.cleanupAnalyticsFunctions = [];
    }
    willUpdate() {
        this.isRendering = true;
    }
    updated() {
        this.isRendering = false;
        this.emitCurrentHeight();
        this.bindAnalyticsToLinks();
    }
    firstUpdated() {
        requestAnimationFrame(()=>{
            this.classList.add('loaded');
        });
        this.setupResizeObserver();
    }
    render() {
        return html`${this.renderStyle()} ${this.renderContent()}`;
    }
    setupResizeObserver() {
        if (this.wrapperRef.value) {
            if (this.resizeObserver) this.resizeObserver.disconnect();
            this.resizeObserver = new ResizeObserver(()=>this.emitCurrentHeight());
            this.resizeObserver.observe(this.wrapperRef.value);
        }
    }
    get sanitizedStyle() {
        if (!this.innerStyle) return;
        return sanitizeStyle(this.innerStyle);
    }
    emitCurrentHeight() {
        if (this.isRendering || !this.wrapperRef.value) return;
        this.dispatchEvent(new CustomEvent('answerSizeUpdated', {
            detail: {
                height: this.wrapperRef.value.scrollHeight
            },
            bubbles: false
        }));
    }
    bindAnalyticsToLink(element) {
        const link = {
            linkText: element.innerText,
            linkURL: element.href
        };
        const cleanup = bindAnalyticsToLink(element, {
            stopPropagation: false,
            onSelect: ()=>this.dispatchEvent(new CustomEvent('selectInlineLink', {
                    detail: link,
                    bubbles: false
                })),
            onBeginDelayedSelect: ()=>this.dispatchEvent(new CustomEvent('beginDelayedSelectInlineLink', {
                    detail: link,
                    bubbles: false
                })),
            onCancelPendingSelect: ()=>this.dispatchEvent(new CustomEvent('cancelPendingSelectInlineLink', {
                    detail: link,
                    bubbles: false
                }))
        });
        this.cleanupAnalyticsFunctions.push(cleanup);
    }
    bindAnalyticsToLinks() {
        if (!this.contentRef.value) return;
        this.cleanupAnalyticsFunctions.forEach((cleanup)=>cleanup());
        this.cleanupAnalyticsFunctions = [];
        Array.from(this.contentRef.value.querySelectorAll('a')).forEach((link)=>this.bindAnalyticsToLink(link));
    }
    renderStyle() {
        const style = this.sanitizedStyle;
        return when(style, ()=>html`<style>
          ${unsafeHTML(style)}
        </style>`);
    }
    renderContent() {
        return html`
      <div class="wrapper" ${ref(this.wrapperRef)}>
        <div part="answer" class="margin" ${ref(this.contentRef)}>
          ${unsafeHTML(dompurify.sanitize(this.htmlContent, {
            USE_PROFILES: {
                html: true
            }
        }))}
        </div>
      </div>
    `;
    }
    constructor(...args){
        super(...args), this.wrapperRef = createRef(), this.contentRef = createRef(), this.isRendering = true, this.cleanupAnalyticsFunctions = [];
    }
}
AtomicSmartSnippetAnswer.styles = atomic_smart_snippet_answer_tw_css;
_ts_decorate([
    property({
        type: String,
        attribute: 'html-content'
    }),
    _ts_metadata("design:type", String)
], AtomicSmartSnippetAnswer.prototype, "htmlContent", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'inner-style'
    }),
    _ts_metadata("design:type", String)
], AtomicSmartSnippetAnswer.prototype, "innerStyle", void 0);
AtomicSmartSnippetAnswer = _ts_decorate([
    customElement('atomic-smart-snippet-answer'),
    withTailwindStyles
], AtomicSmartSnippetAnswer);
export { AtomicSmartSnippetAnswer };
