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

export interface FavoriteItem {
  id: string;
  title: string;
  path: string;
  category: string;
  addedAt: number;
}

const STORAGE_KEY = 'codigo0_favorites';

export function useFavorites() {
  const [favorites, setFavorites] = useState<FavoriteItem[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  const addFavorite = useCallback((item: Omit<FavoriteItem, 'addedAt'>) => {
    const newItem: FavoriteItem = {
      ...item,
      addedAt: Date.now(),
    };
    const exists = favorites.some(f => f.id === item.id);
    if (!exists) {
      save([newItem, ...favorites]);
    }
  }, [favorites, save]);

  const removeFavorite = useCallback((id: string) => {
    save(favorites.filter(f => f.id !== id));
  }, [favorites, save]);

  const toggleFavorite = useCallback((item: Omit<FavoriteItem, 'addedAt'>) => {
    const exists = favorites.some(f => f.id === item.id);
    if (exists) {
      removeFavorite(item.id);
    } else {
      addFavorite(item);
    }
  }, [favorites, addFavorite, removeFavorite]);

  const isFavorite = useCallback((id: string) => {
    return favorites.some(f => f.id === id);
  }, [favorites]);

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

  return {
    favorites,
    loading,
    addFavorite,
    removeFavorite,
    toggleFavorite,
    isFavorite,
    clearAll,
  };
}
