import { useCallback, useEffect, useRef } from 'react';
import { useUserState } from './useUserState';
import type { ModelOption } from './useModels';

const MAX_RECENTS = 5;

export const useRecentModels = () => {
  const [recents, setRecents] = useUserState<ModelOption[]>('recentModels', []);
  const migrated = useRef(false);

  // One-time migration from localStorage
  useEffect(() => {
    if (migrated.current) return;
    migrated.current = true;

    const raw = localStorage.getItem('OC_RECENT_MODELS');
    if (!raw) return;

    try {
      const parsed = JSON.parse(raw) as ModelOption[];
      if (Array.isArray(parsed) && parsed.length > 0) {
        setRecents(parsed.slice(0, MAX_RECENTS));
        localStorage.removeItem('OC_RECENT_MODELS');
      }
    } catch {
      localStorage.removeItem('OC_RECENT_MODELS');
    }
  }, []);

  const addRecent = useCallback(
    (model: ModelOption) => {
      setRecents((prev) => {
        const filtered = prev.filter((m) => m.id !== model.id);
        return [model, ...filtered].slice(0, MAX_RECENTS);
      });
    },
    [setRecents],
  );

  return { recents, addRecent };
};
