import { computed } from "vue";
//#region components/conversations/hooks/useGroupable.ts
function useGroupable(groupable, items) {
	const groupConfig = computed(() => {
		let baseConfig = {
			label: "",
			collapsibleHandle: false,
			collapsibleOptions: {}
		};
		if (!groupable.value) return baseConfig;
		if (typeof groupable.value === "object") {
			const { collapsible, defaultExpandedKeys, expandedKeys, onExpand, ...other } = groupable.value;
			baseConfig = {
				...baseConfig,
				...other,
				collapsibleHandle: collapsible ?? false,
				collapsibleOptions: {
					defaultExpandedKeys,
					expandedKeys,
					onExpand
				}
			};
		}
		return baseConfig;
	});
	const groupList = computed(() => {
		return items.value.reduce((currentGroupList, item) => {
			if (item?.type === "divider" || !item.group || !groupable.value) {
				currentGroupList.push({
					data: [item],
					name: "",
					label: "",
					enableGroup: false,
					collapsible: false
				});
				return currentGroupList;
			}
			const baseItem = item;
			const foundIndex = currentGroupList.findIndex((group) => group.name === baseItem.group);
			if (foundIndex > -1) {
				currentGroupList[foundIndex]?.data.push(baseItem);
				return currentGroupList;
			}
			const { collapsibleHandle, label } = groupConfig.value;
			const collapsible = typeof collapsibleHandle === "function" ? collapsibleHandle(baseItem.group) : collapsibleHandle;
			currentGroupList.push({
				data: [baseItem],
				enableGroup: true,
				name: baseItem.group,
				label,
				collapsible
			});
			return currentGroupList;
		}, []);
	});
	return {
		groupList,
		keyList: computed(() => {
			return groupList.value.reduce((currentKeyList, group) => {
				group.data.forEach((item) => {
					if (item.type !== "divider") {
						const baseItem = item;
						currentKeyList.push({
							key: baseItem.key,
							disabled: baseItem.disabled
						});
					}
				});
				return currentKeyList;
			}, []);
		}),
		collapsibleOptions: computed(() => groupConfig.value.collapsibleOptions)
	};
}
//#endregion
export { useGroupable as default };
