// Composable for managing calendar search and filter state
export const useCalendarSearch = () => {
  const searchQuery = ref("");
  const includePastEvents = ref(false);
  const searchResults = ref([]);
  const selectedCategories = ref([]);
  const isSearching = computed(() => {
    return (
      searchQuery.value.length > 0 ||
      selectedCategories.value.length > 0
    );
  });

  // Save search state to sessionStorage for persistence across navigation
  const saveSearchState = (
    query,
    categories,
    includePast,
    results
  ) => {
    if (process.client) {
      sessionStorage.setItem(
        "calendarSearchState",
        JSON.stringify({
          searchQuery: query,
          selectedCategories: categories,
          includePastEvents: includePast,
          searchResults: results,
          timestamp: Date.now(),
        })
      );
    }
  };

  // Load search state from sessionStorage
  const loadSearchState = () => {
    if (process.client) {
      const saved = sessionStorage.getItem("calendarSearchState");
      if (saved) {
        try {
          const state = JSON.parse(saved);
          // Only restore if saved less than 30 minutes ago
          if (Date.now() - state.timestamp < 30 * 60 * 1000) {
            searchQuery.value = state.searchQuery;
            selectedCategories.value = state.selectedCategories;
            includePastEvents.value = state.includePastEvents;
            searchResults.value = state.searchResults;
            return true;
          }
        } catch (e) {
          console.error("Failed to load search state:", e);
        }
      }
    }
    return false;
  };

  // Clear all search filters
  const clearSearch = () => {
    searchQuery.value = "";
    selectedCategories.value = [];
    searchResults.value = [];
  };

  // Clear search state from sessionStorage
  const clearSearchState = () => {
    if (process.client) {
      sessionStorage.removeItem("calendarSearchState");
    }
  };

  return {
    searchQuery,
    includePastEvents,
    searchResults,
    selectedCategories,
    isSearching,
    saveSearchState,
    loadSearchState,
    clearSearch,
    clearSearchState,
  };
};
