import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { apiClient } from '@/api/client';

export function useAIContext(entityType?: string, entityId?: string, entityData?: any) {
  const location = useLocation();
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      apiClient.post('/ai-proactive/context', {
        page: location.pathname,
        entity_type: entityType,
        entity_id: entityId,
        entity_data: entityData,
      }).catch(() => {}); // Silent fail, don't bother user
    }, 500); // Debounce 500ms

    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [location.pathname, entityType, entityId, entityData]);
}
