import type { WidgetConfig, Doctor, TimeSlot } from './types'; let baseUrl = ''; let widgetKey = ''; export const initApi = (url: string, key: string) => { baseUrl = url; widgetKey = key; }; const headers = () => ({ 'Content-Type': 'application/json', 'X-Widget-Key': widgetKey, }); export const fetchInit = async (): Promise => { const res = await fetch(`${baseUrl}/api/widget/init?key=${widgetKey}`); if (!res.ok) throw new Error('Widget init failed'); return res.json(); }; export const fetchDoctors = async (): Promise => { const res = await fetch(`${baseUrl}/api/widget/doctors?key=${widgetKey}`); if (!res.ok) throw new Error('Failed to load doctors'); return res.json(); }; export const fetchSlots = async (doctorId: string, date: string): Promise => { const res = await fetch(`${baseUrl}/api/widget/slots?key=${widgetKey}&doctorId=${doctorId}&date=${date}`); if (!res.ok) throw new Error('Failed to load slots'); return res.json(); }; export const submitBooking = async (data: any): Promise<{ appointmentId: string; reference: string }> => { const res = await fetch(`${baseUrl}/api/widget/book?key=${widgetKey}`, { method: 'POST', headers: headers(), body: JSON.stringify(data), }); if (!res.ok) throw new Error('Booking failed'); return res.json(); }; export const submitLead = async (data: any): Promise<{ leadId: string }> => { const res = await fetch(`${baseUrl}/api/widget/lead?key=${widgetKey}`, { method: 'POST', headers: headers(), body: JSON.stringify(data), }); if (!res.ok) throw new Error('Submission failed'); return res.json(); }; export const startChatSession = async (name: string, phone: string): Promise<{ leadId: string }> => { const res = await fetch(`${baseUrl}/api/widget/chat-start?key=${widgetKey}`, { method: 'POST', headers: headers(), body: JSON.stringify({ name, phone }), }); if (!res.ok) throw new Error('Chat start failed'); return res.json(); }; // Send the simplified {role, content: string}[] history to the backend. // Backend responds with an SSE stream of UIMessageChunk events. // branch (when set) is injected into the system prompt so the AI scopes // tool calls to that branch. type OutboundMessage = { role: 'user' | 'assistant'; content: string }; export const streamChat = async ( leadId: string, messages: OutboundMessage[], branch: string | null, ): Promise> => { const res = await fetch(`${baseUrl}/api/widget/chat?key=${widgetKey}`, { method: 'POST', headers: headers(), body: JSON.stringify({ leadId, messages, branch }), }); if (!res.ok || !res.body) throw new Error('Chat failed'); return res.body; };