/**
 * useProductAnalytics – analytics event binding hook for custom components
 *
 * Returns event handler props ready to spread onto any element, plus imperative
 * tracking methods. Builds on existing useAnalytics infrastructure.
 */
import { useCallback, useRef, useEffect } from 'react';
import { log } from '@seekora-ai/ui-sdk-core';
export function useProductAnalytics({ client, product, position = 0, section, tabId, query, context, enabled = true, }) {
    const impressionTrackedRef = useRef(false);
    const observerRef = useRef(null);
    const elementRef = useRef(null);
    const productId = product.id || product.objectID || '';
    const sendEvent = useCallback(async (eventName, metadata) => {
        if (!enabled || !client)
            return;
        try {
            await client.trackEvent?.({
                event_name: eventName,
                metadata: {
                    product_id: productId,
                    product_title: product.title || product.name,
                    product_price: product.price,
                    position,
                    section,
                    tab_id: tabId,
                    original_query: query,
                    timestamp: Date.now(),
                    source: 'product_analytics',
                    ...metadata,
                },
            }, context);
            log.verbose(`ProductAnalytics: ${eventName}`, metadata);
        }
        catch (error) {
            log.warn(`Failed to track ${eventName}`, { error });
        }
    }, [client, enabled, productId, product, position, section, tabId, query, context]);
    const trackClick = useCallback(() => {
        sendEvent('product.click', {});
        // Also fire via client.trackClick for V3 compat
        if (client?.trackClick) {
            Promise.resolve(client.trackClick(productId, position + 1, context)).catch(() => { });
        }
    }, [sendEvent, client, productId, position, context]);
    const trackVariantSelect = useCallback((optionName, value) => {
        sendEvent('product.variant_select', {
            option_name: optionName,
            option_value: value,
        });
    }, [sendEvent]);
    const trackAddToCart = useCallback((variant) => {
        sendEvent('product.add_to_cart', {
            variant_id: variant?.id,
            variant_sku: variant?.sku,
            variant_title: variant?.title,
            variant_price: variant?.price,
        });
    }, [sendEvent]);
    const trackCustomEvent = useCallback((eventName, metadata) => {
        sendEvent(eventName, metadata ?? {});
    }, [sendEvent]);
    // Impression tracking via IntersectionObserver
    const impressionRef = useCallback((node) => {
        // Cleanup previous observer
        if (observerRef.current) {
            observerRef.current.disconnect();
            observerRef.current = null;
        }
        elementRef.current = node;
        if (!node || !enabled || impressionTrackedRef.current)
            return;
        if (typeof IntersectionObserver === 'undefined')
            return;
        observerRef.current = new IntersectionObserver((entries) => {
            for (const entry of entries) {
                if (entry.isIntersecting && !impressionTrackedRef.current) {
                    impressionTrackedRef.current = true;
                    sendEvent('product.impression', {});
                    observerRef.current?.disconnect();
                }
            }
        }, { threshold: 0.5 });
        observerRef.current.observe(node);
    }, [enabled, sendEvent]);
    // Cleanup on unmount
    useEffect(() => {
        return () => {
            observerRef.current?.disconnect();
        };
    }, []);
    const clickProps = {
        onClick: () => trackClick(),
        'data-seekora-product-id': productId,
        'data-seekora-position': position,
    };
    const variantSelectProps = (optionName, value) => ({
        onClick: () => trackVariantSelect(optionName, value),
        'data-seekora-variant-option': optionName,
        'data-seekora-variant-value': value,
    });
    const addToCartProps = (variant) => ({
        onClick: () => trackAddToCart(variant),
        'data-seekora-action': 'add-to-cart',
    });
    return {
        clickProps,
        variantSelectProps,
        addToCartProps,
        impressionRef,
        trackClick,
        trackVariantSelect,
        trackAddToCart,
        trackCustomEvent,
    };
}
