import { NumberValue, Schema } from "@coveo/bueno";
import { buildInteractiveResult } from "@coveo/headless";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { getAttributesFromLinkSlotContent } from "../../common/item-link/attributes-slot.js";
import { renderLinkWithItemAnalytics } from "../../common/item-link/item-link.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { createResultContextController } from "../result-template-component-utils/context/result-context-controller.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { LightDomMixin } from "../../../mixins/light-dom.js";
import { parseXML } from "../../../utils/utils.js";
import arrow_right from "../../../images/arrow-right.js";
import "../atomic-result-text/atomic-result-text.js";
import "../../common/atomic-icon/atomic-icon.js";
import atomic_result_printable_uri_tw_css from "./atomic-result-printable-uri.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 AtomicResultPrintableUri extends LightDomMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        const slotName = 'attributes';
        this.linkAttributes = getAttributesFromLinkSlotContent(this, slotName);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.cleanupLinkCallbacks();
    }
    initialize() {
        if (!this.result && this.resultController.item) {
            const item = this.resultController.item;
            if ('result' in item) this.result = item.result;
            else this.result = item;
        }
        if (this.result) this.interactiveResult = buildInteractiveResult(this.bindings.engine, {
            options: {
                result: this.result
            }
        });
    }
    render() {
        return html`${when(this.result, ()=>this.renderPrintableUri())}`;
    }
    cleanupLinkCallbacks() {
        this.linkCleanupCallbacks.forEach((cleanup)=>cleanup());
        this.linkCleanupCallbacks = [];
    }
    getIndexOfEllipsis(parentsCount) {
        const valuesToHide = Math.max(2, parentsCount - this.maxNumberOfParts);
        const valuesToShowBeforeEllipsis = parentsCount - valuesToHide - 1;
        return valuesToShowBeforeEllipsis;
    }
    renderEllipsis() {
        return html`
      <li>
        <button
          aria-label=${this.bindings.i18n.t('collapsed-uri-parts')}
          aria-expanded=${this.listExpanded}
          @click=${(e)=>{
            e.stopPropagation();
            this.listExpanded = true;
            requestAnimationFrame(()=>{
                this.expandedPartElement?.focus();
            });
        }}
        >
          ...
        </button>
        ${this.renderSeparator()}
      </li>
    `;
    }
    get allParents() {
        const parentsXml = parseXML(`${this.result.raw.parents}`);
        const parents = Array.from(parentsXml.getElementsByTagName('parent'));
        const ellipsisIndex = this.getIndexOfEllipsis(parents.length);
        return parents.map((parent, i)=>{
            const name = parent.getAttribute('name');
            const uri = parent.getAttribute('uri');
            return {
                name,
                uri,
                isEllipsisTarget: i === ellipsisIndex,
                isLast: i === parents.length - 1
            };
        });
    }
    renderSeparator() {
        return html`
      <atomic-icon
        class="result-printable-uri-separator"
        .icon=${arrow_right}
        role="separator"
      ></atomic-icon>
    `;
    }
    renderParents() {
        const parents = this.allParents;
        if (this.listExpanded || parents.length <= this.maxNumberOfParts) return parents.map((parent)=>this.renderParentListItem(parent));
        const ellipsisIndex = this.getIndexOfEllipsis(parents.length);
        return html`
      ${parents.slice(0, ellipsisIndex).map((parent)=>this.renderParentListItem(parent))}
      ${this.renderEllipsis()}
      ${parents.slice(-1).map((parent)=>this.renderParentListItem(parent))}
    `;
    }
    renderParentListItem(parent) {
        return html`
      <li>
        ${this.renderLink(parent.name, parent.uri, parent.isEllipsisTarget)}
        ${parent.isLast ? nothing : this.renderSeparator()}
      </li>
    `;
    }
    renderLink(content, uri, shouldSetTarget) {
        return renderLinkWithItemAnalytics({
            props: {
                href: uri,
                title: content ?? void 0,
                onSelect: ()=>this.interactiveResult.select(),
                onBeginDelayedSelect: ()=>this.interactiveResult.beginDelayedSelect(),
                onCancelPendingSelect: ()=>this.interactiveResult.cancelPendingSelect(),
                attributes: this.linkAttributes,
                ref: shouldSetTarget ? (el)=>{
                    if (el instanceof HTMLAnchorElement) this.expandedPartElement = el;
                } : void 0,
                onInitializeLink: this.registerLinkCleanup
            }
        })(content ? html`${content}` : nothing);
    }
    renderPrintableUri() {
        const parents = this.allParents;
        if (parents.length) return html`
        <ul aria-label=${this.bindings.i18n.t('printable-uri')}>
          ${this.renderParents()}
        </ul>
      `;
        return renderLinkWithItemAnalytics({
            props: {
                href: this.result.clickUri,
                ariaLabel: this.result.printableUri || this.result.clickUri,
                onSelect: ()=>this.interactiveResult.select(),
                onBeginDelayedSelect: ()=>this.interactiveResult.beginDelayedSelect(),
                onCancelPendingSelect: ()=>this.interactiveResult.cancelPendingSelect(),
                attributes: this.linkAttributes,
                onInitializeLink: this.registerLinkCleanup
            }
        })(html`<atomic-result-text field="printableUri"></atomic-result-text>`);
    }
    constructor(){
        super(), this.maxNumberOfParts = 5, this.listExpanded = false, this.resultController = createResultContextController(this), this.linkCleanupCallbacks = [], this.registerLinkCleanup = (cleanup)=>{
            this.linkCleanupCallbacks.push(cleanup);
        };
        new ValidatePropsController(this, ()=>({
                maxNumberOfParts: this.maxNumberOfParts
            }), AtomicResultPrintableUri.propsSchema);
    }
}
AtomicResultPrintableUri.styles = atomic_result_printable_uri_tw_css;
AtomicResultPrintableUri.propsSchema = new Schema({
    maxNumberOfParts: new NumberValue({
        min: 3
    })
});
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'max-number-of-parts'
    })
], AtomicResultPrintableUri.prototype, "maxNumberOfParts", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultPrintableUri.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultPrintableUri.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicResultPrintableUri.prototype, "listExpanded", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Result ? Object : Result)
], AtomicResultPrintableUri.prototype, "result", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultPrintableUri.prototype, "render", null);
AtomicResultPrintableUri = _ts_decorate([
    customElement('atomic-result-printable-uri'),
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultPrintableUri);
export { AtomicResultPrintableUri };
