import { computed, ref, watch } from 'vue';
import { useSearch } from './useSearch.js';
import { useDebounceFn } from '@vueuse/core';

export function useSearchUI() {
  const query = ref('');
  const isSearchActive = ref(false);
  const { search, loading, searchResults } = useSearch();

  const filteredSearchResults = computed(() => {
    if (!searchResults.value) return {};

    return Object.entries(searchResults.value)
      .reduce((acc, [category, blocks]) => {
        if (blocks.length > 0) {
          acc[category] = blocks;
        }
        return acc;
      }, {});
  });

  const hasResults = computed(() => {
    if (!searchResults.value) return false;

    return Object.keys(searchResults.value).some(key => {
      return Array.isArray(searchResults.value[key]) &&
             searchResults.value[key].length > 0;
    });
  });

  function getBlockTitle(category) {
    return category.charAt(0).toUpperCase() + category.slice(1);
  }

  function clearSearch() {
    query.value = '';
    searchResults.value = null;
  }

  function toggleSearch(value) {
    isSearchActive.value = value !== undefined ? value : !isSearchActive.value;
  }

  const debouncedSearch = useDebounceFn(async () => {
    if (query.value) {
      await search(query.value);
    } else {
      searchResults.value = null;
    }
  }, 750);

  watch(() => query.value, async () => {
    await debouncedSearch();
  }, { immediate: false });

  return {
    query,
    isSearchActive,
    loading,
    searchResults,
    filteredSearchResults,
    hasResults,
    getBlockTitle,
    clearSearch,
    toggleSearch
  };
}