import { h } from "@stencil/core";
export class ImageUploader {
    constructor() {
        this.maxImages = 10;
        this.disabled = false;
        this.images = [];
        this.isEventListenrAttached = false;
        this.handlePaste = (e) => {
            e.stopPropagation();
            e.preventDefault();
            if (e.clipboardData && e.clipboardData.getData("text")) {
                // Ignore text pastes for image uploader
                return;
            }
            const items = (e.clipboardData || window["clipboardData"]).files;
            this.uploadImage(items);
        };
        this.handleDragEnter = (e) => {
            e.preventDefault();
            if (e.target && e.target.style) {
                ;
                e.target.style.border = "1px dashed #000";
            }
        };
        this.handleDragOver = (e) => {
            e.preventDefault();
            if (e.target && e.target.style) {
                ;
                e.target.style.border = "1px dashed #000";
            }
        };
        this.handleDrop = (e) => {
            e.preventDefault();
            if (e.target && e.target.style) {
                ;
                e.target.style.border = "none";
            }
            this.uploadImage(e.dataTransfer.files);
        };
        this.onInputChange = (files) => {
            if (files.length > 0) {
                this.uploadImage(files);
            }
            else {
                this.imageUploadError.emit("No image uploaded.");
                return false;
            }
        };
    }
    handleIsOpened() {
        this.setupEventListeners();
    }
    // @Method()
    setupEventListeners() {
        const container = this.targetElement;
        if (!container)
            return;
        if (this.isEventListenrAttached)
            return;
        this.isEventListenrAttached = true;
        container.addEventListener("paste", this.handlePaste);
        container.addEventListener("dragenter", this.handleDragEnter);
        container.addEventListener("dragover", this.handleDragOver);
        container.addEventListener("drop", this.handleDrop);
    }
    disconnectedCallback() {
        const container = this.el.querySelector(".custom-input");
        if (!container)
            return;
        container.removeEventListener("paste", this.handlePaste);
        container.removeEventListener("dragenter", this.handleDragEnter);
        container.removeEventListener("dragover", this.handleDragOver);
        container.removeEventListener("drop", this.handleDrop);
    }
    handleCapturedImage(event) {
        this.uploadImage(event.detail);
    }
    uploadImage(files) {
        const currentCount = this.images.length;
        const filesArr = Array.from(files);
        // Validate each file
        for (const file of filesArr) {
            // Check file size (5MB limit)
            if (file.size > 5 * 1024 * 1024) {
                this.imageUploadError.emit(`Image "${file.name}" must be under 5MB`);
                return;
            }
            // Check file type
            if (!file.type.startsWith('image/')) {
                this.imageUploadError.emit(`File "${file.name}" is not an image. Only image files are allowed.`);
                return;
            }
        }
        const validFiles = filesArr.filter(file => file.type.match("image.*"));
        if (currentCount + validFiles.length > this.maxImages) {
            this.imageUploadError.emit(`You can upload a maximum of ${this.maxImages} images at a time.`);
            return;
        }
        const readers = validFiles.map(file => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                    const mimeType = file.type;
                    const base64Image = `data:${mimeType};base64,${reader.result.split(",")[1]}`;
                    resolve(base64Image);
                };
                reader.onerror = err => {
                    this.imageUploadError.emit("Something went wrong while reading the file.");
                    reject(err);
                };
                reader.readAsDataURL(file);
            });
        });
        Promise.all(readers).then(newImagesArr => {
            const newImages = [...this.images, ...newImagesArr];
            this.imagesChange.emit(newImages);
        });
    }
    async removeImageAtIndex(idx) {
        const newImages = this.images.filter((_, i) => i !== idx);
        this.imagesChange.emit(newImages);
    }
    render() {
        return (h("div", { key: 'c9818407a99ed0d89a24d8c561497dd22c451d71', class: "image-uploader" }, h("button", { key: 'e4346c7faeb97827b4f0d2140c2aadad17c595f6', type: "button", class: "py-1", disabled: this.disabled, onClick: () => this.uploadElem && this.uploadElem.click(), "aria-label": "Upload Images" }, h("div", { key: '3f84c3eb9b71f795c775e96c6bf758c736e0f872', class: "flex items-center gap-2" }, h("div", { key: 'fd837005d49b988a562d6b2072ff7fd709621d24' }, h("svg", { key: 'b787a29fe238db1c981e8f6afc148b54fe83a8f2', width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", class: "h-5 w-5 shrink-0" }, h("path", { key: '7bba989aa3dfbcca5be561c1931f04866e4fc4bc', "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M18.0322 5.02393C17.7488 5.00078 17.3766 5 16.8 5H11.5002C11.3 6 11.0989 6.91141 10.8903 7.85409C10.7588 8.44955 10.6432 8.97304 10.3675 9.41399C10.1262 9.80009 9.80009 10.1262 9.41399 10.3675C8.97304 10.6432 8.44955 10.7588 7.85409 10.8903C7.81276 10.8994 7.77108 10.9086 7.72906 10.9179L5.21693 11.4762C5.1442 11.4924 5.07155 11.5001 5 11.5002V16.8C5 17.3766 5.00078 17.7488 5.02393 18.0322C5.04612 18.3038 5.0838 18.4045 5.109 18.454C5.20487 18.6422 5.35785 18.7951 5.54601 18.891C5.59546 18.9162 5.69617 18.9539 5.96784 18.9761C6.25118 18.9992 6.62345 19 7.2 19H10C10.5523 19 11 19.4477 11 20C11 20.5523 10.5523 21 10 21H7.16144C6.6343 21 6.17954 21 5.80497 20.9694C5.40963 20.9371 5.01641 20.8658 4.63803 20.673C4.07354 20.3854 3.6146 19.9265 3.32698 19.362C3.13419 18.9836 3.06287 18.5904 3.03057 18.195C2.99997 17.8205 2.99998 17.3657 3 16.8385L3 11C3 8.92477 4.02755 6.93324 5.4804 5.4804C6.93324 4.02755 8.92477 3 11 3L16.8385 3C17.3657 2.99998 17.8205 2.99997 18.195 3.03057C18.5904 3.06287 18.9836 3.13419 19.362 3.32698C19.9265 3.6146 20.3854 4.07354 20.673 4.63803C20.8658 5.01641 20.9371 5.40963 20.9694 5.80497C21 6.17954 21 6.6343 21 7.16144V10C21 10.5523 20.5523 11 20 11C19.4477 11 19 10.5523 19 10V7.2C19 6.62345 18.9992 6.25118 18.9761 5.96784C18.9539 5.69617 18.9162 5.59546 18.891 5.54601C18.7951 5.35785 18.6422 5.20487 18.454 5.109C18.4045 5.0838 18.3038 5.04612 18.0322 5.02393ZM5.28014 9.41336L7.2952 8.96556C8.08861 8.78925 8.24308 8.74089 8.35381 8.67166C8.48251 8.59121 8.59121 8.48251 8.67166 8.35381C8.74089 8.24308 8.78925 8.08861 8.96556 7.2952L9.41336 5.28014C8.51014 5.59289 7.63524 6.15398 6.89461 6.89461C6.15398 7.63524 5.59289 8.51014 5.28014 9.41336ZM17 15C17 14.4477 17.4477 14 18 14C18.5523 14 19 14.4477 19 15V17H21C21.5523 17 22 17.4477 22 18C22 18.5523 21.5523 19 21 19H19V21C19 21.5523 18.5523 22 18 22C17.4477 22 17 21.5523 17 21V19H15C14.4477 19 14 18.5523 14 18C14 17.4477 14.4477 17 15 17H17V15Z", fill: "currentColor" }))), h("div", { key: '4c3feb42c66cc98af2b8cc5a863643a671f9cf00' }, "Upload Images"))), h("input", { key: 'fe0ae0769c82a7c76f1bb9b9ba97de26cc2f765c', type: "file", multiple: true, accept: "image/*", style: { display: "none" }, disabled: this.disabled, onChange: ($event) => this.onInputChange($event.target.files), ref: el => (this.uploadElem = el) })));
    }
    static get is() { return "image-uploader"; }
    static get originalStyleUrls() {
        return {
            "$": ["./input.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["input.css"]
        };
    }
    static get properties() {
        return {
            "maxImages": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-images",
                "defaultValue": "10"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "false"
            },
            "images": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "targetElement": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "HTMLTextAreaElement",
                    "resolved": "HTMLTextAreaElement",
                    "references": {
                        "HTMLTextAreaElement": {
                            "location": "global",
                            "id": "global::HTMLTextAreaElement"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get events() {
        return [{
                "method": "imagesChange",
                "name": "imagesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                }
            }, {
                "method": "imageUploadError",
                "name": "imageUploadError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }, {
                "method": "capturedImgUpload",
                "name": "capturedImgUpload",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "File[]",
                    "resolved": "File[]",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    }
                }
            }, {
                "method": "isElementAvailable",
                "name": "isElementAvailable",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "removeImageAtIndex": {
                "complexType": {
                    "signature": "(idx: number) => Promise<void>",
                    "parameters": [{
                            "name": "idx",
                            "type": "number",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get listeners() {
        return [{
                "name": "isElementAvailable",
                "method": "handleIsOpened",
                "target": "document",
                "capture": false,
                "passive": false
            }, {
                "name": "capturedImgUpload",
                "method": "handleCapturedImage",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
