import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { ResultTemplatesHelpers, buildBreadcrumbManager } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";
import { when } from "lit/directives/when.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 { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { getFieldValueCaption } from "../../../utils/field-utils.js";
import { titleToKebab } from "../../../utils/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 AtomicResultMultiValueText extends LitElement {
    get result() {
        return this.resultContext.item;
    }
    initialize() {
        this.breadcrumbManager = buildBreadcrumbManager(this.bindings.engine);
    }
    get resultValues() {
        const value = ResultTemplatesHelpers.getResultProperty(this.result, this.field);
        if (null === value) return null;
        if (Array.isArray(value)) return value.map((v)=>`${v}`.trim());
        if ('string' != typeof value || '' === value.trim()) {
            this.error = new Error(`Could not parse "${value}" from field "${this.field}" as a string array.`);
            return null;
        }
        return this.delimiter ? value.split(this.delimiter).map((value)=>value.trim()) : [
            value
        ];
    }
    get facetSelectedValues() {
        const values = [];
        if (!this.breadcrumbManager) return values;
        this.breadcrumbManager.state.facetBreadcrumbs.filter((facet)=>facet.field === this.field).forEach((facet)=>{
            values.push(...facet.values.map(({ value })=>value.value));
        });
        return values;
    }
    updateSortedValues() {
        const allValues = this.resultValues;
        if (null === allValues) {
            this.sortedValues = null;
            return;
        }
        const allValuesSet = new Set(allValues);
        const firstValues = this.facetSelectedValues.filter((value)=>allValuesSet.has(value));
        this.sortedValues = Array.from(allValues.reduce((set, value)=>set.add(value), new Set(firstValues)));
    }
    getShouldDisplayLabel(values) {
        return this.maxValuesToDisplay > 0 && values.length > this.maxValuesToDisplay;
    }
    getNumberOfValuesToDisplay(values) {
        return Math.min(values.length, this.maxValuesToDisplay);
    }
    renderValue(value) {
        const label = getFieldValueCaption(this.field, value, this.bindings.i18n);
        const kebabValue = titleToKebab(value);
        return keyed(value, html`
        <li part="result-multi-value-text-value">
          <slot name=${`result-multi-value-text-value-${kebabValue}`}>
            ${label}
          </slot>
        </li>
      `);
    }
    renderSeparator() {
        return html`
      <li
        aria-hidden="true"
        part="result-multi-value-text-separator"
        class="${String.raw`inline-block before:inline before:content-[',\00a0']`}"
      ></li>
    `;
    }
    renderMoreLabel(value) {
        return html`
      <li part="result-multi-value-text-value-more">
        ${this.bindings.i18n.t('n-more', {
            value
        })}
      </li>
    `;
    }
    renderListItems(values) {
        const numberOfValuesToDisplay = this.getNumberOfValuesToDisplay(values);
        const nodes = [];
        for(let i = 0; i < numberOfValuesToDisplay; i++){
            if (i > 0) nodes.push(this.renderSeparator());
            nodes.push(this.renderValue(values[i]));
        }
        if (this.getShouldDisplayLabel(values)) {
            nodes.push(this.renderSeparator());
            nodes.push(this.renderMoreLabel(values.length - numberOfValuesToDisplay));
        }
        return nodes;
    }
    willUpdate() {
        this.updateSortedValues();
    }
    render() {
        return html`${when(this.sortedValues, ()=>html`
        <ul part="result-multi-value-text-list" class="m-0 flex list-none p-0">
          ${this.renderListItems(this.sortedValues)}
        </ul>
      `)}`;
    }
    constructor(){
        super(), this.maxValuesToDisplay = 3, this.delimiter = null, this.sortedValues = null, this.resultContext = createResultContextController(this);
        new ValidatePropsController(this, ()=>({
                field: this.field,
                maxValuesToDisplay: this.maxValuesToDisplay
            }), AtomicResultMultiValueText.propsSchema);
    }
}
AtomicResultMultiValueText.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    }),
    maxValuesToDisplay: new NumberValue({
        min: 0,
        required: false
    })
});
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultMultiValueText.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'max-values-to-display'
    })
], AtomicResultMultiValueText.prototype, "maxValuesToDisplay", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", Object)
], AtomicResultMultiValueText.prototype, "delimiter", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultMultiValueText.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultMultiValueText.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", Object)
], AtomicResultMultiValueText.prototype, "sortedValues", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultMultiValueText.prototype, "render", null);
AtomicResultMultiValueText = _ts_decorate([
    customElement('atomic-result-multi-value-text'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultMultiValueText);
export { AtomicResultMultiValueText };
