"use client"
import { useEffect, useState } from "react";

export default function WebSearchPage({ searchParams }) {
  const [aiResponse, setAiResponse] = useState(null);
  const startIndex = searchParams.start || "1";

  useEffect(() => {
    const url = new URL('/api/llm', window.location.origin);
    url.searchParams.append('question', searchParams.searchTerm);
    url.searchParams.append('startIndex', startIndex);
  
    const openaiRes = new EventSource(url);

    // Listen for AI responses and append to state
    openaiRes.onmessage = function(event) {
        setAiResponse(aiResponse => aiResponse + event.data);
    };
  
    // Close connection when component unmounts
    return () => {
      openaiRes.close();
    };
  }, [searchParams, startIndex]);

  
  return <>{aiResponse ? JSON.stringify(aiResponse) : 'Loading...'}</>;
}
