import { writable, derived } from "svelte/store";

interface SearchState {
  query: string;
  isActive: boolean;
  matchCount: number;
  currentMatchIndex: number;
}

const initialState: SearchState = {
  query: "",
  isActive: false,
  matchCount: 0,
  currentMatchIndex: 0,
};

const searchStore = writable<SearchState>(initialState);

export const searchState = {
  subscribe: searchStore.subscribe,

  setQuery: (query: string) => {
    searchStore.update((state) => ({
      ...state,
      query,
      isActive: query.length > 0,
      currentMatchIndex: 0,
    }));
  },

  setMatchCount: (count: number) => {
    searchStore.update((state) => ({
      ...state,
      matchCount: count,
    }));
  },

  nextMatch: () => {
    searchStore.update((state) => ({
      ...state,
      currentMatchIndex:
        state.matchCount > 0 ? (state.currentMatchIndex + 1) % state.matchCount : 0,
    }));
  },

  previousMatch: () => {
    searchStore.update((state) => ({
      ...state,
      currentMatchIndex:
        state.matchCount > 0
          ? (state.currentMatchIndex - 1 + state.matchCount) % state.matchCount
          : 0,
    }));
  },

  clear: () => {
    searchStore.set(initialState);
  },
};

export const isSearchActive = derived(searchStore, ($search) => $search.isActive);

export const searchQuery = derived(searchStore, ($search) => $search.query);
