export const SEARCH_HISTORY_KEY = 'blog_search_history'
const MAX_HISTORY = 10

export function useSearchHistory() {
  const readHistory = (): string[] => {
    try {
      const raw = localStorage.getItem(SEARCH_HISTORY_KEY)
      if (!raw) return []
      const parsed = JSON.parse(raw)
      return Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : []
    } catch {
      return []
    }
  }

  const writeHistory = (items: string[]) => {
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
  }

  const getHistory = () => readHistory()

  const addHistory = (keyword: string) => {
    const trimmed = keyword.trim()
    if (!trimmed) return
    const next = [trimmed, ...readHistory().filter((item) => item !== trimmed)].slice(0, MAX_HISTORY)
    writeHistory(next)
  }

  const removeHistory = (keyword: string) => {
    writeHistory(readHistory().filter((item) => item !== keyword))
  }

  const clearHistory = () => {
    localStorage.removeItem(SEARCH_HISTORY_KEY)
  }

  return {
    getHistory,
    addHistory,
    removeHistory,
    clearHistory,
  }
}
