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;
};
import { MelodicComponent } from '@melodicdev/core';
import { formFieldTemplate } from './form-field.template.js';
import { formFieldStyles } from './form-field.styles.js';
/**
 * ml-form-field - Wrapper component that adds label, hint, and error to any form control
 *
 * @example
 * ```html
 * <ml-form-field label="Username" hint="Choose a unique username" required>
 *   <input type="text" />
 * </ml-form-field>
 *
 * <ml-form-field label="Email" error="Invalid email address">
 *   <input type="email" />
 * </ml-form-field>
 *
 * <ml-form-field label="Agree to terms" orientation="horizontal">
 *   <ml-checkbox></ml-checkbox>
 * </ml-form-field>
 * ```
 *
 * @slot default - The form control element
 */
let FormFieldComponent = class FormFieldComponent {
    constructor() {
        /** Label text */
        this.label = '';
        /** Hint text shown below the control */
        this.hint = '';
        /** Error message (shows error state when set) */
        this.error = '';
        /** Field size */
        this.size = 'md';
        /** Layout orientation */
        this.orientation = 'vertical';
        /** Disabled state */
        this.disabled = false;
        /** Required field indicator */
        this.required = false;
        /** Unique ID for connecting label to control */
        this._fieldId = `ml-form-field-${Math.random().toString(36).slice(2, 9)}`;
        this.handleSlotChange = () => {
            this.connectSlottedControl();
        };
    }
    get fieldId() {
        return this._fieldId;
    }
    get hintId() {
        return `${this._fieldId}-hint`;
    }
    get errorId() {
        return `${this._fieldId}-error`;
    }
    get describedBy() {
        if (this.error)
            return this.errorId;
        if (this.hint)
            return this.hintId;
        return '';
    }
    onCreate() {
        this.connectSlottedControl();
    }
    connectSlottedControl() {
        const slot = this.elementRef.shadowRoot?.querySelector('slot:not([name])');
        if (!slot)
            return;
        const elements = slot.assignedElements({ flatten: true });
        const control = this.findFormControl(elements);
        if (control) {
            // Set ID if not present
            if (!control.id) {
                control.id = this.fieldId;
            }
            // Connect aria-describedby for hint/error
            if (this.describedBy) {
                control.setAttribute('aria-describedby', this.describedBy);
            }
            // Set aria-invalid for error state
            if (this.error) {
                control.setAttribute('aria-invalid', 'true');
            }
            else {
                control.removeAttribute('aria-invalid');
            }
            // Set aria-required
            if (this.required) {
                control.setAttribute('aria-required', 'true');
            }
            // Set disabled if applicable
            if (this.disabled && 'disabled' in control) {
                control.disabled = true;
            }
        }
    }
    findFormControl(elements) {
        for (const element of elements) {
            // Check if it's a native form control
            if (element instanceof HTMLInputElement ||
                element instanceof HTMLSelectElement ||
                element instanceof HTMLTextAreaElement) {
                return element;
            }
            // Check if it's a custom element form control (has role or is focusable)
            if (element instanceof HTMLElement) {
                const role = element.getAttribute('role');
                if (role === 'textbox' ||
                    role === 'combobox' ||
                    role === 'checkbox' ||
                    role === 'radio' ||
                    role === 'switch' ||
                    role === 'slider') {
                    return element;
                }
                // Check for Melodic components
                if (element.tagName.toLowerCase().startsWith('ml-')) {
                    return element;
                }
            }
            // Recursively check children
            const nested = this.findFormControl(Array.from(element.children));
            if (nested)
                return nested;
        }
        return null;
    }
};
FormFieldComponent = __decorate([
    MelodicComponent({
        selector: 'ml-form-field',
        template: formFieldTemplate,
        styles: formFieldStyles,
        attributes: ['label', 'hint', 'error', 'size', 'orientation', 'disabled', 'required']
    })
], FormFieldComponent);
export { FormFieldComponent };
