import { EF_INTERACTIVE } from "../EF_INTERACTIVE.js";
import { EFSourceMixin } from "./EFSourceMixin.js";
import { EFTemporal } from "./EFTemporal.js";
import { FetchMixin } from "./FetchMixin.js";
import { Task } from "@lit/task";
import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import _decorate from "@oxc-project/runtime/helpers/decorate";
import { createRef, ref } from "lit/directives/ref.js";
let EFImage = class EFImage$1 extends EFTemporal(EFSourceMixin(FetchMixin(LitElement), { assetType: "image_files" })) {
	constructor(..._args) {
		super(..._args);
		this.imageRef = createRef();
		this.canvasRef = createRef();
		this.fetchImage = new Task(this, {
			autoRun: EF_INTERACTIVE,
			args: () => [this.assetPath(), this.fetch],
			task: async ([assetPath, fetch], { signal }) => {
				if (this.isDirectUrl(assetPath)) return;
				const response = await fetch(assetPath, { signal });
				const image = new Image();
				image.src = URL.createObjectURL(await response.blob());
				await new Promise((resolve, reject) => {
					image.onload = resolve;
					image.onerror = reject;
				});
				if (!this.canvasRef.value) throw new Error("Canvas not ready");
				const ctx = this.canvasRef.value.getContext("2d");
				if (!ctx) throw new Error("Canvas 2d context not ready");
				this.canvasRef.value.width = image.width;
				this.canvasRef.value.height = image.height;
				ctx.drawImage(image, 0, 0);
			}
		});
		this.frameTask = new Task(this, {
			autoRun: EF_INTERACTIVE,
			args: () => [this.fetchImage.status],
			task: async () => {
				await this.fetchImage.taskComplete;
			}
		});
	}
	static {
		this.styles = [css`
      :host {
        display: block;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      canvas, img {
        all: inherit;
      }
    `];
	}
	#assetId = null;
	set assetId(value) {
		this.#assetId = value;
	}
	get assetId() {
		return this.#assetId ?? this.getAttribute("asset-id");
	}
	render() {
		const assetPath = this.assetPath();
		const isDirectUrl = this.isDirectUrl(assetPath);
		return isDirectUrl ? html`<img ${ref(this.imageRef)} src=${assetPath} />` : html`<canvas ${ref(this.canvasRef)}></canvas>`;
	}
	isDirectUrl(src) {
		return src.startsWith("http://") || src.startsWith("https://");
	}
	assetPath() {
		if (this.assetId) return `${this.apiHost}/api/v1/image_files/${this.assetId}`;
		if (this.isDirectUrl(this.src)) return this.src;
		return `/@ef-image/${this.src}`;
	}
	get hasOwnDuration() {
		return this.hasExplicitDuration;
	}
};
_decorate([property({
	type: String,
	attribute: "asset-id",
	reflect: true
})], EFImage.prototype, "assetId", null);
EFImage = _decorate([customElement("ef-image")], EFImage);
export { EFImage };
