'use strict';

var index = require('./index-BUvWX8u2.js');
var form = require('./form-CpM5Z8q7.js');
var index$1 = require('./index-DGBoDsAL.js');

const pdsSelectTokensCss = ":host{--pine-select-color-background-danger:var(--pine-color-red-050)}";

const labelCss = ":host{display:inline-block}:host([aria-disabled=true]) label{color:var(--pine-color-text-label-disabled)}:host([aria-readonly=true]) label{color:var(--pine-color-text-label-readonly)}label{color:var(--pine-color-text-label);font:var(--pine-typography-body-medium);letter-spacing:var(--pine-letter-spacing)}";

const pdsSelectCss = ":host{--pds-select-background:var(--pine-color-background-container);--pds-select-border:var(--pine-border);--pds-select-border-radius:var(--pine-dimension-125);--pds-select-border-radius-start-end:var(--pine-dimension-125);--pds-select-border-radius-start-start:var(--pine-dimension-125);--pds-select-border-radius-end-end:var(--pine-dimension-125);--pds-select-border-radius-end-start:var(--pine-dimension-125);--pds-select-min-height:36px;--box-shadow-focus:0 0 0 1px var(--pine-color-background-container), 0 0 0 3px var(--pine-color-focus-ring);--box-shadow-focus-error:0 0 0 1px var(--pine-color-background-container), 0 0 0 3px var(--pine-color-focus-ring-danger)}:host .hidden,:host :host([hidden]){display:none}.pds-select{color:var(--pine-color-text);display:grid;-ms-flex-direction:column;flex-direction:column;grid-template-areas:\"label label\" \"field field\" \"message message\";grid-template-columns:1fr minmax(2rem, -webkit-min-content);grid-template-columns:1fr minmax(2rem, min-content);grid-template-rows:-webkit-min-content -webkit-min-content -webkit-min-content;grid-template-rows:min-content min-content min-content;position:relative;width:100%}.pds-select__label-wrapper{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;grid-area:label;-ms-flex-pack:justify;justify-content:space-between;-webkit-margin-after:var(--pine-dimension-2xs);margin-block-end:var(--pine-dimension-2xs)}.pds-select__action{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;gap:var(--pine-dimension-xs);-webkit-margin-start:var(--pine-dimension-xs);margin-inline-start:var(--pine-dimension-xs)}label{-webkit-margin-after:var(--pine-dimension-2xs);margin-block-end:var(--pine-dimension-2xs)}.pds-select__label-wrapper label{-webkit-margin-after:0;margin-block-end:0}select{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:var(--pds-select-background);border:var(--pds-select-border);border-end-end-radius:var(--pds-select-border-radius-end-end, var(--pds-select-border-radius));border-end-start-radius:var(--pds-select-border-radius-end-start, var(--pds-select-border-radius));border-start-end-radius:var(--pds-select-border-radius-start-end, var(--pds-select-border-radius));border-start-start-radius:var(--pds-select-border-radius-start-start, var(--pds-select-border-radius));color:var(--pine-color-text);font:var(--pine-typography-body);grid-area:field;letter-spacing:var(--pine-letter-spacing);min-height:var(--pds-select-min-height);padding:calc(var(--pine-dimension-xs) - var(--pine-border-width)) var(--pine-dimension-150);-webkit-padding-end:var(--pine-dimension-450);padding-inline-end:var(--pine-dimension-450);position:relative}select:hover{border-color:var(--pine-color-border-hover);cursor:pointer}select:focus-visible{border-color:var(--pine-color-border-active);outline:var(--pine-outline-focus);outline-offset:var(--pine-border-width)}select:disabled{background-color:var(--pine-color-background-container-disabled);border-color:var(--pine-color-border-disabled);color:var(--pine-color-text-disabled);cursor:not-allowed}select:has(~.pds-select__message .pds-select__error-message){background-color:var(--pine-select-color-background-danger);border-color:var(--pine-color-border-danger)}:host-context([data-theme=dark]) select:has(~.pds-select__message .pds-select__error-message){background-color:var(--pine-color-red-950)}select:has(~.pds-select__message .pds-select__error-message):focus-visible{outline-color:var(--pine-color-focus-ring-danger)}:host(.is-disabled) .pds-select__select-icon{color:var(--pine-color-text-disabled)}:host(.is-invalid) select{background-color:var(--pine-select-color-background-danger);border-color:var(--pine-color-border-danger)}:host-context([data-theme=dark]) :host(.is-invalid) select{background-color:var(--pine-color-red-950)}:host(.is-invalid) select:focus-visible{outline-color:var(--pine-color-focus-ring-danger)}:host([highlight]:not(.is-disabled):not(.is-invalid)) select{background-color:var(--pine-color-accent-disabled);border-color:var(--pine-color-accent);color:var(--pine-color-text-accent)}:host([highlight]:not(.is-disabled):not(.is-invalid)) select:hover:not(:disabled){border-color:var(--pine-color-accent-hover)}:host([highlight]:not(.is-disabled):not(.is-invalid)) select:focus-visible{outline-color:var(--pine-color-focus-ring)}:host([highlight]:not(.is-disabled):not(.is-invalid)) .pds-select__select-icon{color:var(--pine-color-text-accent)}.pds-select__error-message,.pds-select__helper-message{color:var(--pine-color-text-message);font:var(--pine-typography-body-sm-medium);-webkit-margin-after:0;margin-block-end:0;-webkit-margin-before:var(--pine-dimension-2xs);margin-block-start:var(--pine-dimension-2xs)}.pds-select__error-message{color:var(--pine-color-text-message-danger);display:-ms-flexbox;display:flex;gap:var(--pine-dimension-2xs)}.pds-select__error-message pds-icon{-webkit-margin-before:var(--pine-dimension-025);margin-block-start:var(--pine-dimension-025)}.pds-select__message{grid-area:message}.pds-select__select-icon{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;grid-column:-1/-2;grid-row:2/3;height:var(--pds-select-min-height);pointer-events:none;position:relative;z-index:var(--pine-z-index-raised)}.visually-hidden{border:0;clip:rect(0 0 0 0);-webkit-clip-path:polygon(0 0, 0 0, 0 0);clip-path:polygon(0 0, 0 0, 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;white-space:nowrap;width:1px}";

const PdsSelect = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.pdsSelectChange = index.createEvent(this, "pdsSelectChange");
        this.pdsBlur = index.createEvent(this, "pdsBlur");
        this.pdsFocus = index.createEvent(this, "pdsFocus");
        this.pdsKeyDown = index.createEvent(this, "pdsKeyDown");
        this._type = 'select-one';
        /**
         * Indicates whether or not the select field is disabled.
         * @defaultValue false
         */
        this.disabled = false;
        /**
         * Indicates whether multiple options can be selected.
         * @defaultValue false
         */
        this.multiple = false;
        /**
         * Indicates whether or not the select field is required.
         * @defaultValue false
         */
        this.required = false;
        /**
         * Emits an event on input change.
        */
        this.onSelectUpdate = (e) => {
            const target = e.target;
            const values = Array.from(target.options)
                .filter((option) => (option.selected))
                .map((option) => (option.value));
            if (values.length === 1 && !this.multiple) {
                this.value = values[0];
            }
            else {
                this.value = values;
            }
            this.pdsSelectChange.emit(e);
        };
        this.onBlur = (ev) => {
            this.pdsBlur.emit(ev);
        };
        this.onFocus = (ev) => {
            this.pdsFocus.emit(ev);
        };
        this.onKeyDown = (ev) => {
            this.pdsKeyDown.emit(ev);
        };
        /**
         * Handles the change event for the slot element.
         * This method is triggered when the slot content changes.
         * It updates the inner HTML of the select element by cloning and appending
         * the assigned <option> elements from the slot.
         */
        this.handleSlotChange = () => {
            const slot = this.slotContainer.querySelector('slot');
            this.selectEl.innerHTML = '';
            const assignedElements = slot.assignedElements({ flatten: true });
            assignedElements.forEach((item) => {
                if (['OPTION', 'OPTGROUP'].includes(item.tagName)) {
                    const clonedItem = item.cloneNode(true);
                    if (clonedItem.tagName === 'OPTION' && clonedItem.value === this.value) {
                        clonedItem.selected = true;
                    }
                    this.selectEl.appendChild(clonedItem);
                }
            });
            this.updateSelectedOption();
        };
    }
    /**
     * Handles the change in the value of the select component.
     * This method is called whenever the value of the select component changes.
     * It updates the selected option accordingly.
     */
    valueChanged() {
        this.updateSelectedOption();
        this.updateFormValue();
    }
    /**
     * Updates the type property when multiple changes to match native select behavior.
     */
    multipleChanged() {
        this.updateType();
    }
    updateType() {
        this._type = this.multiple ? 'select-multiple' : 'select-one';
    }
    connectedCallback() {
        // Initialize ElementInternals for form association (only once per element instance)
        if (this.el.attachInternals && !this.internals) {
            this.internals = this.el.attachInternals();
        }
        // Expose type property on the element instance to match native form element behavior
        form.exposeTypeProperty(this.el, () => this._type);
    }
    componentWillLoad() {
        // Set initial type based on multiple prop
        this.updateType();
        this.updateSelectedOption();
    }
    componentDidLoad() {
        // Set initial form value
        this.updateFormValue();
    }
    /**
     * Updates the selected option in the select element based on the current value.
     *
     * This method iterates through all the options of the select element and sets the
     * 'selected' attribute on the option that matches the current value. If an option
     * does not match the current value, the 'selected' attribute is removed.
     *
     * @private
     * @returns {void}
     */
    updateSelectedOption() {
        if (this.selectEl) {
            const options = this.selectEl.options;
            // Update the selected attribute for all options.
            Array.from(options).map((option) => {
                if (Array.isArray(this.value)) {
                    option.selected = this.value.includes(option.value);
                }
                else {
                    option.selected = this.value === option.value;
                }
            });
        }
    }
    getHelperMessage() {
        return this.helperMessage && (index.h("p", { class: "pds-select__helper-message", id: form.messageId(this.componentId, 'helper') }, this.helperMessage));
    }
    getErrorMessage() {
        return this.errorMessage && (index.h("p", { class: "pds-select__error-message", id: form.messageId(this.componentId, 'error'), "aria-live": "assertive" }, index.h("pds-icon", { icon: index$1.danger, size: "small" }), this.errorMessage));
    }
    renderMessages() {
        if (!this.helperMessage && !this.errorMessage)
            return null;
        return (index.h("div", { class: "pds-select__message" }, this.getHelperMessage(), this.getErrorMessage()));
    }
    classNames() {
        const classNames = [];
        if (this.invalid) {
            classNames.push('is-invalid');
        }
        if (this.disabled) {
            classNames.push('is-disabled');
        }
        return classNames.join('  ');
    }
    renderAction() {
        const hasAction = this.el.querySelector('[slot="action"]') !== null;
        if (hasAction) {
            return (index.h("div", { class: "pds-select__action", part: "action" }, index.h("slot", { name: "action" })));
        }
        return null;
    }
    /**
     * Updates the form value using ElementInternals API
     */
    updateFormValue() {
        if (form.isSpecTest())
            return;
        if (this.internals && this.internals.setFormValue) {
            const value = this.value;
            // Handle multi-select arrays by converting to FormData or comma-separated string
            if (Array.isArray(value)) {
                if (value.length > 1) {
                    // For multiple values, create FormData with multiple entries
                    const formData = new FormData();
                    value.forEach(val => formData.append(this.name || '', val));
                    this.internals.setFormValue(formData);
                }
                else {
                    // Single value in array, use the string value
                    this.internals.setFormValue(value[0] || null);
                }
            }
            else {
                // Single string value
                this.internals.setFormValue(value || null);
            }
            // Set validity based on native select validation
            if (this.selectEl && this.internals && this.internals.setValidity) {
                this.internals.setValidity(this.selectEl.validity, this.selectEl.validationMessage, this.selectEl);
            }
        }
    }
    /**
     * Form Associated Custom Elements API: Called when the form is reset
     */
    formResetCallback() {
        this.value = '';
        this.updateFormValue();
    }
    /**
     * Form Associated Custom Elements API: Called when the form is disabled
     */
    formDisabledCallback(disabled) {
        this.disabled = disabled;
    }
    /**
     * Form Associated Custom Elements API: Called to restore form state
     */
    formStateRestoreCallback(state) {
        if (typeof state === 'string') {
            this.value = state;
        }
        else if (state instanceof FormData && this.name) {
            // Extract value(s) from FormData using the select's name
            const values = state.getAll(this.name);
            if (values.length > 1) {
                // Multi-select: convert to string array
                this.value = values.filter(v => typeof v === 'string');
            }
            else if (values.length === 1 && typeof values[0] === 'string') {
                // Single select: use string value
                this.value = values[0];
            }
        }
    }
    render() {
        const hasAction = this.el.querySelector('[slot="action"]') !== null;
        return (index.h(index.Host, { key: '28292440973cbb60c63a296415a617e05fc9c5ce', "aria-disabled": this.disabled ? 'true' : null, class: this.classNames(), "has-action": hasAction && !this.hideLabel ? 'true' : null }, index.h("div", { key: '4a0f255ecc75c9fcedfc933c0a728d26918d9a9c', class: "pds-select" }, !this.hideLabel && (index.h("div", { key: '1f0b2a9ccf4ce2b79d5bb4dd40ff076b415bc6ac', class: "pds-select__label-wrapper" }, index.h("label", { key: '9e30b1b0266981f73f0821c05e833cb66a3caf3c', htmlFor: this.componentId }, index.h("span", { key: '7790be41907be6c5e3b460aa84b7ea54773cc14d', class: this.hideLabel ? 'visually-hidden' : '' }, this.label)), hasAction && this.renderAction())), index.h("select", { key: 'd66b39ee412bfbf3c6dfff722cb061f24ba82df6', "aria-label": this.hideLabel ? this.label : undefined, autocomplete: this.autocomplete || undefined, class: "pds-select__field", disabled: this.disabled, id: this.componentId, multiple: this.multiple, name: this.name, onBlur: this.onBlur, onChange: this.onSelectUpdate, onFocus: this.onFocus, onKeyDown: this.onKeyDown, part: "select", required: this.required, ref: (el) => (this.selectEl = el) }), index.h("div", { key: 'daf4846494666ebade54249c8d925423e71e7d33', "aria-hidden": "true", class: "hidden", ref: (el) => (this.slotContainer = el) }, index.h("slot", { key: '545f421fd2679d4bb6ee34658f7dd4089ece4f81', onSlotchange: this.handleSlotChange })), this.renderMessages(), !this.multiple && index.h("pds-icon", { key: '0b3bcd3ceee6e6b2ab24b52f16f6cbd89ae88322', class: "pds-select__select-icon", icon: index$1.enlarge }))));
    }
    static get formAssociated() { return true; }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "value": ["valueChanged"],
        "multiple": ["multipleChanged"]
    }; }
};
PdsSelect.style = pdsSelectTokensCss + (labelCss + pdsSelectCss);

exports.pds_select = PdsSelect;
//# sourceMappingURL=pds-select.entry.cjs.js.map
