var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") 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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _DevvitFormImageField_instances, _DevvitFormImageField_dragabble, _DevvitFormImageField_handleInput, _DevvitFormImageField_handleError, _DevvitFormImageField_setRequiredFieldError, _DevvitFormImageField_handleInputWrapperClick;
import { msg } from '@lit/localize';
import { InputElement } from '@reddit/faceplate/base-classes/input-element.js';
import { html } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styles } from '../../../../styles.js';
import { DragAndDropController, DragState } from './drag-and-drop-controller.js';
import { MediaController, UPLOAD_ERROR_VALIDATION_MESSAGE } from './media-controller.js';
import { renderEmptyState } from './render-empty-state.js';
import { renderCarousel } from './render-media-carousel.js';
import { ALLOWED_IMAGE_MIMETYPES } from './validateMedia.js';
export class DevvitFormImageField extends InputElement {
    constructor() {
        super(...arguments);
        _DevvitFormImageField_instances.add(this);
        // @ts-expect-error copied from shreddit.
        _DevvitFormImageField_dragabble.set(this, new DragAndDropController(this, (files) => {
            void this.mediaController.handleMedia(files);
        }));
        this.mediaController = new MediaController(this, {
            setValidation: (message) => {
                // ingore media upload errors for non-required fields
                if (message === UPLOAD_ERROR_VALIDATION_MESSAGE && this.field && !this.field.required) {
                    __classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_handleError).call(this, '');
                    return;
                }
                __classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_handleError).call(this, message);
            },
        });
        this.handleRemoveClick = () => {
            this.mediaController.media = [];
            if (!this.mediaController.media.length) {
                __classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_setRequiredFieldError).call(this);
            }
            // @ts-expect-error copied from shreddit.
            this.requestUpdate();
        };
        _DevvitFormImageField_handleInputWrapperClick.set(this, async (event) => {
            const target = event.target;
            const button = target.closest('button.action');
            if (!button) {
                return;
            }
            if (button.classList.contains('remove')) {
                this.handleRemoveClick();
            }
            else if (button.classList.contains('upload-media')) {
                this._input?.click();
            }
        });
    }
    /** @ignore */
    static get styles() {
        return [styles, super.styles];
    }
    firstUpdated(_changedProperties) {
        // @ts-expect-error copied from shreddit.
        super.firstUpdated(_changedProperties);
        __classPrivateFieldGet(this, _DevvitFormImageField_dragabble, "f").initEventListeners(this.fileInputInnerWrapper);
    }
    get value() {
        return this.mediaController.getValue();
    }
    set value(newValue) {
        this.mediaController.setValue(newValue);
    }
    formDisabledCallback(disabled) {
        if (disabled) {
            // @ts-expect-error copied from shreddit.
            this.setCustomValidity('');
        }
        else if (!disabled && this.value?.length === 0 && this.field?.required) {
            __classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_setRequiredFieldError).call(this);
            // @ts-expect-error copied from shreddit.
            this.reportValidity();
        }
    }
    render() {
        const mimetypes = ALLOWED_IMAGE_MIMETYPES;
        let containerClasses = `border-neutral-border ${this.mediaController.media.length ? 'border-solid' : 'border-dashed'}`;
        if (__classPrivateFieldGet(this, _DevvitFormImageField_dragabble, "f").dragState === DragState.IN_WINDOW) {
            containerClasses = 'bg-neutral-background-weak border-alienblue-600 border-dashed';
        }
        else if (__classPrivateFieldGet(this, _DevvitFormImageField_dragabble, "f").dragState === DragState.IN_FRAME) {
            containerClasses = 'bg-neutral-background-weak border-alienblue-600 border-solid';
        }
        const HiddenInput = html `
      <input
        class="file-input"
        hidden
        type="file"
        @input="${__classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_handleInput)}"
        accept="${mimetypes.join(',')}"
      />
    `;
        return html `
      ${HiddenInput}
      <div
        id="fileInputInnerWrapper"
        class="flex w-full border-sm rounded-dx-md overflow-hidden group min-h-[min(20vw,150px)] ${containerClasses}"
        @click="${__classPrivateFieldGet(this, _DevvitFormImageField_handleInputWrapperClick, "f")}"
        @keypress="${__classPrivateFieldGet(this, _DevvitFormImageField_handleInputWrapperClick, "f")}"
      >
        ${this.mediaController.media.length
            ? renderCarousel(this.mediaController)
            : renderEmptyState({
                allowImages: true,
                allowVideos: false,
                inputDragState: __classPrivateFieldGet(this, _DevvitFormImageField_dragabble, "f").dragState,
            })}
      </div>
    `;
    }
}
_DevvitFormImageField_dragabble = new WeakMap(), _DevvitFormImageField_handleInputWrapperClick = new WeakMap(), _DevvitFormImageField_instances = new WeakSet(), _DevvitFormImageField_handleInput = function _DevvitFormImageField_handleInput(e) {
    if (!(e.target instanceof HTMLInputElement))
        return;
    const files = e.target.files;
    if (files?.length) {
        void this.mediaController.handleMedia(Array.from(files));
        e.target.value = '';
    }
}, _DevvitFormImageField_handleError = function _DevvitFormImageField_handleError(error) {
    // @ts-expect-error copied from shreddit.
    this.setCustomValidity(error);
    // @ts-expect-error copied from shreddit.
    this.reportValidity();
}, _DevvitFormImageField_setRequiredFieldError = function _DevvitFormImageField_setRequiredFieldError() {
    __classPrivateFieldGet(this, _DevvitFormImageField_instances, "m", _DevvitFormImageField_handleError).call(this, msg('Please add an image', {
        desc: 'Message to user to please add an image file',
    }));
};
__decorate([
    query('#fileInputInnerWrapper'),
    __metadata("design:type", HTMLDivElement)
], DevvitFormImageField.prototype, "fileInputInnerWrapper", void 0);
__decorate([
    property({ type: MediaController })
    // @ts-expect-error copied from shreddit.
    ,
    __metadata("design:type", MediaController)
], DevvitFormImageField.prototype, "mediaController", void 0);
__decorate([
    property({ attribute: false }),
    __metadata("design:type", Object)
], DevvitFormImageField.prototype, "field", void 0);
__decorate([
    query('input.file-input'),
    __metadata("design:type", HTMLInputElement)
], DevvitFormImageField.prototype, "_input", void 0);
// Faceplate's base classes and mixins aren't playing nice with type checking for some reason
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customElements.define('devvit-form-image-field', DevvitFormImageField);
//# sourceMappingURL=devvit-image-field.js.map