import { h, } from "@stencil/core";
import { isNestedInIfxComponent } from "../..//shared/utils/dom-utils";
import { detectFramework } from "../..//shared/utils/framework-detection";
import { trackComponent } from "../../shared/utils/tracking";
export class RadioButton {
    el;
    /** If true, the checkbox is disabled and not interactive. */
    disabled = false;
    /** Value submitted when the checkbox is checked. */
    value;
    /** If true, the checkbox is shown in an error state. */
    error = false;
    /** Size of the checkbox (small or medium). */
    size = "s";
    /** Name attribute used when submitting the checkbox in a form. */
    name;
    /** Whether the checkbox is currently checked (can be updated). */
    checked;
    internalChecked = false;
    hasSlot = false;
    /** Returns the current checked state of the checkbox. */
    async isChecked() {
        return this.internalChecked;
    }
    inputElement;
    //private internals: ElementInternals;
    fallbackInput;
    /** Fired when the checked state of the checkbox changes. */
    ifxChange;
    /** Fired when the checkbox enters or leaves an error state. */
    ifxError;
    componentWillLoad() {
        // Fallback for form association
        this.fallbackInput = document.createElement("input");
        this.fallbackInput.type = "radio";
        this.fallbackInput.hidden = true;
        this.fallbackInput.className = "_ifx-radiobutton-fallback";
        this.fallbackInput.style.cssText = `
      display: none !important;
      position: absolute !important;
      opacity: 0 !important;
      pointer-events: none !important;
      width: 0 !important;
      height: 0 !important;
    `;
        this.fallbackInput.setAttribute("aria-hidden", "true");
        this.fallbackInput.tabIndex = -1;
        this.el.appendChild(this.fallbackInput);
        // Initialize ElementInternals if supported
        if ("attachInternals" in HTMLElement.prototype) {
            try {
                //this.internals = this.el.attachInternals();
            }
            catch (e) {
                console.warn("ElementInternals not supported");
            }
        }
        // Initial state
        this.internalChecked = this.checked || false;
        this.hasSlot =
            !!this.el.querySelector("[slot]") || this.el.innerHTML.trim() !== "";
    }
    async componentDidLoad() {
        if (!isNestedInIfxComponent(this.el)) {
            const framework = detectFramework();
            trackComponent("ifx-radio-button", await framework);
        }
    }
    handleCheckedChange(newValue) {
        this.internalChecked = newValue;
    }
    updateFormValue() {
        // Update both ElementInternals and fallback input
        // if (this.internals?.setFormValue) {
        //   this.internals.setFormValue(this.internalChecked ? this.value : null);
        // }
        this.fallbackInput.checked = this.internalChecked;
        this.fallbackInput.name = this.name;
        this.fallbackInput.value = this.value;
        this.fallbackInput.disabled = this.disabled;
    }
    errorChanged(newValue, oldValue) {
        if (newValue !== oldValue) {
            this.ifxError.emit(newValue);
        }
    }
    handleRadioButtonClick(event) {
        if (this.disabled) {
            event.stopPropagation();
            return;
        }
        this.inputElement.click();
        this.internalChecked = this.inputElement.checked;
        this.checked = this.internalChecked;
        this.ifxChange.emit(this.internalChecked);
        const changeEvent = new CustomEvent("change", {
            bubbles: true,
            composed: true,
            detail: { checked: this.internalChecked },
        });
        this.el.dispatchEvent(changeEvent);
    }
    handleKeyDown(ev) {
        if ([" ", "Enter"].includes(ev.key)) {
            ev.preventDefault();
            this.handleRadioButtonClick(new PointerEvent("click"));
        }
    }
    handleExternalChange(event) {
        const target = event.target;
        if (target === this.el ||
            target.tagName.toLowerCase() !== "ifx-radio-button")
            return;
        if (target.getAttribute("name") === this.name) {
            this.internalChecked = false;
        }
    }
    render() {
        return (h("div", { key: 'd64218e469694c2dfb4e62840dcdea1a215a3312', role: "radio", "aria-checked": String(this.internalChecked), "aria-disabled": String(this.disabled), class: `radioButton__container ${this.size} ${this.disabled ? "disabled" : ""}`, onClick: (e) => this.handleRadioButtonClick(e), tabindex: this.disabled ? -1 : 0 }, h("div", { key: 'b4177bda89e18d2a7ab95b3ba99b98aaf8f0355e', class: `radioButton__wrapper 
            ${this.internalChecked ? "checked" : ""}  
            ${this.error ? "error" : ""}` }, this.internalChecked && (h("div", { key: 'ec6c98b74456c88378a0abd5e78ee734ef17a716', class: "radioButton__wrapper-mark" }))), this.hasSlot && (h("div", { key: '76d20887fdff454f2706f5374a83958c9d119f58', class: `label ${this.size === "m" ? "label-m" : ""}` }, h("slot", { key: '9775c637065e4ca7a75eba439cda4cf97b953a86' }))), h("input", { key: '87534ecb30c2c06b58784c719ae9c2b106859238', type: "radio", hidden: true, ref: (el) => (this.inputElement = el), name: this.name, value: this.value, checked: this.internalChecked, disabled: this.disabled, onClick: (e) => e.stopPropagation() })));
    }
    static get is() { return "ifx-radio-button"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["radio-button.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["radio-button.css"]
        };
    }
    static get properties() {
        return {
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If true, the checkbox is disabled and not interactive."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "false"
            },
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Value submitted when the checkbox is checked."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "error": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If true, the checkbox is shown in an error state."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "error",
                "defaultValue": "false"
            },
            "size": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "\"s\" | \"m\"",
                    "resolved": "\"m\" | \"s\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Size of the checkbox (small or medium)."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "size",
                "defaultValue": "\"s\""
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Name attribute used when submitting the checkbox in a form."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "name"
            },
            "checked": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether the checkbox is currently checked (can be updated)."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "checked"
            }
        };
    }
    static get states() {
        return {
            "internalChecked": {},
            "hasSlot": {}
        };
    }
    static get events() {
        return [{
                "method": "ifxChange",
                "name": "ifxChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Fired when the checked state of the checkbox changes."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "ifxError",
                "name": "ifxError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Fired when the checkbox enters or leaves an error state."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "isChecked": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "Returns the current checked state of the checkbox.",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "checked",
                "methodName": "handleCheckedChange"
            }, {
                "propName": "internalChecked",
                "methodName": "updateFormValue"
            }, {
                "propName": "error",
                "methodName": "errorChanged"
            }];
    }
    static get listeners() {
        return [{
                "name": "keydown",
                "method": "handleKeyDown",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "change",
                "method": "handleExternalChange",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
