import { defineComponent, mergeModels, useAttrs, computed, inject, useModel, useTemplateRef, onUnmounted, onMounted, nextTick, watch, createElementBlock, openBlock, mergeProps, unref, createVNode, withCtx, createElementVNode, renderSlot, createBlock, resolveDynamicComponent, createTextVNode, toDisplayString, useSlots, ref, shallowRef, provide, toRef, readonly, normalizeClass } from "vue";
import { g as accordionInjectionKey } from "./keys-D5Pj1dmf.mjs";
import { u as useId } from "./useId-9_HUwM96.mjs";
import { u as useDefaults } from "./useDefaults-DvqfKEoD.mjs";
import { f as flattenFragments } from "./flattenFragments-BoFLyuna.mjs";
import { _ as _sfc_main$2 } from "./BCollapse.vue_vue_type_script_setup_true_lang-Y_U2y1JS.mjs";
import { i as isReadOnlyArray } from "./object-hfadz3TY.mjs";
import { s as sortSlotElementsByPosition } from "./dom-DVb-f0ZG.mjs";
const _hoisted_1$1 = ["aria-expanded", "aria-controls", "onClick"];
const _sfc_main$1 = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "BAccordionItem",
  props: /* @__PURE__ */ mergeModels({
    bodyAttrs: { default: void 0 },
    bodyClass: { default: void 0 },
    buttonAttrs: { default: void 0 },
    buttonClass: { default: void 0 },
    collapseClass: { default: void 0 },
    headerAttrs: { default: void 0 },
    headerClass: { default: void 0 },
    headerTag: { default: "h2" },
    horizontal: { type: Boolean, default: void 0 },
    id: { default: void 0 },
    isNav: { type: Boolean, default: void 0 },
    lazy: { type: Boolean, default: false },
    unmountLazy: { type: Boolean, default: false },
    tag: { default: void 0 },
    title: { default: void 0 },
    show: { type: Boolean, default: void 0 },
    visible: { type: Boolean, default: false },
    wrapperAttrs: { default: void 0 }
  }, {
    "modelValue": { type: Boolean, ...{
      default: false
    } },
    "modelModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["hide", "hide-prevented", "hidden", "show", "show-prevented", "shown", "toggle", "toggle-prevented"], ["update:modelValue"]),
  setup(__props, { emit: __emit }) {
    const _props = __props;
    const props = useDefaults(_props, "BAccordionItem");
    const emit = __emit;
    const attrs = useAttrs();
    const processedAttrs = computed(() => {
      const { class: wrapperClass, ...collapseAttrs } = attrs;
      return { wrapperClass, collapseAttrs };
    });
    const parentData = inject(accordionInjectionKey, null);
    const computedId = useId(() => props.id, "accordion_item");
    const modelValue = useModel(__props, "modelValue");
    if (modelValue.value) {
      parentData?.setOpenItem(computedId.value);
    } else {
      modelValue.value = (isReadOnlyArray(parentData?.openItem.value) ? parentData?.openItem.value.includes(computedId.value) : parentData?.openItem.value === computedId.value) && !parentData?.initialAnimation.value;
    }
    const el = useTemplateRef("_el");
    parentData?.registerAccordionItem(computedId.value, el);
    onUnmounted(() => {
      parentData?.unregisterAccordionItem(computedId.value);
    });
    onMounted(() => {
      if (!modelValue.value && parentData?.openItem.value === computedId.value) {
        nextTick(() => {
          modelValue.value = true;
        });
      }
    });
    const openInParent = computed(
      () => isReadOnlyArray(parentData?.openItem.value) ? parentData?.openItem.value.includes(computedId.value) : parentData?.openItem.value === computedId.value
    );
    watch(
      () => parentData?.openItem.value,
      () => modelValue.value = openInParent.value
    );
    watch(modelValue, () => {
      if (modelValue.value && !openInParent.value) {
        parentData?.setOpenItem(computedId.value);
      } else if (!modelValue.value && openInParent.value) {
        parentData?.setCloseItem(computedId.value);
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", mergeProps({
        ref: "_el",
        class: "accordion-item"
      }, unref(props).wrapperAttrs, {
        class: processedAttrs.value.wrapperClass
      }), [
        createVNode(_sfc_main$2, mergeProps({
          id: unref(computedId),
          modelValue: modelValue.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => modelValue.value = $event),
          class: ["accordion-collapse", unref(props).collapseClass],
          "aria-labelledby": `${unref(computedId)}-heading`
        }, processedAttrs.value.collapseAttrs, {
          tag: unref(props).tag,
          show: unref(props).show,
          horizontal: unref(props).horizontal,
          visible: unref(props).visible,
          "is-nav": unref(props).isNav,
          lazy: unref(props).lazy || unref(parentData)?.lazy.value,
          "unmount-lazy": unref(props).unmountLazy || unref(parentData)?.unmountLazy.value,
          onShow: _cache[1] || (_cache[1] = ($event) => emit("show", $event)),
          onShown: _cache[2] || (_cache[2] = ($event) => emit("shown", $event)),
          onHide: _cache[3] || (_cache[3] = ($event) => emit("hide", $event)),
          onHidden: _cache[4] || (_cache[4] = ($event) => emit("hidden", $event)),
          onHidePrevented: _cache[5] || (_cache[5] = ($event) => emit("hide-prevented", $event)),
          onShowPrevented: _cache[6] || (_cache[6] = ($event) => emit("show-prevented", $event)),
          onTogglePrevented: _cache[7] || (_cache[7] = ($event) => emit("toggle-prevented", $event)),
          onToggle: _cache[8] || (_cache[8] = ($event) => emit("toggle", $event))
        }), {
          header: withCtx(({ visible: toggleVisible, toggle: slotToggle }) => [
            (openBlock(), createBlock(resolveDynamicComponent(unref(props).headerTag), mergeProps({
              id: `${unref(computedId)}-heading`,
              class: ["accordion-header", unref(props).headerClass]
            }, unref(props).headerAttrs), {
              default: withCtx(() => [
                createElementVNode("button", mergeProps({ class: "accordion-button" }, unref(props).buttonAttrs, {
                  class: [{ collapsed: !toggleVisible }, unref(props).buttonClass],
                  type: "button",
                  "aria-expanded": toggleVisible ? "true" : "false",
                  "aria-controls": unref(computedId),
                  onClick: slotToggle
                }), [
                  renderSlot(_ctx.$slots, "title", {}, () => [
                    createTextVNode(toDisplayString(unref(props).title), 1)
                  ])
                ], 16, _hoisted_1$1)
              ]),
              _: 2
            }, 1040, ["id", "class"]))
          ]),
          default: withCtx(() => [
            createElementVNode("div", mergeProps({ class: "accordion-body" }, unref(props).bodyAttrs, {
              class: unref(props).bodyClass
            }), [
              renderSlot(_ctx.$slots, "default")
            ], 16)
          ]),
          _: 3
        }, 16, ["id", "modelValue", "class", "aria-labelledby", "tag", "show", "horizontal", "visible", "is-nav", "lazy", "unmount-lazy"])
      ], 16);
    };
  }
});
const _hoisted_1 = ["id"];
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "BAccordion",
  props: /* @__PURE__ */ mergeModels({
    flush: { type: Boolean, default: false },
    free: { type: Boolean, default: false },
    id: { default: void 0 },
    initialAnimation: { type: Boolean, default: false },
    lazy: { type: Boolean, default: false },
    unmountLazy: { type: Boolean, default: false }
  }, {
    "modelValue": {
      default: void 0
    },
    "modelModifiers": {},
    "index": {
      default: void 0
    },
    "indexModifiers": {}
  }),
  emits: ["update:modelValue", "update:index"],
  setup(__props) {
    const _props = __props;
    const props = useDefaults(_props, "BAccordion");
    const slots = useSlots();
    const modelValue = useModel(__props, "modelValue");
    const index = useModel(__props, "index");
    const itemElementsArray = ref([]);
    const updateItemElementsArray = () => {
      const itemElements = flattenFragments(slots.default?.({}) ?? []);
      itemElementsArray.value = (Array.isArray(itemElements) ? itemElements : [itemElements]).filter(
        (item) => item.type === _sfc_main$1
      );
    };
    updateItemElementsArray();
    watch(
      () => slots.default?.({}),
      () => {
        updateItemElementsArray();
        nextTick(() => {
          sortAccordionItems();
        });
      }
    );
    const accordionItems = shallowRef([]);
    const sortAccordionItems = () => {
      accordionItems.value = accordionItems.value.sort(
        (a, b) => sortSlotElementsByPosition(unref(a.el), unref(b.el))
      );
      if (modelValue.value) {
        if (isReadOnlyArray(modelValue.value)) {
          const next = modelValue.value.map((id) => accordionItems.value.findIndex((item) => item.id === id)).filter((i) => i !== -1);
          if (next.length !== modelValue.value.length) {
            if (process.env.NODE_ENV === "development") {
              console.warn("[BAccordion] Unknown item id in v-model:", modelValue.value);
            }
          }
          index.value = next;
        } else {
          const idx = accordionItems.value.findIndex((item) => item.id === modelValue.value);
          if (idx !== -1) index.value = idx;
        }
      } else if (index.value !== void 0) {
        modelValue.value = isReadOnlyArray(index.value) ? index.value.map((idx) => accordionItems.value[idx]?.id) : accordionItems.value[index.value]?.id;
      }
    };
    const computedId = useId(() => props.id, "accordion");
    const computedClasses = computed(() => ({
      "accordion-flush": props.flush
    }));
    const areEqual = (a, b) => {
      if (Array.isArray(a) && Array.isArray(b)) {
        return a.length === b.length && a.every((item, index2) => item === b[index2]);
      }
      return a === b;
    };
    watch(index, (newValue, oldValue) => {
      if (areEqual(newValue, oldValue)) return;
      if (index.value === void 0) {
        modelValue.value = void 0;
        return;
      }
      if (!props.free) {
        const idx = !isReadOnlyArray(index.value) ? index.value : index.value?.[0];
        if (accordionItems.value[idx]?.id) {
          if (modelValue.value !== accordionItems.value[idx]?.id) {
            modelValue.value = accordionItems.value[idx]?.id;
          }
        } else {
          nextTick(() => {
            index.value = void 0;
          });
        }
      } else {
        if (isReadOnlyArray(index.value)) {
          const newValue2 = index.value.map((item) => accordionItems.value[item]?.id);
          if (!areEqual(newValue2, modelValue.value)) {
            modelValue.value = newValue2;
          }
        } else {
          const newValue2 = accordionItems.value[index.value]?.id;
          if (newValue2 === void 0) {
            nextTick(() => {
              index.value = void 0;
            });
            return;
          }
          if (!areEqual(newValue2, modelValue.value)) {
            modelValue.value = newValue2;
          }
        }
      }
    });
    watch(
      modelValue,
      (newValue, oldValue) => {
        if (areEqual(newValue, oldValue)) return;
        if (modelValue.value === void 0) {
          index.value = void 0;
          return;
        }
        if (!props.free) {
          const idx = accordionItems.value.findIndex(
            (item) => item.id === (!isReadOnlyArray(modelValue.value) ? modelValue.value : modelValue.value?.[0])
          );
          if (idx !== -1) {
            if (index.value !== idx) {
              index.value = idx;
            }
          } else {
            nextTick(() => {
              modelValue.value = void 0;
            });
          }
        } else if (props.free) {
          if (isReadOnlyArray(modelValue.value)) {
            const idxes = modelValue.value.map((value) => accordionItems.value.findIndex((item) => item.id === value)).filter((index2) => index2 !== -1);
            if (idxes.length > 0) {
              if (!areEqual(idxes, index.value)) {
                index.value = idxes;
              }
            } else {
              nextTick(() => {
                modelValue.value = void 0;
              });
            }
          } else {
            const newValue2 = accordionItems.value.findIndex((item) => item.id === modelValue.value);
            if (!areEqual(newValue2, index.value)) {
              index.value = newValue2;
            }
          }
        }
      },
      { deep: true }
    );
    watch(
      () => props.free,
      (free) => {
        if (modelValue.value) {
          if (!free && isReadOnlyArray(modelValue.value)) {
            modelValue.value = modelValue.value[0];
          } else if (free && !isReadOnlyArray(modelValue.value)) {
            modelValue.value = [modelValue.value];
          }
        }
      }
    );
    provide(accordionInjectionKey, {
      openItem: readonly(modelValue),
      free: toRef(() => props.free),
      initialAnimation: toRef(() => props.initialAnimation),
      lazy: toRef(() => props.lazy),
      unmountLazy: toRef(() => props.unmountLazy),
      setOpenItem: (id) => {
        if (props.free && !isReadOnlyArray(modelValue.value)) {
          if (modelValue.value !== void 0) {
            modelValue.value = [modelValue.value, id];
          } else {
            modelValue.value = [id];
          }
          return;
        }
        if (!props.free && isReadOnlyArray(modelValue.value)) {
          modelValue.value = id;
          return;
        }
        if (isReadOnlyArray(modelValue.value)) {
          if (!modelValue.value.includes(id)) {
            modelValue.value = [...modelValue.value, id];
          }
        } else {
          modelValue.value = id;
        }
      },
      setCloseItem: (id) => {
        if (!props.free && isReadOnlyArray(modelValue.value)) {
          modelValue.value = void 0;
          return;
        }
        if (isReadOnlyArray(modelValue.value)) {
          const next = modelValue.value.filter((item) => item !== id);
          modelValue.value = next.length ? next : void 0;
        } else {
          if (modelValue.value === id) {
            modelValue.value = void 0;
          }
        }
      },
      registerAccordionItem: (id, el) => {
        accordionItems.value = [...accordionItems.value, { id, el }];
        if (accordionItems.value.length === itemElementsArray.value.length) {
          sortAccordionItems();
        }
      },
      unregisterAccordionItem: (id) => {
        accordionItems.value = accordionItems.value.filter((item) => item.id !== id);
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        id: unref(computedId),
        class: normalizeClass(["accordion", computedClasses.value])
      }, [
        renderSlot(_ctx.$slots, "default")
      ], 10, _hoisted_1);
    };
  }
});
export {
  _sfc_main as _,
  _sfc_main$1 as a
};
//# sourceMappingURL=BAccordion.vue_vue_type_script_setup_true_lang-D_v2LJZI.mjs.map
