import { useState, useEffect } from 'react';

export const SEARCH_HISTORY_KEY = 'castad_search_history';
export const SEARCH_HISTORY_MAX = 5;

export interface SearchHistoryItem {
  type: 'url' | 'name';
  value: string;
  address?: string;
  roadAddress?: string;
}

export const saveSearchHistory = (item: SearchHistoryItem) => {
  try {
    const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
    const history: SearchHistoryItem[] = saved ? JSON.parse(saved) : [];
    const filtered = history.filter(h => h.value !== item.value);
    const updated = [item, ...filtered].slice(0, SEARCH_HISTORY_MAX);
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
  } catch { /* ignore */ }
};

export const useSearchHistory = (searchType: 'url' | 'name') => {
  const [history, setHistory] = useState<SearchHistoryItem[]>([]);
  const [showHistory, setShowHistory] = useState(false);

  useEffect(() => {
    try {
      const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
      if (saved) setHistory(JSON.parse(saved));
    } catch { /* ignore */ }
  }, []);

  const filteredHistory = history.filter(h => h.type === searchType);

  const deleteItem = (value: string) => {
    const updated = history.filter(h => h.value !== value);
    setHistory(updated);
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
    if (updated.filter(h => h.type === searchType).length === 0) {
      setShowHistory(false);
    }
  };

  const openHistory = (inputValue: string) => {
    if (!inputValue && filteredHistory.length > 0) setShowHistory(true);
  };

  const closeHistory = () => setShowHistory(false);

  const hideOnInput = (value: string) => {
    if (value) setShowHistory(false);
  };

  return { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem };
};
