import { useCallback, useRef, useMemo } from "react"; import type { WidgetCallbacks, WidgetData } from "../domain"; import { WidgetEventService } from "../services/WidgetEventService"; import { WidgetValidationService } from "../services/WidgetValidationService"; import type { WidgetStateManager } from "../services/WidgetStateManager"; interface UseWidgetServicesParams { hide: () => void; resize: (height: string) => void; userId: string; callbacks?: WidgetCallbacks; data: WidgetData; stateManager: WidgetStateManager; } export const useWidgetServices = ({ hide, resize, userId, callbacks, data, stateManager }: UseWidgetServicesParams) => { const eventServiceRef = useRef(null as WidgetEventService | null); if (!eventServiceRef.current) { eventServiceRef.current = new WidgetEventService(hide, resize, userId, data?.transaction_id, callbacks, stateManager); } const validationServiceRef = useRef(null as WidgetValidationService | null); if (!validationServiceRef.current) { validationServiceRef.current = new WidgetValidationService(stateManager); } const isForm = useMemo(() => Boolean(data?.form_id), [data?.form_id]); const handleWebViewMessage = useCallback(async (message: string) => { if (message && message.length > 0) { try { await eventServiceRef.current!.handleMessage(message, isForm); } catch (error) { console.error("[useWidgetServices] Error handling widget message:", error); } } }, []); return { eventService: eventServiceRef.current, validationService: validationServiceRef.current, handleWebViewMessage, }; };