<script>
import theme from "#build/b24ui/page-card-group";
</script>

<script setup>
import { computed, ref, useId } from "vue";
import { useAppConfig } from "#imports";
import { useComponentProps } from "../composables/useComponentProps";
import { useFormField } from "../composables/useFormField";
import { get } from "../utils";
import { tv } from "../utils/tv";
import CheckLIcon from "@bitrix24/b24icons-vue/outline/CheckLIcon";
import B24PageCard from "./PageCard.vue";
import B24Badge from "./Badge.vue";
const _props = defineProps({
  as: { type: null, required: false, default: "div" },
  legend: { type: String, required: false },
  items: { type: Array, required: false },
  modelValue: { type: [String, Number, Object, null, Boolean, Array], required: false, skipCheck: true },
  defaultValue: { type: [String, Number, Object, null, Boolean, Array], required: false, skipCheck: true },
  valueKey: { type: String, required: false, default: "value" },
  labelKey: { type: String, required: false, default: "label" },
  descriptionKey: { type: String, required: false, default: "description" },
  iconKey: { type: String, required: false, default: "icon" },
  categoryKey: { type: String, required: false, default: "category" },
  multiple: { type: Boolean, required: false, default: false },
  disabled: { type: Boolean, required: false },
  required: { type: Boolean, required: false },
  name: { type: String, required: false },
  size: { type: null, required: false, default: "md" },
  variant: { type: null, required: false, default: "outline" },
  color: { type: null, required: false, default: "air-primary-success" },
  highlightColor: { type: null, required: false },
  badgeColor: { type: null, required: false },
  badgeSize: { type: null, required: false },
  avatar: { type: Object, required: false },
  columns: { type: null, required: false },
  class: { type: null, required: false },
  b24ui: { type: Object, required: false }
});
const emits = defineEmits(["update:modelValue", "change"]);
const slots = defineSlots();
const props = useComponentProps("pageCardGroup", _props);
const appConfig = useAppConfig();
const { emitFormChange, emitFormInput, name, id: _id, disabled: formFieldDisabled, ariaAttrs } = useFormField(_props, { bind: false });
const disabled = computed(() => formFieldDisabled.value ?? props.disabled);
const groupId = _id.value ?? useId();
const localValue = ref(
  props.modelValue !== void 0 ? props.modelValue : props.defaultValue ?? (props.multiple ? [] : void 0)
);
const currentValue = computed(() => {
  return props.modelValue !== void 0 ? props.modelValue : localValue.value;
});
const b24ui = computed(() => tv({ extend: theme, ...appConfig.b24ui?.pageCardGroup || {} })({
  size: props.size,
  columns: props.columns,
  disabled: disabled.value
}));
const effectiveHighlightColor = computed(() => props.highlightColor ?? props.color);
const effectiveBadgeColor = computed(() => props.badgeColor ?? props.color);
const sizeToBadgeSize = {
  sm: "sm",
  md: "md",
  lg: "lg"
};
const effectiveBadgeSize = computed(
  () => props.badgeSize ?? sizeToBadgeSize[props.size] ?? "md"
);
const innerCardUI = computed(() => ({
  container: b24ui.value.cardContainer({ class: props.b24ui?.cardContainer }),
  wrapper: b24ui.value.cardWrapper({ class: props.b24ui?.cardWrapper }),
  leading: b24ui.value.cardLeading({ class: props.b24ui?.cardLeading }),
  body: b24ui.value.cardBody({ class: props.b24ui?.cardBody }),
  title: b24ui.value.cardTitle({ class: props.b24ui?.cardTitle }),
  description: b24ui.value.cardDescription({ class: props.b24ui?.cardDescription }),
  leadingIcon: b24ui.value.leadingIcon({ class: props.b24ui?.leadingIcon }),
  leadingAvatar: b24ui.value.leadingAvatar({ class: props.b24ui?.leadingAvatar }),
  leadingAvatarSize: props.b24ui?.leadingAvatarSize || b24ui.value.leadingAvatarSize()
}));
function getItemValue(item) {
  if (item === null || typeof item !== "object") return item;
  const v = get(item, props.valueKey);
  return v ?? item[props.labelKey];
}
function isSelected(item) {
  const v = getItemValue(item);
  const cur = currentValue.value;
  if (props.multiple) {
    return Array.isArray(cur) && cur.includes(v);
  }
  return cur === v;
}
function getItemIcon(item) {
  return get(item, props.iconKey);
}
function getItemAvatar(item) {
  if (getItemIcon(item)) return void 0;
  const itemAvatar = item.avatar;
  if (!itemAvatar && !props.avatar) return void 0;
  return {
    ...props.avatar,
    ...itemAvatar,
    alt: itemAvatar?.alt ?? get(item, props.labelKey)
  };
}
function setValue(next, event) {
  localValue.value = next;
  emits("update:modelValue", next);
  emits("change", event);
  emitFormChange();
  emitFormInput();
}
function onItemChange(item, event) {
  if (item.disabled || disabled.value) return;
  const v = getItemValue(item);
  if (props.multiple) {
    const arr = Array.isArray(currentValue.value) ? [...currentValue.value] : [];
    const idx = arr.indexOf(v);
    if (idx >= 0) arr.splice(idx, 1);
    else arr.push(v);
    setValue(arr, event);
  } else {
    setValue(v, event);
  }
}
const groupedItems = computed(() => {
  const items = props.items ?? [];
  if (!props.categoryKey) return [{ items }];
  const map = /* @__PURE__ */ new Map();
  const order = [];
  for (const item of items) {
    const cat = typeof item === "object" && item !== null ? item[props.categoryKey] : void 0;
    if (!map.has(cat)) {
      map.set(cat, []);
      order.push(cat);
    }
    map.get(cat).push(item);
  }
  return order.map((cat) => ({ category: cat, items: map.get(cat) }));
});
</script>

<template>
  <component
    :is="props.as"
    :id="groupId"
    :role="props.multiple ? 'group' : 'radiogroup'"
    :aria-disabled="disabled || void 0"
    :aria-required="props.required || void 0"
    data-slot="root"
    :class="b24ui.root({ class: [props.b24ui?.root, props.class] })"
  >
    <fieldset data-slot="fieldset" :class="b24ui.fieldset({ class: props.b24ui?.fieldset })" v-bind="ariaAttrs" :disabled="disabled">
      <legend v-if="props.legend || !!slots.legend" data-slot="legend" :class="b24ui.legend({ class: props.b24ui?.legend })">
        <slot name="legend" :b24ui="b24ui">
          {{ props.legend }}
        </slot>
      </legend>

      <div
        v-for="(group, gi) in groupedItems"
        :key="group.category ?? `group:${gi}`"
        data-slot="group"
        :class="b24ui.group({ class: props.b24ui?.group })"
      >
        <div
          v-if="group.category"
          data-slot="categoryLabel"
          :class="b24ui.categoryLabel({ class: props.b24ui?.categoryLabel })"
        >
          <slot name="categoryLabel" :category="group.category" :items="group.items" :b24ui="b24ui">
            {{ group.category }}
          </slot>
        </div>

        <div data-slot="grid" :class="b24ui.grid({ class: props.b24ui?.grid })">
          <label
            v-for="item in group.items"
            :key="String(getItemValue(item))"
            data-slot="item"
            :data-disabled="item.disabled || disabled || void 0"
            :class="b24ui.item({ class: [props.b24ui?.item, item.class] })"
          >
            <input
              :type="props.multiple ? 'checkbox' : 'radio'"
              :name="name ?? groupId"
              :value="getItemValue(item)"
              :checked="isSelected(item)"
              :disabled="item.disabled || disabled"
              :required="props.required && !props.multiple"
              class="sr-only"
              @change="onItemChange(item, $event)"
            >

            <B24PageCard
              :title="get(item, props.labelKey)"
              :description="get(item, props.descriptionKey)"
              :icon="getItemIcon(item)"
              :avatar="getItemAvatar(item)"
              :variant="props.variant"
              orientation="vertical"
              :highlight="isSelected(item)"
              :highlight-color="effectiveHighlightColor"
              :class="b24ui.card({ class: props.b24ui?.card })"
              :b24ui="innerCardUI"
            >
              <template v-if="!!slots.leading" #leading>
                <slot name="leading" :item="item" :selected="isSelected(item)" :b24ui="b24ui" />
              </template>

              <template v-if="isSelected(item)">
                <span data-slot="badge" :class="b24ui.badge({ class: props.b24ui?.badge })">
                  <slot name="badge" :item="item" :selected="true" :b24ui="b24ui">
                    <B24Badge
                      :icon="CheckLIcon"
                      :color="effectiveBadgeColor"
                      :size="effectiveBadgeSize"
                      square
                      :class="b24ui.badgeIcon({ class: props.b24ui?.badgeIcon })"
                    />
                  </slot>
                </span>
              </template>
            </B24PageCard>
          </label>
        </div>
      </div>
    </fieldset>
  </component>
</template>
