/**
 * useAnalytics Hook
 *
 * Hook for tracking analytics events with the Seekora SDK.
 * Supports Analytics V3 payload fields (event_ts, anonymous_id, orgcode, xstoreid);
 * the SDK sends both legacy and v3 fields for backend compatibility.
 */
import { useCallback } from 'react';
import { log } from '@seekora-ai/ui-sdk-core';
export const useAnalytics = ({ client, enabled = true, }) => {
    const trackEvent = useCallback(async (eventType, payload, context) => {
        if (!enabled)
            return;
        try {
            const eventPayload = {
                event_name: eventType,
                ...payload,
            };
            await client.trackEvent?.(eventPayload, context);
        }
        catch (err) {
            log.error('Failed to track event:', err);
        }
    }, [client, enabled]);
    const trackClick = useCallback(async (resultId, result, context, position) => {
        if (!enabled)
            return;
        const pos = position ?? 0;
        if (client.trackClick) {
            await client.trackClick(resultId, pos, context);
        }
        else {
            await trackEvent('product_click', {
                clicked_item_id: resultId,
                metadata: { result, ...(position !== undefined && { position: pos }) },
            }, context);
        }
    }, [client, trackEvent, enabled]);
    const trackConversion = useCallback(async (resultId, result, value, currency, context) => {
        if (!enabled)
            return;
        await trackEvent('conversion', {
            clicked_item_id: resultId,
            value: value,
            currency: currency,
            metadata: {
                result: result,
            },
        }, context);
    }, [trackEvent, enabled]);
    const trackBatch = useCallback(async (events, context) => {
        if (!enabled || events.length === 0)
            return;
        try {
            await client.trackEvents?.(events, context);
        }
        catch (err) {
            log.error('Failed to track batch events:', err);
        }
    }, [client, enabled]);
    return {
        trackEvent,
        trackClick,
        trackConversion,
        trackBatch,
    };
};
