/**
 * Hook to manage recent searches in localStorage.
 */

import { useState, useCallback, useEffect } from 'react';

export interface RecentSearch {
  query: string;
  type: 'block' | 'transaction' | 'address' | 'unknown';
  timestamp: number;
}

const STORAGE_KEY = 'synor-recent-searches';
const MAX_RECENT_SEARCHES = 10;

function getStoredSearches(): RecentSearch[] {
  if (typeof window === 'undefined') return [];
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch {
    return [];
  }
}

function storeSearches(searches: RecentSearch[]): void {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(searches));
  } catch {
    // Ignore storage errors
  }
}

function detectSearchType(query: string): RecentSearch['type'] {
  const trimmed = query.trim();

  // Address: starts with synor1 (Bech32)
  if (trimmed.startsWith('synor1')) {
    return 'address';
  }

  // Block or Transaction hash: 64 hex characters
  if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
    // Could be either - default to block
    return 'block';
  }

  // Block number
  if (/^\d+$/.test(trimmed)) {
    return 'block';
  }

  return 'unknown';
}

export function useRecentSearches() {
  const [searches, setSearches] = useState<RecentSearch[]>(() => getStoredSearches());

  // Sync with localStorage on mount
  useEffect(() => {
    setSearches(getStoredSearches());
  }, []);

  const addSearch = useCallback((query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return;

    setSearches((prev) => {
      // Remove existing entry with same query
      const filtered = prev.filter((s) => s.query !== trimmed);

      // Add new entry at the beginning
      const newSearch: RecentSearch = {
        query: trimmed,
        type: detectSearchType(trimmed),
        timestamp: Date.now(),
      };

      const updated = [newSearch, ...filtered].slice(0, MAX_RECENT_SEARCHES);
      storeSearches(updated);
      return updated;
    });
  }, []);

  const removeSearch = useCallback((query: string) => {
    setSearches((prev) => {
      const updated = prev.filter((s) => s.query !== query);
      storeSearches(updated);
      return updated;
    });
  }, []);

  const clearSearches = useCallback(() => {
    setSearches([]);
    storeSearches([]);
  }, []);

  return {
    searches,
    addSearch,
    removeSearch,
    clearSearches,
  };
}

export default useRecentSearches;
