<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 YhCheckbox from "./checkbox.vue";
import { checkboxGroupContextKey } from "./checkbox";
defineOptions({
  name: "YhCheckboxGroup"
});
const props = defineProps({
  modelValue: { type: Array, required: false, default: () => [] },
  options: { type: Array, required: false },
  size: { type: null, required: false },
  disabled: { type: Boolean, required: false, default: false },
  min: { type: Number, required: false },
  max: { type: Number, 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("checkbox-group");
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 { themeStyle } = useComponentTheme(
  "checkbox-group",
  computed(() => props.themeOverrides)
);
const { modelValue, size, disabled, min, max } = toRefs(props);
provide(checkboxGroupContextKey, {
  get modelValue() {
    return modelValue.value;
  },
  get size() {
    return size?.value || globalSize.value || "default";
  },
  get disabled() {
    return disabled.value;
  },
  get min() {
    return min?.value;
  },
  get max() {
    return max?.value;
  },
  get themeOverrides() {
    return props.themeOverrides;
  },
  changeEvent
});
const groupClasses = computed(() => [ns.b()]);
</script>

<template>
  <component
    :is="tag"
    :class="groupClasses"
    :style="themeStyle"
    role="group"
    :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-checkbox
          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-checkbox-group {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  font-size: 0;
  line-height: 0;
}
</style>
