import { ref, watch } from 'vue';

const searchQuery = ref('');
const filterState = ref({
  time: 'all' as 'all' | 'today' | 'early',
  status: 'open' as 'all' | 'open' | 'settled',
  leagueIds: [] as string[],
});

/** 空数组表示未限定联赛，等价于全部选中 */
export function isLeagueSelected(leagueId: string, leagueIds: string[]) {
  return leagueIds.length === 0 || leagueIds.includes(leagueId);
}

watch(
  () => filterState.value.time,
  () => {
    filterState.value.leagueIds = [];
  },
);

export function useMatchFilters() {
  function clearFilters() {
    searchQuery.value = '';
    filterState.value.time = 'all';
    filterState.value.status = 'open';
    filterState.value.leagueIds = [];
  }

  function toggleLeague(leagueId: string, availableIds: string[]) {
    const current = filterState.value.leagueIds;

    if (current.length === 0) {
      filterState.value.leagueIds = availableIds.filter((id) => id !== leagueId);
      return;
    }

    const idx = current.indexOf(leagueId);
    if (idx > -1) {
      current.splice(idx, 1);
      return;
    }

    current.push(leagueId);
    if (availableIds.every((id) => current.includes(id))) {
      filterState.value.leagueIds = [];
    }
  }

  return {
    searchQuery,
    filterState,
    clearFilters,
    toggleLeague,
    isLeagueSelected,
  };
}
