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 __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
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 _DevvitFormSelectionDropdown_instances, _DevvitFormSelectionDropdown_config, _DevvitFormSelectionDropdown_getLabel, _DevvitFormSelectionDropdown_updateSelection, _DevvitFormSelectionDropdown_singleSelectListItem, _DevvitFormSelectionDropdown_multiSelectListItem, _DevvitFormSelectionDropdown_renderEmptyItem, _DevvitFormSelectionDropdown_validateFieldValue, _DevvitFormSelectionDropdown_setError;
import '@reddit/faceplate-ui/components/faceplate-dropdown-menu.js';
import '@reddit/faceplate-ui/components/faceplate-menu.js';
import '@reddit/faceplate-ui/components/faceplate-switch-input.js';
import { FieldConfig_Selection } from '@devvit/protos/types/devvit/ui/form_builder/v1alpha/field.js';
import { InputElement } from '@reddit/faceplate/base-classes/input-element.js';
import { msg } from '@reddit/faceplate/lib/i18n/localize.js';
import { html } from '@reddit/faceplate-ui/templateRenderingStrategy/clientStrategy.js';
import { dropdownButton } from '@reddit/faceplate-ui/templates/client/dropdownButton.js';
import { listItem } from '@reddit/faceplate-ui/templates/client/list-item.js';
import { css } from 'lit';
import { property, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styles } from '../../../styles.js';
import { renderHelpText } from '../fields/renderHelpText.js';
export class DevvitFormSelectionDropdown extends InputElement {
    constructor() {
        super(...arguments);
        _DevvitFormSelectionDropdown_instances.add(this);
        this.dropdownOpen = false;
        this.selectedValues = [];
        _DevvitFormSelectionDropdown_config.set(this, FieldConfig_Selection.fromPartial({}));
        _DevvitFormSelectionDropdown_singleSelectListItem.set(this, (option) => listItem({
            label: option.label,
            onClick: () => __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_updateSelection).call(this, option),
        }));
        _DevvitFormSelectionDropdown_multiSelectListItem.set(this, (option) => listItem({
            label: html `
        <faceplate-switch-input ?checked="${this.selectedValues.includes(option.value)}">
          ${option.label}
        </faceplate-switch-input>
      `,
            onClick: (e) => {
                __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_updateSelection).call(this, option, e.currentTarget.checked);
                e.stopImmediatePropagation();
            },
        }));
    }
    static get styles() {
        return [
            super.styles,
            styles,
            // fixes a layering bug when dropdown menus are too close together
            css `
        .button .dropdown-icon {
          transform: none;
        }
      `,
        ];
    }
    get value() {
        return this.selectedValues.join(',');
    }
    willUpdate(changedProperties) {
        if (changedProperties.has('field')) {
            __classPrivateFieldSet(this, _DevvitFormSelectionDropdown_config, this.field?.fieldConfig?.selectionConfig ?? FieldConfig_Selection.fromPartial({}), "f");
            this.selectedValues = this.field?.defaultValue?.selectionValue?.values ?? [];
        }
    }
    formDisabledCallback(disabled) {
        __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_validateFieldValue).call(this, disabled);
    }
    render() {
        let formField;
        if (this.field) {
            const option = __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").choices ?? [];
            const items = __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").multiSelect
                ? option.map((o) => __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_multiSelectListItem, "f").call(this, o))
                : option.map((o) => __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_singleSelectListItem, "f").call(this, o));
            const emptyItem = !__classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").multiSelect && !__classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").minSelections && !this.field.required
                ? __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_renderEmptyItem).call(this)
                : undefined;
            const classes = {
                'flex-grow': true,
                'z-auto': !this.dropdownOpen,
            };
            formField = html `
        <faceplate-dropdown-menu
          id="${this.field.fieldId}"
          class="${classMap(classes)}"
          .onopen="${() => (this.dropdownOpen = true)}"
          .onclose="${() => (this.dropdownOpen = false)}"
          ?disabled="${this.field.disabled}"
        >
          ${dropdownButton({
                attributes: {
                    disabled: Boolean(this.field.disabled),
                    className: 'flex justify-between grow',
                },
                children: html `<span class="grow">${__classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_getLabel).call(this)}</span>`,
                selected: this.dropdownOpen,
            })}
          <faceplate-menu slot="menu" class="max-h-[160px] max-w-[400px] overflow-y-auto"
            >${emptyItem}${items}
          </faceplate-menu>
        </faceplate-dropdown-menu>
        ${renderHelpText(this.field.helpText)}
      `;
        }
        return html `${formField}${super.render()}`;
    }
}
_DevvitFormSelectionDropdown_config = new WeakMap(), _DevvitFormSelectionDropdown_singleSelectListItem = new WeakMap(), _DevvitFormSelectionDropdown_multiSelectListItem = new WeakMap(), _DevvitFormSelectionDropdown_instances = new WeakSet(), _DevvitFormSelectionDropdown_getLabel = function _DevvitFormSelectionDropdown_getLabel() {
    const selectedCount = this.selectedValues.length;
    if (selectedCount === 0) {
        return '';
    }
    if (selectedCount === 1) {
        const value = this.selectedValues[0];
        return __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").choices.find((c) => c.value === value)?.label ?? '';
    }
    return msg(`[${selectedCount} items selected]`, {
        desc: 'Displayed on a drop down menu when multiple values are selected',
    });
}, _DevvitFormSelectionDropdown_updateSelection = function _DevvitFormSelectionDropdown_updateSelection(option, selected = true) {
    if (__classPrivateFieldGet(this, _DevvitFormSelectionDropdown_config, "f").multiSelect) {
        const isAlreadySelected = this.selectedValues.includes(option.value);
        if (selected && !isAlreadySelected) {
            this.selectedValues = [...this.selectedValues, option.value];
        }
        else if (isAlreadySelected) {
            this.selectedValues = this.selectedValues.filter((v) => v !== option.value);
        }
    }
    else {
        this.selectedValues = [option.value];
    }
    __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_validateFieldValue).call(this, Boolean(this.field?.disabled));
}, _DevvitFormSelectionDropdown_renderEmptyItem = function _DevvitFormSelectionDropdown_renderEmptyItem() {
    return listItem({
        label: html `&nbsp;`,
        onClick: () => {
            this.selectedValues = [];
        },
    });
}, _DevvitFormSelectionDropdown_validateFieldValue = function _DevvitFormSelectionDropdown_validateFieldValue(disabled) {
    if (disabled || Boolean(this.value?.length)) {
        __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_setError).call(this, null);
        return;
    }
    if (this.value?.length === 0 && this.field?.required) {
        __classPrivateFieldGet(this, _DevvitFormSelectionDropdown_instances, "m", _DevvitFormSelectionDropdown_setError).call(this, msg('Please select an option', {
            desc: 'Message to user to select an option for a required field',
        }));
    }
}, _DevvitFormSelectionDropdown_setError = function _DevvitFormSelectionDropdown_setError(error) {
    // @ts-expect-error copied from shreddit.
    this.setCustomValidity(error || '');
    // @ts-expect-error copied from shreddit.
    this.reportValidity();
};
__decorate([
    property({ attribute: false }),
    __metadata("design:type", Object)
], DevvitFormSelectionDropdown.prototype, "field", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], DevvitFormSelectionDropdown.prototype, "dropdownOpen", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], DevvitFormSelectionDropdown.prototype, "selectedValues", 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-selection-dropdown', DevvitFormSelectionDropdown);
//# sourceMappingURL=devvit-form-selection-dropdown.js.map