import { Schema, StringValue } from "@coveo/bueno";
import { ResultTemplatesHelpers } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit-html/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 { LightDomMixin } from "../../../mixins/light-dom.js";
import { filterProtocol } from "../../../utils/xss-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 AtomicResultImage extends LightDomMixin(LitElement) {
    initialize() {
        if (!this.result && this.resultController.item) {
            const item = this.resultController.item;
            if ('result' in item) this.result = item.result;
            else this.result = item;
        }
    }
    get url() {
        const value = ResultTemplatesHelpers.getResultProperty(this.result, this.field);
        return Array.isArray(value) ? value[0] : value;
    }
    get altText() {
        if (this.imageAltField) {
            const value = ResultTemplatesHelpers.getResultProperty(this.result, this.imageAltField);
            if (Array.isArray(value) && 'string' == typeof value[0]) return value[0];
            if ('string' == typeof value) return value;
        }
        return this.bindings.i18n.t('image-alt-fallback', {
            itemName: this.result.title
        });
    }
    logWarning(message) {
        this.bindings.engine.logger.warn(message);
    }
    handleImageError() {
        const message = `The image url "${this.url}" is not valid or could not be loaded. You might want to add a "fallback" property.`;
        if (this.fallback) this.useFallback = true;
        else this.logWarning(message);
    }
    handleMissingFallback(message) {
        if (!this.fallback) {
            this.logWarning(message);
            this.remove();
            return null;
        }
        return this.fallback;
    }
    validateUrl(url) {
        if (!url) {
            const message = `"${this.field}" is missing. Please review your indexation. You might want to add a "fallback" property.`;
            return this.handleMissingFallback(message);
        }
        if ('string' != typeof url) {
            const message = `Expected "${this.field}" to be a text field. Please review your indexation. You might want to add a "fallback" property.`;
            return this.handleMissingFallback(message);
        }
        return url;
    }
    renderImage() {
        let url = this.useFallback ? this.fallback : this.url;
        if (!this.useFallback) {
            url = this.validateUrl(url);
            if (!url) return nothing;
        }
        return html`
      <img
        alt=${this.altText}
        src=${filterProtocol(url)}
        @error=${()=>this.handleImageError()}
        loading="lazy"
      />
    `;
    }
    render() {
        return html`${when(this.result, ()=>this.renderImage())}`;
    }
    constructor(){
        super(), this.useFallback = false, this.resultController = createResultContextController(this);
        new ValidatePropsController(this, ()=>({
                field: this.field
            }), AtomicResultImage.propsSchema, false);
    }
}
AtomicResultImage.styles = css`atomic-result-image{display:grid;grid-template-rows:100%;height:100%;place-items:center;width:100%;img{height:100%;object-fit:contain;width:100%}}`;
AtomicResultImage.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    })
});
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultImage.prototype, "field", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'image-alt-field'
    }),
    _ts_metadata("design:type", String)
], AtomicResultImage.prototype, "imageAltField", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultImage.prototype, "fallback", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultImage.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultImage.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Result ? Object : Result)
], AtomicResultImage.prototype, "result", void 0);
_ts_decorate([
    state()
], AtomicResultImage.prototype, "useFallback", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultImage.prototype, "render", null);
AtomicResultImage = _ts_decorate([
    customElement('atomic-result-image'),
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultImage);
export { AtomicResultImage };
