'use strict';

Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });

const lit = require('lit');
const decorators_js = require('lit/decorators.js');
const index = require('../../chunks/index-BBPgtFEP.js');

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
exports.LuksoRadioGroup = class LuksoRadioGroup extends index.TailwindElement {
  constructor() {
    super(...arguments);
    this.name = "";
    this.value = "";
    this.autofocus = false;
    this.focusedIndex = -1;
    this.radios = [];
  }
  // Detect if radio group is laid out horizontally or vertically
  isHorizontalLayout() {
    const firstRadio = this.querySelector("lukso-radio");
    if (!firstRadio) return false;
    const secondRadio = firstRadio.nextElementSibling;
    if (!secondRadio) return false;
    const firstRect = firstRadio.getBoundingClientRect();
    const secondRect = secondRadio.getBoundingClientRect();
    return Math.abs(secondRect.left - firstRect.left) > Math.abs(secondRect.top - firstRect.top);
  }
  handleChange(e) {
    const newValue = e.detail.value;
    this.value = newValue;
    this.updateRadios();
    this.dispatchEvent(
      new CustomEvent("change", {
        detail: { value: this.value },
        bubbles: true,
        composed: true
      })
    );
  }
  updateRadios() {
    const radios = this.querySelectorAll("lukso-radio");
    for (const el of radios) {
      el.checked = el.value === this.value;
    }
  }
  // Make sure radios are updated when they become available
  setupInitialState() {
    this.updateRadios();
    setTimeout(() => this.updateRadios(), 50);
    setTimeout(() => this.updateRadios(), 150);
  }
  handleKeydown(e) {
    this.radios = Array.from(this.querySelectorAll("lukso-radio"));
    if (!this.radios.length) return;
    const selectedIndex = this.radios.findIndex(
      (radio) => radio.checked
    );
    if (this.focusedIndex === -1) {
      this.focusedIndex = selectedIndex >= 0 ? selectedIndex : 0;
    }
    let newIndex = this.focusedIndex;
    const isHorizontal = this.isHorizontalLayout();
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault();
        if (!isHorizontal) {
          newIndex = (this.focusedIndex + 1) % this.radios.length;
        }
        break;
      case "ArrowRight":
        e.preventDefault();
        newIndex = (this.focusedIndex + 1) % this.radios.length;
        break;
      case "ArrowUp":
        e.preventDefault();
        if (!isHorizontal) {
          newIndex = (this.focusedIndex - 1 + this.radios.length) % this.radios.length;
        }
        break;
      case "ArrowLeft":
        e.preventDefault();
        newIndex = (this.focusedIndex - 1 + this.radios.length) % this.radios.length;
        break;
      case "Home":
        e.preventDefault();
        newIndex = 0;
        break;
      case "End":
        e.preventDefault();
        newIndex = this.radios.length - 1;
        break;
      default:
        return;
    }
    if (newIndex !== this.focusedIndex) {
      this.focusedIndex = newIndex;
      const radioToFocus = this.radios[newIndex];
      if (!radioToFocus.isDisabled && !radioToFocus.isReadonly) {
        radioToFocus.focus();
        this.value = radioToFocus.value;
        this.updateRadios();
        this.dispatchEvent(
          new CustomEvent("change", {
            detail: { value: this.value },
            bubbles: true,
            composed: true
          })
        );
      }
    }
  }
  connectedCallback() {
    super.connectedCallback();
    this.addEventListener("on-change", this.handleChange);
    this.addEventListener("keydown", this.handleKeydown);
    this.setupInitialState();
    if (this.autofocus) {
      setTimeout(() => this.handleGroupFocus(), 50);
    }
  }
  // Called after the first update and subsequent updates
  updated(changedProperties) {
    super.updated?.(changedProperties);
    if (changedProperties.has("value")) {
      this.updateRadios();
    }
  }
  attributeChangedCallback(name, oldVal, newVal) {
    super.attributeChangedCallback(name, oldVal, newVal);
    if (name === "value" && oldVal !== newVal && this.isConnected) {
      this.updateRadios();
    }
  }
  disconnectedCallback() {
    this.removeEventListener("on-change", this.handleChange);
    this.removeEventListener("keydown", this.handleKeydown);
    super.disconnectedCallback();
  }
  // When the group gets focus, we should move focus to the selected radio or first available
  handleGroupFocus() {
    if (!this.isConnected) return;
    const radios = Array.from(
      this.querySelectorAll("lukso-radio")
    );
    if (!radios.length) return;
    const selectedRadio = radios.find(
      (radio) => radio.checked && !radio.isDisabled && !radio.isReadonly
    );
    const firstEnabledRadio = radios.find(
      (radio) => !radio.isDisabled && !radio.isReadonly
    );
    const radioToFocus = selectedRadio || firstEnabledRadio;
    if (radioToFocus) {
      setTimeout(() => radioToFocus.focus(), 0);
    }
  }
  render() {
    return lit.html`
      <div
        role="radiogroup"
        aria-label="${this.name}"
        tabindex="0"
        @focus="${this.handleGroupFocus}"
      >
        <slot></slot>
      </div>
    `;
  }
};
__decorateClass([
  decorators_js.property({ type: String })
], exports.LuksoRadioGroup.prototype, "name", 2);
__decorateClass([
  decorators_js.property({ type: String })
], exports.LuksoRadioGroup.prototype, "value", 2);
__decorateClass([
  decorators_js.property({ type: Boolean })
], exports.LuksoRadioGroup.prototype, "autofocus", 2);
__decorateClass([
  decorators_js.state()
], exports.LuksoRadioGroup.prototype, "focusedIndex", 2);
__decorateClass([
  decorators_js.state()
], exports.LuksoRadioGroup.prototype, "radios", 2);
exports.LuksoRadioGroup = __decorateClass([
  index.safeCustomElement("lukso-radio-group")
], exports.LuksoRadioGroup);
