<script setup>
import { computed, provide, toRefs } from "vue";
import { useNamespace, useFormItem, useId } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { useConfig } from "@yh-ui/hooks";
import YhRadio from "./radio.vue";
import { radioGroupContextKey } from "./radio";
defineOptions({
  name: "YhRadioGroup"
});
const props = defineProps({
  modelValue: { type: [String, Number, Boolean], required: false },
  options: { type: Array, required: false },
  size: { type: null, required: false },
  disabled: { type: Boolean, required: false, default: false },
  name: { type: String, required: false },
  validateEvent: { type: Boolean, required: false, default: true },
  textColor: { type: String, required: false },
  fill: { type: String, required: false },
  tag: { type: null, required: false, default: "div" },
  themeOverrides: { type: null, required: false }
});
const emit = defineEmits(["update:modelValue", "change"]);
const ns = useNamespace("radio-group");
const { themeStyle } = useComponentTheme(
  "radio-group",
  computed(() => props.themeOverrides)
);
const { formItem } = useFormItem();
const { validate } = useFormItem();
const labelId = useId().value;
const { globalSize } = useConfig();
const changeEvent = (value) => {
  emit("update:modelValue", value);
  emit("change", value);
  if (props.validateEvent) {
    validate("change");
  }
};
const { modelValue, size, disabled, name, fill, textColor } = toRefs(props);
provide(radioGroupContextKey, {
  get modelValue() {
    return modelValue.value;
  },
  get size() {
    return size?.value || globalSize.value || "default";
  },
  get disabled() {
    return disabled.value;
  },
  get name() {
    return name?.value;
  },
  get fill() {
    return fill?.value;
  },
  get textColor() {
    return textColor?.value;
  },
  get themeOverrides() {
    return props.themeOverrides;
  },
  changeEvent
});
const groupSize = computed(() => props.size || globalSize.value || "default");
const groupClasses = computed(() => [
  ns.b(),
  groupSize.value !== "default" ? ns.m(groupSize.value) : ""
]);
</script>

<template>
  <component
    :is="tag"
    :class="groupClasses"
    :style="themeStyle"
    role="radiogroup"
    :aria-labelledby="labelId"
    :aria-invalid="formItem?.validateStatus === 'error'"
    :aria-describedby="formItem?.validateStatus === 'error' ? formItem?.errorId : void 0"
  >
    <slot>
      <template v-if="options && options.length">
        <yh-radio
          v-for="item in options"
          :key="String(item.value)"
          :value="item.value"
          :label="item.label"
          :disabled="item.disabled"
        />
      </template>
    </slot>
  </component>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-radio-group {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  font-size: 0;
  line-height: 0;
}
</style>
