/**
 * withAnalytics – HOC that wraps any React component to inject analytics tracking
 */
import React, { useRef, useEffect, useCallback } from 'react';
import { log } from '@seekora-ai/ui-sdk-core';
export function withAnalytics(Component, config = {}) {
    const { trackClick = true, trackImpression = false, clickEventName = 'product.click', getProductFromProps = () => null, getPositionFromProps = () => 0, } = config;
    const displayName = Component.displayName || Component.name || 'Component';
    const Wrapped = React.forwardRef((props, ref) => {
        const { seekoraClient, seekoraContext, ...rest } = props;
        const containerRef = useRef(null);
        const impressionTrackedRef = useRef(false);
        const product = getProductFromProps(rest);
        const position = getPositionFromProps(rest);
        const sendEvent = useCallback(async (eventName, metadata) => {
            if (!seekoraClient)
                return;
            try {
                await seekoraClient.trackEvent?.({
                    event_name: eventName,
                    metadata: {
                        product_id: product?.id || product?.objectID,
                        product_title: product?.title || product?.name,
                        product_price: product?.price,
                        position,
                        timestamp: Date.now(),
                        source: 'with_analytics_hoc',
                        ...metadata,
                    },
                }, seekoraContext);
            }
            catch (error) {
                log.warn(`withAnalytics: Failed to track ${eventName}`, { error });
            }
        }, [seekoraClient, seekoraContext, product, position]);
        const handleClick = useCallback(() => {
            if (!trackClick || !product)
                return;
            sendEvent(clickEventName, {});
            if (seekoraClient?.trackClick && product) {
                Promise.resolve(seekoraClient.trackClick(product.id || product.objectID || '', position + 1, seekoraContext)).catch(() => { });
            }
        }, [trackClick, product, sendEvent, seekoraClient, seekoraContext, position]);
        // Impression tracking
        useEffect(() => {
            if (!trackImpression || !seekoraClient || !containerRef.current || impressionTrackedRef.current)
                return;
            if (typeof IntersectionObserver === 'undefined')
                return;
            const observer = new IntersectionObserver((entries) => {
                for (const entry of entries) {
                    if (entry.isIntersecting && !impressionTrackedRef.current) {
                        impressionTrackedRef.current = true;
                        sendEvent('product.impression', {});
                        observer.disconnect();
                    }
                }
            }, { threshold: 0.5 });
            observer.observe(containerRef.current);
            return () => observer.disconnect();
        }, [trackImpression, seekoraClient, sendEvent]);
        return (React.createElement("div", { ref: (node) => {
                containerRef.current = node;
                if (typeof ref === 'function')
                    ref(node);
                else if (ref)
                    ref.current = node;
            }, onClick: handleClick, style: { display: 'contents' } },
            React.createElement(Component, { ...rest })));
    });
    Wrapped.displayName = `withAnalytics(${displayName})`;
    return Wrapped;
}
