import { useState, useCallback } from 'react';
import { captureCaught } from '@/lib/observability';

const STORAGE_KEY = 'md:recent-searches';
const MAX_ITEMS = 6;

function readFromStorage(): string[] {
  if (typeof window === 'undefined') return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw) as unknown;
    if (!Array.isArray(parsed)) return [];
    return parsed.filter((s): s is string => typeof s === 'string').slice(0, MAX_ITEMS);
  } catch (err) {
    captureCaught(err, { scope: 'useRecentSearches.readFromStorage', severity: 'warning' });
    return [];
  }
}

function writeToStorage(searches: string[]): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(searches));
  } catch (err) {
    captureCaught(err, { scope: 'useRecentSearches.writeToStorage', severity: 'warning' });
  }
}

export function useRecentSearches() {
  // Init to [] for SSR/hydration parity — lazy initializer reads localStorage during
  // hydration but SSR render had window=undefined → [] → mismatch (React #418).
  const [searches, setSearches] = useState<string[]>(readFromStorage);

  const add = useCallback((query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return;
    setSearches((prev) => {
      const deduped = [trimmed, ...prev.filter((s) => s !== trimmed)].slice(0, MAX_ITEMS);
      writeToStorage(deduped);
      return deduped;
    });
  }, []);

  const remove = useCallback((query: string) => {
    setSearches((prev) => {
      const next = prev.filter((s) => s !== query);
      writeToStorage(next);
      return next;
    });
  }, []);

  const clear = useCallback(() => {
    setSearches([]);
    writeToStorage([]);
  }, []);

  return { searches, add, remove, clear };
}

export const recentSearchesStorage = {
  maxItems: MAX_ITEMS,
  storageKey: STORAGE_KEY,
} as const;
