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 { LitElement, html, nothing } from 'lit';
import { property } from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { EventEmitterMixin } from '../../util/EventEmitterMixin.js';
import { ReadyMixin } from '../../util/ReadyMixin.js';
import '../icon/Icon.js';
/**
 * A checkbox component for selecting one or more options from a set.
 *
 * Uses a hidden native checkbox internally for accessibility and form
 * participation. Styled via the `btu-checkbox` Tailwind plugin classes.
 * The component manages its own `className` — do not modify it externally
 * after initialization (classes present at connection time are preserved).
 *
 * @element btu-checkbox
 *
 * @fires {CustomEvent} btu-checkbox-ready - Fired after the checkbox is first rendered and initialized
 * @fires {CustomEvent<{ checked: boolean }>} btu-checkbox-change - Fired when the user toggles the checked state
 *
 * @cssprop --checkbox-color-primary - Background and border color when checked or indeterminate, and tinted background/border on unchecked hover (default: oklch(var(--btu-theme-primary-700)))
 * @cssprop --checkbox-color-border - Border color in the unchecked state (default: oklch(var(--btu-theme-gray-300)))
 * @cssprop --checkbox-color-error - Border and text color in the error state (default: oklch(var(--btu-theme-error-600)))
 * @cssprop --checkbox-border-radius - Corner rounding of the checkbox square (default: 4px)
 * @cssprop --checkbox-label-spacing - Distance between the checkbox and the label (default: 0.75rem)
 * @cssprop --checkbox-box-size - [Internal] Width and height of the checkbox square, set by the size variant (sm: 1rem, md: 1.25rem). Use the `size` attribute instead of overriding directly — the icon must scale in tandem.
 * @cssprop --checkbox-icon-size - [Internal] Width and height of the icon inside the box, set by the size variant (sm: 0.75rem, md: 0.875rem). Use the `size` attribute instead of overriding directly.
 */
export default class Checkbox extends EventEmitterMixin(ReadyMixin(LitElement)) {
    constructor() {
        super(...arguments);
        /**
         * Controls the scale of the checkbox and associated typography.
         * @attr
         */
        this.size = 'sm';
        /**
         * Whether the checkbox is currently selected.
         * @attr
         */
        this.checked = false;
        /**
         * Whether the checkbox is in a partially selected state. Sets `aria-checked='mixed'`
         * and activates the native `:indeterminate` pseudo-class. Cleared automatically when
         * the user clicks the checkbox.
         * @attr
         */
        this.indeterminate = false;
        /**
         * If true, the checkbox is non-interactive and visually muted.
         * @attr
         */
        this.disabled = false;
        /**
         * If true, displays error styling on the checkbox.
         * @attr
         */
        this.invalid = false;
        /**
         * Marks the field as mandatory for form submission.
         * @attr
         */
        this.required = false;
        /**
         * Value associated with the checkbox when submitted.
         * @attr
         */
        this.value = 'on';
        this._userInitiated = false;
        this._initialClasses = [];
        this._initialClassesCaptured = false;
        this._descId = `checkbox-desc-${crypto.randomUUID()}`;
        this._errorId = `checkbox-error-${crypto.randomUUID()}`;
        this._handleClick = (e) => {
            if (this.disabled)
                return;
            // input.click() fires a synthetic click that bubbles back here — skip it
            if (e.target.closest('.btu-checkbox-input'))
                return;
            this.renderRoot.querySelector('.btu-checkbox-input')?.click();
        };
    }
    connectedCallback() {
        super.connectedCallback();
        if (!this._initialClassesCaptured && this.className) {
            this._initialClasses = this.className.split(' ').filter(c => c.trim());
            this._initialClassesCaptured = true;
        }
        this.addEventListener('click', this._handleClick);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('click', this._handleClick);
    }
    createRenderRoot() {
        return this;
    }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        const classes = [
            ...this._initialClasses,
            'btu-checkbox',
            this.size === 'md' && 'btu-checkbox-md',
            (this.invalid || this.error) && 'btu-checkbox-invalid',
        ];
        this.className = classes.filter(Boolean).join(' ');
    }
    firstUpdated(changedProperties) {
        super.firstUpdated(changedProperties);
        this.emit('btu-checkbox-ready');
    }
    updated(changedProperties) {
        super.updated(changedProperties);
        // Sync indeterminate to the native input (it's a property, not an attribute)
        const input = this.renderRoot.querySelector('.btu-checkbox-input');
        if (input) {
            input.indeterminate = this.indeterminate;
        }
        if (!this._userInitiated)
            return;
        this._userInitiated = false;
        if (changedProperties.has('checked')) {
            this.emit('btu-checkbox-change', { checked: this.checked });
        }
    }
    _onInputChange(e) {
        const input = e.target;
        this._userInitiated = true;
        this.checked = input.checked;
        // Mirror native behavior: clicking an indeterminate checkbox clears the state
        if (this.indeterminate) {
            this.indeterminate = false;
        }
    }
    get _describedBy() {
        const ids = [];
        if (this.description)
            ids.push(this._descId);
        if (this.error)
            ids.push(this._errorId);
        return ids.length ? ids.join(' ') : undefined;
    }
    get _iconSymbol() {
        return this.indeterminate ? 'minus' : 'check';
    }
    render() {
        return html `
      <input
        type="checkbox"
        class="btu-checkbox-input"
        .checked=${this.checked}
        ?disabled=${this.disabled}
        ?required=${this.required}
        name=${ifDefined(this.name)}
        value=${this.value}
        aria-checked=${ifDefined(this.indeterminate ? 'mixed' : undefined)}
        aria-label=${ifDefined(this.label)}
        aria-describedby=${ifDefined(this._describedBy)}
        aria-invalid=${ifDefined(this.invalid || this.error ? 'true' : undefined)}
        @change=${this._onInputChange}
      />
      <span class="btu-checkbox-box">
        <btu-icon
          class="btu-checkbox-icon"
          symbol=${this._iconSymbol}
          style="--icon-size: var(--checkbox-icon-size)"
        ></btu-icon>
      </span>
      ${this.label || this.description || this.error
            ? html `
            <span class="btu-checkbox-text">
              ${this.label ? html `<span class="btu-checkbox-label">${this.label}</span>` : nothing}
              ${this.description
                ? html `<span id=${this._descId} class="btu-checkbox-description">${this.description}</span>`
                : nothing}
              ${this.error ? html `<span id=${this._errorId} class="btu-checkbox-error">${this.error}</span>` : nothing}
            </span>
          `
            : nothing}
    `;
    }
}
__decorate([
    property()
], Checkbox.prototype, "label", void 0);
__decorate([
    property()
], Checkbox.prototype, "description", void 0);
__decorate([
    property({ reflect: true })
], Checkbox.prototype, "size", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Checkbox.prototype, "checked", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Checkbox.prototype, "indeterminate", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Checkbox.prototype, "disabled", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Checkbox.prototype, "invalid", void 0);
__decorate([
    property()
], Checkbox.prototype, "error", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Checkbox.prototype, "required", void 0);
__decorate([
    property()
], Checkbox.prototype, "name", void 0);
__decorate([
    property()
], Checkbox.prototype, "value", void 0);
if (!customElements.get('btu-checkbox')) {
    customElements.define('btu-checkbox', Checkbox);
}
//# sourceMappingURL=Checkbox.js.map