import { useFetch } from '@win2win/shared-ui';
import { computed, ref } from 'vue';

const collator = new Intl.Collator('es', { sensitivity: 'base' });

export function useCollection(collectionCode?: string) {
  if (!collectionCode) return { data: ref(null), fetching: ref(false), getLabel: () => '' };
  const { data, fetching } = useFetch<any[]>(['collections', collectionCode], '/public/collections/' + collectionCode);
  const sortedData = computed(() => {
    if (!data.value) return null;
    return [...data.value].sort((a, b) => collator.compare(a.label, b.label));
  });

  function getLabel(value: any): string {
    if (!value) return '';
    const item = (data.value || []).find((item: any) => item.value === value);
    return item?.label ?? 'value';
  }

  return { data: sortedData, fetching, getLabel };
}
