/**
 * Custom hook for managing school comparison state
 * Uses shared context for real-time updates across components
 */

'use client';

import useSWR from 'swr';
import { fetcher } from '@/lib/api';
import { useComparisonContext } from '@/context/ComparisonContext';
import type { ComparisonResponse } from '@/lib/types';

export function useComparison() {
  const {
    selectedSchools,
    addSchool,
    removeSchool,
    clearAll,
    isSelected,
    canAddMore,
    isInitialized,
  } = useComparisonContext();

  // Fetch comparison data for selected schools
  const urns = selectedSchools.map((s) => s.urn).join(',');
  const { data, error, isLoading, mutate } = useSWR<ComparisonResponse>(
    selectedSchools.length > 0 ? `/compare?urns=${urns}` : null,
    fetcher,
    {
      revalidateOnFocus: false,
      dedupingInterval: 10000,
    }
  );

  return {
    selectedSchools,
    comparisonData: data?.comparison,
    isLoading,
    error,
    addSchool,
    removeSchool,
    clearAll,
    isSelected,
    canAddMore,
    isInitialized,
    mutate,
  };
}
