import { createPopper, preventOverflow } from "@popperjs/core";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { createRef, ref } from "lit/directives/ref.js";
import { watch } from "../../../decorators/watch.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { renderHeading } from "../heading.js";
import { renderLinkWithItemAnalytics } from "../item-link/item-link.js";
import atomic_citation_tw_css from "./atomic-citation.tw.css.js";
import { generatePdfPageUrl, generateTextFragmentUrl } from "./citation-anchoring-utils.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 AtomicCitation extends LitElement {
    disconnectedCallback() {
        super.disconnectedCallback();
        this.cleanupPopper();
        this.clearTimers();
        this.removeEventListener('keydown', this.handleKeyDown);
    }
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('keydown', this.handleKeyDown);
    }
    sendHoverAnalytics() {
        if (this.isOpen) {
            this.hoverStart = Date.now();
            return;
        }
        if (!this.hoverStart) return;
        const difference = Date.now() - this.hoverStart;
        if (difference > this.hoverAnalyticsTimeout) this.sendHoverEndEvent(difference);
        this.hoverStart = void 0;
    }
    updated() {
        this.updatePopper();
    }
    render() {
        return html`
      <div class="relative">
        ${renderLinkWithItemAnalytics({
            props: {
                href: this.anchorUrl(this.citation.clickUri ?? this.citation.uri, this.citation.text, this.citation.filetype ?? this.citation.fields?.filetype),
                ref: this.citationRef,
                part: 'citation',
                target: '_blank',
                rel: 'noopener',
                attributes: [
                    this.ariaHaspopupAttr
                ],
                className: 'bg-background btn-outline-primary border-neutral text-on-background flex items-center rounded-full border p-1',
                onSelect: ()=>this.interactiveCitation.select(),
                onBeginDelayedSelect: ()=>this.interactiveCitation.beginDelayedSelect(),
                onCancelPendingSelect: ()=>this.interactiveCitation.cancelPendingSelect(),
                stopPropagation: this.stopPropagation,
                onMouseLeave: this.delayedClosePopover,
                onMouseOver: this.delayedPopoverOpen,
                onFocus: this.openPopover,
                onBlur: this.closePopover
            }
        })(html`
          <span class="citation-title mx-1 truncate">
            ${this.citation.title}
          </span>
        `)}
        ${this.renderPopover()}
      </div>
    `;
    }
    updatePopper() {
        if (this.popperInstance) return void this.popperInstance.forceUpdate();
        const citationEl = this.citationRef.value;
        const popupEl = this.popupRef.value;
        if (!citationEl || !popupEl) return;
        this.popperInstance = createPopper(citationEl, popupEl, {
            placement: 'top-start',
            modifiers: [
                {
                    name: 'offset',
                    options: {
                        offset: [
                            0,
                            6
                        ]
                    }
                },
                preventOverflow
            ]
        });
    }
    cleanupPopper() {
        if (this.popperInstance) {
            this.popperInstance.destroy();
            this.popperInstance = void 0;
        }
    }
    clearTimers() {
        clearTimeout(this.hoverTimeout);
        clearTimeout(this.closePopoverTimeout);
    }
    getTruncatedText() {
        return this.citation.text && `${this.citation.text?.trim().slice(0, 200)}${this.citation.text.length > 200 ? '...' : ''}`;
    }
    anchorUrl(uri, text, filetype, pageNumber) {
        if (this.disableCitationAnchoring) return uri;
        switch(filetype){
            case 'html':
                return generateTextFragmentUrl(uri, text, filetype);
            case 'pdf':
                return generatePdfPageUrl(uri, pageNumber);
            default:
                return uri;
        }
    }
    renderPopover() {
        return html`
      <div
        ${ref(this.popupRef)}
        part="citation-popover"
        class="border-neutral bg-background mobile-only:hidden z-10 rounded-md border p-4 shadow flex-col gap-3 ${classMap({
            'desktop-only:flex': this.isOpen,
            hidden: !this.isOpen
        })}"
        role="dialog"
        @mouseenter=${this.cancelClosePopover}
        @mouseleave=${this.delayedClosePopover}
      >
        <div class="text-neutral-dark truncate text-sm">
          ${this.citation.clickUri ?? this.citation.uri}
        </div>
        ${renderHeading({
            props: {
                level: 0,
                class: 'text-md font-bold'
            }
        })(html`${this.citation.title}`)}
        <p class="text-on-background text-sm">${this.getTruncatedText()}</p>
      </div>
    `;
    }
    constructor(...args){
        super(...args), this.disableCitationAnchoring = false, this.isOpen = false, this.citationRef = createRef(), this.popupRef = createRef(), this.hoverAnalyticsTimeout = 1000, this.hoverDebounceTimeoutMs = 200, this.closePopoverDebounceMs = 100, this.ariaHaspopupAttr = (()=>{
            const attr = document.createAttribute('aria-haspopup');
            attr.value = 'dialog';
            return attr;
        })(), this.openPopover = ()=>{
            this.isOpen = true;
        }, this.closePopover = ()=>{
            this.clearTimers();
            this.isOpen = false;
        }, this.handleKeyDown = (e)=>{
            if ('Escape' === e.key && this.isOpen) this.closePopover();
        }, this.delayedClosePopover = ()=>{
            this.clearTimers();
            this.closePopoverTimeout = setTimeout(()=>{
                this.isOpen = false;
            }, this.closePopoverDebounceMs);
        }, this.cancelClosePopover = ()=>{
            clearTimeout(this.closePopoverTimeout);
        }, this.delayedPopoverOpen = ()=>{
            this.clearTimers();
            this.hoverTimeout = setTimeout(this.openPopover, this.hoverDebounceTimeoutMs);
        };
    }
}
AtomicCitation.styles = atomic_citation_tw_css;
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof GeneratedAnswerCitation ? Object : GeneratedAnswerCitation)
], AtomicCitation.prototype, "citation", void 0);
_ts_decorate([
    property({
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicCitation.prototype, "index", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", Function)
], AtomicCitation.prototype, "sendHoverEndEvent", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof InteractiveCitation ? Object : InteractiveCitation)
], AtomicCitation.prototype, "interactiveCitation", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-citation-anchoring'
    })
], AtomicCitation.prototype, "disableCitationAnchoring", void 0);
_ts_decorate([
    state()
], AtomicCitation.prototype, "isOpen", void 0);
_ts_decorate([
    watch('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCitation.prototype, "sendHoverAnalytics", null);
AtomicCitation = _ts_decorate([
    customElement('atomic-citation'),
    withTailwindStyles
], AtomicCitation);
export { AtomicCitation };
