import { n as d, C as f } from "../chunks/lib-cortex-element.CVMmyPMC.js";
import { c as g } from "../chunks/component.styles.CRO4Odto.js";
import { f as y } from "../chunks/form-control.styles.CaGWmeAS.js";
import { c as v } from "../chunks/custom-element.L4WJXn1j.js";
import { d as x } from "../chunks/default-value.COZopaet.js";
import { F as b, c as C, a as w, v as R } from "../chunks/form.Ch1cwYzO.js";
import { H as V } from "../chunks/slot.j5oheLJC.js";
import { w as h } from "../chunks/watch.BCJD77bD.js";
import { i as E, x as u } from "../chunks/lit-element.jLBm65_O.js";
import { r as p } from "../chunks/state.CSDxrqLd.js";
import { e as m } from "../chunks/query.BBf1UFkC.js";
import { e as c } from "../chunks/class-map.BiVq-cVR.js";
import { o as _ } from "../chunks/style-map.llVFPd__.js";
import A from "./button-group.js";
const M = E`:host{--radio-group-gap:var(--cx-spacing-x-small);display:block}.form-control{border:none;margin:0;padding:0;position:relative}.form-control__label{padding:0}.radio-group{align-items:flex-start;gap:var(--radio-group-gap);flex-direction:column;display:flex}.radio-group--compact{--radio-group-gap:0px}.radio-group--horizontal{flex-flow:wrap;align-items:stretch}.radio-group--horizontal slot::slotted(cx-radio-card){flex-basis:calc(100% / var(--radio-group-columns) - var(--radio-group-gap) / var(--radio-group-columns) * (var(--radio-group-columns) - 1))}.radio-group--horizontal.radio-group--filled slot::slotted(cx-radio-card){flex-basis:auto}.radio-group--required .radio-group__label:after{content:var(--cx-input-required-content);margin-inline-start:var(--cx-input-required-content-offset)}.visually-hidden{clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}`;
var k = Object.defineProperty, S = Object.getOwnPropertyDescriptor, i = (e, t, s, a) => {
  for (var r = a > 1 ? void 0 : a ? S(t, s) : t, l = e.length - 1, n; l >= 0; l--)
    (n = e[l]) && (r = (a ? n(t, s, r) : n(r)) || r);
  return a && r && k(t, s, r), r;
};
let o = class extends f {
  constructor() {
    super(...arguments), this.formControlController = new b(this), this.hasSlotController = new V(
      this,
      "help-text",
      "label"
    ), this.customValidityMessage = "", this.hasButtonGroup = !1, this.errorMessage = "", this.label = "", this.helpText = "", this.name = "option", this.value = "", this.defaultValue = this.value, this.size = "medium", this.form = void 0, this.required = !1, this.horizontal = !1, this.compact = !1, this.itemsPerRow = 0;
  }
  /** Gets the validity state object */
  get validity() {
    const e = this.required && !this.value;
    return this.customValidityMessage !== "" ? C : e ? w : R;
  }
  /** Gets the validation message */
  get validationMessage() {
    const e = this.required && !this.value;
    return this.customValidityMessage !== "" ? this.customValidityMessage : e ? this.validationInput.validationMessage : "";
  }
  runFirstUpdated() {
    this.formControlController.updateValidity();
  }
  getAllRadios() {
    return [
      ...this.querySelectorAll(
        "cx-radio, cx-radio-button, cx-radio-card"
      )
    ];
  }
  handleRadioClick(e) {
    const t = e.target.closest("cx-radio, cx-radio-button, cx-radio-card"), s = this.getAllRadios(), a = this.value;
    !t || t.disabled || (this.value = t.value, s.forEach((r) => r.checked = r === t), this.value !== a && (this.emit("cx-change"), this.emit("cx-input")));
  }
  handleKeyDown(e) {
    if (!["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "].includes(
      e.key
    ))
      return;
    const t = this.getAllRadios().filter((n) => !n.disabled), s = t.find((n) => n.checked) ?? t[0], a = e.key === " " ? 0 : ["ArrowUp", "ArrowLeft"].includes(e.key) ? -1 : 1, r = this.value;
    let l = t.indexOf(s) + a;
    l < 0 && (l = t.length - 1), l > t.length - 1 && (l = 0), this.getAllRadios().forEach((n) => {
      n.checked = !1, this.hasButtonGroup || n.setAttribute("tabindex", "-1");
    }), this.value = t[l].value, t[l].checked = !0, this.hasButtonGroup ? t[l].shadowRoot.querySelector("button").focus() : (t[l].setAttribute("tabindex", "0"), t[l].focus()), this.value !== r && (this.emit("cx-change"), this.emit("cx-input")), e.preventDefault();
  }
  handleLabelClick() {
    const e = this.getAllRadios(), s = e.find((a) => a.checked) || e[0];
    s && s.focus();
  }
  handleInvalid(e) {
    this.formControlController.setValidity(!1), this.formControlController.emitInvalidEvent(e);
  }
  async syncRadioElements() {
    const e = this.getAllRadios();
    if (await Promise.all(
      // Sync the checked state and size
      e.map(async (t) => {
        await t.updateComplete, t.checked = t.value === this.value, t.tagName.toLowerCase() !== "cx-radio-card" && (t.size = this.size);
      })
    ), this.hasButtonGroup = e.some(
      (t) => t.tagName.toLowerCase() === "cx-radio-button"
    ), e.length > 0 && !e.some((t) => t.checked))
      if (this.hasButtonGroup) {
        const t = e[0].shadowRoot?.querySelector("button");
        t && t.setAttribute("tabindex", "0");
      } else
        e[0].setAttribute("tabindex", "0");
    if (this.hasButtonGroup) {
      const t = this.shadowRoot?.querySelector("cx-button-group");
      t && (t.disableRole = !0);
    }
  }
  syncRadios() {
    if (customElements.get("cx-radio") || customElements.get("cx-radio-button") || customElements.get("cx-radio-card")) {
      this.syncRadioElements();
      return;
    }
    customElements.get("cx-radio") ? this.syncRadioElements() : customElements.whenDefined("cx-radio").then(() => this.syncRadios()), customElements.get("cx-radio-button") ? this.syncRadioElements() : customElements.whenDefined("cx-radio-button").then(() => this.syncRadios()), customElements.get("cx-radio-card") ? this.syncRadioElements() : customElements.whenDefined("cx-radio-card").then(() => this.syncRadios());
  }
  updateCheckedRadio() {
    this.getAllRadios().forEach((t) => t.checked = t.value === this.value), this.formControlController.setValidity(this.validity.valid);
  }
  handleSizeChange() {
    this.syncRadios();
  }
  handleValueChange() {
    this.hasUpdated && this.updateCheckedRadio();
  }
  /** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
  checkValidity() {
    const e = this.required && !this.value, t = this.customValidityMessage !== "";
    return e || t ? (this.formControlController.emitInvalidEvent(), !1) : !0;
  }
  /** Gets the associated form, if one exists. */
  getForm() {
    return this.formControlController.getForm();
  }
  /** Checks for validity and shows the browser's validation message if the control is invalid. */
  reportValidity() {
    const e = this.validity.valid;
    return this.errorMessage = this.customValidityMessage || e ? "" : this.validationInput.validationMessage, this.formControlController.setValidity(e), this.validationInput.hidden = !0, clearTimeout(this.validationTimeout), e || (this.validationInput.hidden = !1, this.validationInput.reportValidity(), this.validationTimeout = setTimeout(
      () => this.validationInput.hidden = !0,
      1e4
    )), e;
  }
  /** Sets a custom validation message. Pass an empty string to restore validity. */
  setCustomValidity(e = "") {
    this.customValidityMessage = e, this.errorMessage = e, this.validationInput.setCustomValidity(e), this.formControlController.updateValidity();
  }
  render() {
    const e = this.hasSlotController.test("label"), t = this.hasSlotController.test("help-text"), s = this.label ? !0 : !!e, a = this.helpText ? !0 : !!t, r = u`<slot @slotchange=${this.syncRadios} @click=${this.handleRadioClick} @keydown=${this.handleKeyDown}></slot>`;
    return u`<fieldset part="form-control" class=${c({
      "form-control": !0,
      "form-control--has-help-text": a,
      "form-control--has-label": s,
      "form-control--large": this.size === "large",
      "form-control--medium": this.size === "medium",
      "form-control--radio-group": !0,
      "form-control--small": this.size === "small"
    })} role="radiogroup" aria-labelledby="label" aria-describedby="help-text" aria-errormessage="error-message"><label part="form-control-label" id="label" class="form-control__label" aria-hidden=${s ? "false" : "true"} @click=${this.handleLabelClick}><slot name="label">${this.label}</slot></label><div part="form-control-input" class="form-control-input"><div class="visually-hidden"><div id="error-message" aria-live="assertive">${this.errorMessage}</div><label class="radio-group__validation"><input type="text" class="radio-group__validation-input" ?required=${this.required} tabindex="-1" hidden @invalid=${this.handleInvalid}></label></div>${this.hasButtonGroup ? u`<cx-button-group part="button-group" exportparts="base:button-group__base" role="presentation">${r}</cx-button-group>` : u`<div role="radiogroup" class=${c({
      "radio-group": !0,
      "radio-group--compact": this.compact,
      "radio-group--filled": this.itemsPerRow < 1,
      "radio-group--horizontal": this.horizontal
    })} style=${_({
      "--radio-group-columns": this.itemsPerRow
    })}>${r}</div>`}</div><div part="form-control-help-text" id="help-text" class="form-control__help-text" aria-hidden=${a ? "false" : "true"}><slot name="help-text">${this.helpText}</slot></div></fieldset>`;
  }
};
o.styles = [
  g,
  y,
  M
];
o.dependencies = { "cx-button-group": A };
i([
  m("slot:not([name])")
], o.prototype, "defaultSlot", 2);
i([
  m(".radio-group__validation-input")
], o.prototype, "validationInput", 2);
i([
  p()
], o.prototype, "hasButtonGroup", 2);
i([
  p()
], o.prototype, "errorMessage", 2);
i([
  d()
], o.prototype, "label", 2);
i([
  d({ attribute: "help-text" })
], o.prototype, "helpText", 2);
i([
  d()
], o.prototype, "name", 2);
i([
  d({ reflect: !0 })
], o.prototype, "value", 2);
i([
  x("value")
], o.prototype, "defaultValue", 2);
i([
  d({ reflect: !0 })
], o.prototype, "size", 2);
i([
  d({ reflect: !1 })
], o.prototype, "form", 2);
i([
  d({ reflect: !0, type: Boolean })
], o.prototype, "required", 2);
i([
  d({ reflect: !0, type: Boolean })
], o.prototype, "horizontal", 2);
i([
  d({ reflect: !0, type: Boolean })
], o.prototype, "compact", 2);
i([
  d({ attribute: "items-per-row", type: Number })
], o.prototype, "itemsPerRow", 2);
i([
  h("size", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleSizeChange", 1);
i([
  h("value")
], o.prototype, "handleValueChange", 1);
o = i([
  v("cx-radio-group")
], o);
export {
  o as default
};
