import { r as registerInstance, c as createEvent, h, H as Host, a as getElement } from './index-B2f84Zog.js';
import { i as isSpecTest, b as isRequired, e as exposeTypeProperty, a as assignDescription, m as messageId } from './form-C3xDZBme.js';
import { d as debounceEvent } from './utils-tJa4KYNO.js';
import { i as inheritAriaAttributes, a as inheritAttributes } from './attributes-C0M1gTKv.js';
import { b as danger } from './index-D4ys0pep.js';

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 pdsInputTokensCss = ":host{--pine-input-color-background-danger:var(--pine-color-red-050)}";

const pdsTextareaCss = ":host{display:inline-block;width:100%}:host([aria-readonly=true]) textarea{background-color:var(--pine-color-background-container-disabled);color:var(--pine-color-text-readonly)}:host([highlight]:not([disabled]):not([aria-disabled=true]):not([aria-readonly=true])) .pds-textarea__field:not(.is-invalid){background-color:var(--pine-color-accent-disabled);border-color:var(--pine-color-accent);color:var(--pine-color-text-accent)}:host([highlight]:not([disabled]):not([aria-disabled=true]):not([aria-readonly=true])) .pds-textarea__field:not(.is-invalid):hover{border-color:var(--pine-color-accent-hover)}:host([highlight]:not([disabled]):not([aria-disabled=true]):not([aria-readonly=true])) .pds-textarea__field:not(.is-invalid):focus-visible{outline-color:var(--pine-color-focus-ring)}:host([highlight]:not([disabled]):not([aria-disabled=true]):not([aria-readonly=true])) .pds-textarea__field:not(.is-invalid)~.pds-textarea__character-counter{background:color-mix(in srgb, var(--pine-color-accent-disabled) 80%, transparent);color:var(--pine-color-text-accent)}.pds-textarea{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.pds-textarea__label-wrapper{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between}.pds-textarea__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{display:block;-webkit-margin-after:var(--pine-dimension-xs);margin-block-end:var(--pine-dimension-xs)}.pds-textarea__label-wrapper label{-webkit-margin-after:0;margin-block-end:0}.pds-textarea__helper-message{color:var(--pine-color-text-message);font:var(--pine-typography-body-sm-medium);-webkit-margin-before:var(--pine-dimension-2xs);margin-block-start:var(--pine-dimension-2xs)}.pds-textarea__error-message{color:var(--pine-color-text-message-danger);display:-ms-flexbox;display:flex;font:var(--pine-typography-body-sm-medium);gap:var(--pine-dimension-2xs);-webkit-margin-before:var(--pine-dimension-2xs);margin-block-start:var(--pine-dimension-2xs)}.pds-textarea__error-message pds-icon{-webkit-margin-before:var(--pine-dimension-025);margin-block-start:var(--pine-dimension-025)}.pds-textarea__field-wrapper{display:inline-block;position:relative;width:100%}.pds-textarea__field{background-color:var(--pine-color-background-container);border:var(--pine-border);border-radius:calc(var(--pine-dimension-xs) * 1.25);-webkit-box-sizing:border-box;box-sizing:border-box;color:var(--pine-color-text);font:var(--pine-typography-body);letter-spacing:var(--pine-letter-spacing);min-height:calc(var(--pine-dimension-xl) * 2);min-width:calc(var(--pine-dimension-xl) * 2);padding:var(--pine-dimension-xs) var(--pine-dimension-sm);resize:both;width:100%}:host([max-length]) .pds-textarea__field{padding-bottom:calc(var(--pine-dimension-xs) + var(--pine-dimension-md))}.pds-textarea__field:hover:not(:disabled,.is-invalid){border:var(--pine-border-hover)}.pds-textarea__field:disabled{background-color:var(--pine-color-background-container-disabled);color:var(--pine-color-text-disabled);cursor:not-allowed}.pds-textarea__field:focus-visible{outline:var(--pine-outline-focus);outline-offset:var(--pine-border-width)}.pds-textarea__field::-webkit-input-placeholder{color:var(--pine-color-text-placeholder)}.pds-textarea__field::-moz-placeholder{color:var(--pine-color-text-placeholder)}.pds-textarea__field:-ms-input-placeholder{color:var(--pine-color-text-placeholder)}.pds-textarea__field::-ms-input-placeholder{color:var(--pine-color-text-placeholder)}.pds-textarea__field::placeholder{color:var(--pine-color-text-placeholder)}.pds-textarea__field.is-invalid{background-color:var(--pine-input-color-background-danger);border-color:var(--pine-color-border-danger)}:host-context([data-theme=dark]) .pds-textarea__field.is-invalid{background-color:var(--pine-color-red-950)}.pds-textarea__field.is-invalid:focus-visible{outline-color:var(--pine-color-focus-ring-danger)}.pds-textarea__character-counter{background:color-mix(in srgb, var(--pine-color-background-container) 80%, transparent);border-radius:calc(var(--pine-dimension-2xs) * 0.5);color:var(--pine-color-text-muted);font:var(--pine-typography-body-sm-medium);padding:calc(var(--pine-dimension-2xs) * 0.5) var(--pine-dimension-2xs);pointer-events:none;position:absolute;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;z-index:var(--pine-z-index)}:host([aria-disabled=true]) .pds-textarea__character-counter{background-color:var(--pine-color-background-container-disabled);color:var(--pine-color-text-disabled)}:host([aria-readonly=true]) .pds-textarea__character-counter{background-color:var(--pine-color-background-container-disabled);color:var(--pine-color-text-readonly)}.pds-textarea__field.is-invalid~.pds-textarea__character-counter{background-color:var(--pine-input-color-background-danger)}:host-context([data-theme=dark]) .pds-textarea__field.is-invalid~.pds-textarea__character-counter{background-color:var(--pine-color-red-950)}.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 PdsTextarea = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.pdsBlur = createEvent(this, "pdsBlur");
        this.pdsFocus = createEvent(this, "pdsFocus");
        this.pdsInput = createEvent(this, "pdsInput");
        this.pdsTextareaChange = createEvent(this, "pdsTextareaChange");
        this.pdsKeyDown = createEvent(this, "pdsKeyDown");
        this.inheritedAttributes = {};
        this._type = 'textarea';
        /**
         * Determines whether or not the textarea is disabled.
         * @defaultValue false
         */
        this.disabled = false;
        /**
         * Determines whether or not the textarea is invalid or throws an error.
         * @defaultValue false
         */
        this.invalid = false; // eslint-disable-line @stencil-community/strict-mutable
        /**
         * Specifies the name. Submitted with the form name/value pair. This value will mirror the componentId.
         */
        this.name = this.componentId;
        /**
         * Determines whether or not the textarea is readonly.
         * @defaultValue false
         */
        this.readonly = false;
        /**
         * Determines whether or not the textarea is required.
         * @defaultValue false
         */
        this.required = false;
        /**
         * The value of the textarea.
         */
        this.value = '';
        this.hasFocus = false;
        /**
         * If true, the textarea has action content in the label area
         */
        this.hasAction = false;
        this.onBlur = (ev) => {
            this.hasFocus = false;
            if (this.focusedValue !== this.value) {
                this.emitValueChange(ev);
            }
            this.pdsBlur.emit(ev);
        };
        this.onFocus = (ev) => {
            this.hasFocus = true;
            this.focusedValue = this.value;
            this.pdsFocus.emit(ev);
        };
        this.onInput = (ev) => {
            const input = ev.target;
            if (input) {
                // Handle maxLength validation
                if (this.maxLength && input.value.length > this.maxLength) {
                    // Prevent input beyond maxLength
                    input.value = input.value.substring(0, this.maxLength);
                }
                this.value = input.value || '';
            }
            this.emitInputChange(ev);
            // Update counter position when content changes
            if (this.maxLength && typeof ResizeObserver !== 'undefined') {
                // Use requestAnimationFrame to ensure DOM is updated
                requestAnimationFrame(() => {
                    this.updateCharacterCounterPosition();
                });
            }
        };
        this.onTextareaChange = (ev) => {
            this.emitValueChange(ev);
        };
        this.onKeyDown = (ev) => {
            this.pdsKeyDown.emit(ev);
        };
    }
    /**
     * Sets focus on the native `textarea` in the `pds-textarea`. Use this method instead of the global
     * `textarea.focus()`.
     */
    async setFocus() {
        if (this.nativeTextarea) {
            this.nativeTextarea.focus();
        }
    }
    debounceChanged() {
        const { pdsInput, debounce, originalPdsInput } = this;
        this.pdsInput = debounce === undefined ? originalPdsInput !== null && originalPdsInput !== void 0 ? originalPdsInput : pdsInput : debounceEvent(pdsInput, debounce);
    }
    /**
     * Update the native input element when the value changes
     */
    valueChanged() {
        const nativeTextarea = this.nativeTextarea;
        const value = this.getValue();
        if (nativeTextarea && nativeTextarea.value !== value) {
            nativeTextarea.value = value;
        }
        // Update form value for Form Associated Custom Elements API
        this.updateFormValue();
        // Update character counter position in case content changes affect sizing
        if (this.maxLength && typeof ResizeObserver !== 'undefined') {
            this.updateCharacterCounterPosition();
        }
    }
    maxLengthChanged() {
        // Setup or teardown ResizeObserver based on maxLength
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
        if (this.maxLength && this.nativeTextarea) {
            this.setupResizeObserver();
        }
        // Update ElementInternals validity when maxLength changes
        if (!isSpecTest() && this.internals && this.internals.setValidity && this.nativeTextarea) {
            const isTooLong = this.nativeTextarea.value.length > (this.maxLength || 0);
            this.internals.setValidity({ tooLong: isTooLong }, isTooLong ? 'Value exceeds maxLength' : '', this.nativeTextarea);
        }
    }
    /**
     * Emits an `pdsInput` event.
     */
    emitInputChange(event) {
        const { value } = this;
        this.pdsInput.emit({ value, event });
    }
    /**
     * Emits an `pdsTextareaChange` event.
     */
    emitValueChange(event) {
        const textarea = event.target;
        isRequired(textarea, this);
        const { value } = textarea;
        // Checks for both null and undefined values
        const newValue = value == null ? value : value.toString();
        this.focusedValue = newValue;
        this.pdsTextareaChange.emit({ value: newValue, event });
    }
    getValue() {
        return this.value || '';
    }
    textareaClassNames() {
        const classNames = ['pds-textarea__field'];
        if (this.invalid && this.invalid === true) {
            classNames.push('is-invalid');
        }
        return classNames.join('  ');
    }
    connectedCallback() {
        this.debounceChanged();
        // Initialize ElementInternals for form association (only once per element instance)
        if (this.el.attachInternals && !this.internals) {
            this.internals = this.el.attachInternals();
        }
    }
    disconnectedCallback() {
        // Clean up ResizeObserver
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
    }
    componentWillLoad() {
        this.inheritedAttributes = Object.assign(Object.assign({}, inheritAriaAttributes(this.el)), inheritAttributes(this.el));
        this.hasAction = this.el.querySelector('[slot="action"]') !== null;
    }
    componentDidLoad() {
        this.originalPdsInput = this.pdsInput;
        // Set initial form value
        this.updateFormValue();
        // Setup ResizeObserver for character counter positioning
        this.setupResizeObserver();
        // Expose type property on the element instance to match native form element behavior
        exposeTypeProperty(this.el, () => this._type);
    }
    /**
     * Sets up ResizeObserver to track textarea resize for character counter positioning
     */
    setupResizeObserver() {
        if (!this.maxLength || !this.nativeTextarea)
            return;
        // ResizeObserver may not be available in test environments
        if (typeof ResizeObserver !== 'undefined') {
            this.resizeObserver = new ResizeObserver(() => {
                // Use requestAnimationFrame to ensure DOM updates are complete
                requestAnimationFrame(() => {
                    this.updateCharacterCounterPosition();
                });
            });
            this.resizeObserver.observe(this.nativeTextarea);
            // Initial positioning with a small delay to ensure counter is rendered
            requestAnimationFrame(() => {
                this.updateCharacterCounterPosition();
            });
        }
    }
    /**
     * Updates character counter position to stay within textarea boundaries during resize
     */
    updateCharacterCounterPosition() {
        if (!this.characterCounter || !this.nativeTextarea)
            return;
        // Skip positioning in test environments where ResizeObserver isn't available
        if (typeof ResizeObserver === 'undefined')
            return;
        // Ensure the character counter has been rendered and has dimensions
        if (this.characterCounter.offsetWidth === 0 || this.characterCounter.offsetHeight === 0) {
            // Counter not ready or component hidden - return and let resize/input observers handle positioning later
            return;
        }
        // Position based on textarea's actual dimensions (which change during manual resize)
        const textareaWidth = this.nativeTextarea.offsetWidth;
        const textareaHeight = this.nativeTextarea.offsetHeight;
        const counterWidth = this.characterCounter.offsetWidth;
        const counterHeight = this.characterCounter.offsetHeight;
        // Calculate position within textarea boundaries with padding from edges
        const rightPosition = textareaWidth - counterWidth - 8;
        const bottomPosition = textareaHeight - counterHeight - 8;
        // Ensure counter stays within textarea boundaries even when resized very small
        const finalLeft = Math.max(8, Math.min(rightPosition, textareaWidth - counterWidth - 8));
        const finalTop = Math.max(8, Math.min(bottomPosition, textareaHeight - counterHeight - 8));
        // Apply absolute positioning within the field wrapper
        this.characterCounter.style.position = 'absolute';
        this.characterCounter.style.left = `${finalLeft}px`;
        this.characterCounter.style.top = `${finalTop}px`;
        this.characterCounter.style.right = 'auto';
        this.characterCounter.style.bottom = 'auto';
    }
    /**
     * Renders the character counter when maxLength is set
     */
    renderCharacterCounter() {
        if (!this.maxLength) {
            return null;
        }
        const currentLength = this.getValue().length;
        return (h("div", { class: "pds-textarea__character-counter", ref: (el) => this.characterCounter = el, role: "status", "aria-live": "polite", "aria-label": `${currentLength} of ${this.maxLength} characters` }, currentLength, " / ", this.maxLength));
    }
    renderAction() {
        const hasAction = this.el.querySelector('[slot="action"]') !== null;
        if (hasAction) {
            return (h("div", { class: "pds-textarea__action", part: "action" }, h("slot", { name: "action" })));
        }
        return null;
    }
    /**
     * Updates the form value using ElementInternals API
     */
    updateFormValue() {
        if (isSpecTest())
            return;
        if (this.internals && this.internals.setFormValue) {
            const value = this.getValue();
            this.internals.setFormValue(value || null);
            // Set validity based on native textarea validation
            if (this.nativeTextarea && this.internals && this.internals.setValidity) {
                this.internals.setValidity(this.nativeTextarea.validity, this.nativeTextarea.validationMessage, this.nativeTextarea);
            }
        }
    }
    /**
     * 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 from FormData using the textarea's name
            const value = state.get(this.name);
            if (typeof value === 'string') {
                this.value = value;
            }
        }
    }
    render() {
        const value = this.getValue();
        return (h(Host, { key: '09726ef6454fe84a5c8d0ea25c6e8a7a6da128f9', "aria-disabled": this.disabled ? 'true' : null, "aria-readonly": this.readonly ? 'true' : null, "has-action": this.hasAction && !this.hideLabel ? 'true' : null }, h("div", { key: '6244104f11d26b25a908fbaf13a815988a3c33d9', class: "pds-textarea" }, this.label &&
            h("div", { key: '5dd7f6caedd7ebf5ecaacf8d111ec5e2426e84ae', class: "pds-textarea__label-wrapper" }, h("label", { key: 'd19f62cd28612423abf0d5696ff1cd88f39d32fe', htmlFor: this.componentId }, h("span", { key: '37f4e9e34ae3205bafa5f1bc8574a98d3a90060d', class: this.hideLabel ? 'visually-hidden' : '' }, this.label)), !this.hideLabel && this.renderAction()), h("div", { key: '4c3c8fadc5596630485ee1775f5d87d77c11d95b', class: "pds-textarea__field-wrapper" }, h("textarea", Object.assign({ key: 'a60be5f3d362cb9bcd2ecf5af16ffc467fc8322a', ref: (el) => this.nativeTextarea = el, "aria-describedby": assignDescription(this.componentId, this.invalid, this.helperMessage), "aria-invalid": this.invalid ? "true" : undefined, autocomplete: this.autocomplete, class: this.textareaClassNames(), disabled: this.disabled, id: this.componentId, maxlength: this.maxLength, name: this.name, placeholder: this.placeholder, readOnly: this.readonly, required: this.required, rows: this.rows, onBlur: this.onBlur, onChange: this.onTextareaChange, onFocus: this.onFocus, onInput: this.onInput, onKeyDown: this.onKeyDown }, this.inheritedAttributes), value), this.renderCharacterCounter()), this.helperMessage &&
            h("p", { key: 'ae03337ef85ac2a3995e967fe671e0ad2c352710', class: "pds-textarea__helper-message", id: messageId(this.componentId, 'helper') }, this.helperMessage), this.invalid &&
            h("p", { key: 'a2bda9a477e7d2b81862833da43158a626d8cc6f', "aria-live": "assertive", class: "pds-textarea__error-message", id: messageId(this.componentId, 'error') }, h("pds-icon", { key: '5ac785e8012aeb49dd0b1c5823233671531b0a7a', icon: danger, size: "small" }), this.errorMessage))));
    }
    static get formAssociated() { return true; }
    get el() { return getElement(this); }
    static get watchers() { return {
        "debounce": ["debounceChanged"],
        "value": ["valueChanged"],
        "maxLength": ["maxLengthChanged"]
    }; }
};
PdsTextarea.style = labelCss + (pdsInputTokensCss + pdsTextareaCss);

export { PdsTextarea as pds_textarea };
//# sourceMappingURL=pds-textarea.entry.js.map
