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

export interface HistoryItem {
  id: string;
  title: string;
  path: string;
  category: string;
  viewedAt: number;
}

const STORAGE_KEY = 'codigo0_history';
const MAX_ITEMS = 20;

export function useHistory() {
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      try {
        setHistory(JSON.parse(stored));
      } catch (e) {
        console.error('Error loading history:', e);
      }
    }
    setLoading(false);
  }, []);

  const save = useCallback((items: HistoryItem[]) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
    setHistory(items);
  }, []);

  const addToHistory = useCallback((item: Omit<HistoryItem, 'viewedAt'>) => {
    const newItem: HistoryItem = {
      ...item,
      viewedAt: Date.now(),
    };
    
    const filtered = history.filter(h => h.id !== item.id);
    const updated = [newItem, ...filtered].slice(0, MAX_ITEMS);
    save(updated);
  }, [history, save]);

  const removeFromHistory = useCallback((id: string) => {
    save(history.filter(h => h.id !== id));
  }, [history, save]);

  const clearHistory = useCallback(() => {
    save([]);
  }, [save]);

  const getRecent = useCallback((limit: number = 5) => {
    return history.slice(0, limit);
  }, [history]);

  return {
    history,
    loading,
    addToHistory,
    removeFromHistory,
    clearHistory,
    getRecent,
  };
}
